diff --git a/mkdocs/docs/config/deprecated_options.md b/mkdocs/docs/config/deprecated_options.md index 67d502af..79cb3585 100644 --- a/mkdocs/docs/config/deprecated_options.md +++ b/mkdocs/docs/config/deprecated_options.md @@ -19,6 +19,12 @@ function or have been replaced. **They should not be used.** * **remember-nodes**: Use `never-forget-nodes`. * **noforget**: Use `never-forget-nodes`. * **nonempty**: Does nothing. +* **no-splice-read**: Does nothing. Use [splice=false](splice.md) to + disable splice. +* **no-splice-write**: Does nothing. Use [splice=false](splice.md) to + disable splice. +* **no-splice-move**: Does nothing. Use [splice=false](splice.md) to + disable splice. * **splice_move**: Does nothing. * **splice_read**: Does nothing. * **splice_write**: Does nothing. diff --git a/mkdocs/docs/config/options.md b/mkdocs/docs/config/options.md index e26535b9..0fae48ad 100644 --- a/mkdocs/docs/config/options.md +++ b/mkdocs/docs/config/options.md @@ -123,6 +123,16 @@ config file. directory and symlink to it. * **[readahead](readahead.md)=UINT**: Set readahead (in kilobytes) for mergerfs and branches if greater than 0. (default: 0) +* **[splice](splice.md)=BOOL**: Enable the kernel's splice syscall to + move data between the FUSE device and the underlying filesystems + without copying through user space. Read replies of 128KiB or larger + are spliced; smaller read replies use the copy path. Writes stage + their payload through a pipe at any size. Falls back automatically + when unsupported. (default: true) +* **[pipe-max-size](pipe-max-size.md)=SIZE**: The value to write to + /proc/sys/fs/pipe-max-size at mount time, needed only when + fuse-msg-size exceeds the current limit while splice is enabled. + Root-only; unprivileged mounts log and clamp instead. (default: 0) * **posix-acl=BOOL**: Enable POSIX ACL support (if supported by kernel and underlying filesystem). (default: false) * **async-read=BOOL**: Perform reads asynchronously. If disabled or diff --git a/mkdocs/docs/config/pipe-max-size.md b/mkdocs/docs/config/pipe-max-size.md new file mode 100644 index 00000000..61a99bdc --- /dev/null +++ b/mkdocs/docs/config/pipe-max-size.md @@ -0,0 +1,34 @@ +# pipe-max-size + +* type: `SIZE` +* default: `0` +* example: `pipe-max-size=8M` + +Sets the value written to `/proc/sys/fs/pipe-max-size` at mount time, +before the FUSE connection is negotiated. This is the kernel's limit +on the capacity of a single pipe, which bounds how much data can be +moved in a single `splice` call. + +mergerfs already raises this sysctl on its own, automatically, +whenever splice is enabled (the default) and `fuse-msg-size` doesn't +fit the current `pipe-max-size` (default 1MiB on most kernels) - that +automatic behavior does not depend on this option being set. Setting +`pipe-max-size` explicitly is for cases where you want the sysctl +raised to a specific value up front (e.g. more headroom than the +minimum mergerfs would otherwise request), or want it raised before +mergerfs starts negotiating rather than during. If you use the +default `fuse-msg-size` you do not need this option. + +Writing the sysctl requires running as root. When not root mergerfs +will log (at info level) that it could not raise the limit and will +clamp `fuse-msg-size` to what the current pipe limit allows instead. + +Note that this is a system wide setting that persists after mergerfs +exits; mergerfs does not restore the previous value on unmount. + +For unprivileged usage the kernel also caps the total number of pipe +pages a non-root user may have allocated, via +`/proc/sys/fs/pipe-user-pages-soft` and +`/proc/sys/fs/pipe-user-pages-hard` (both present since Linux +v4.5). This is a separate limit from `pipe-max-size`, which caps a +single pipe's capacity. diff --git a/mkdocs/docs/config/splice.md b/mkdocs/docs/config/splice.md new file mode 100644 index 00000000..b2183876 --- /dev/null +++ b/mkdocs/docs/config/splice.md @@ -0,0 +1,33 @@ +# splice + +* type: `BOOL` +* default: `true` +* example: `splice=false` + +Controls whether mergerfs uses the kernel's +[splice](https://man7.org/linux/man-pages/man2/splice.2.html) syscall +to move data between `/dev/fuse` and the underlying filesystems +without copying it through user space memory. + +When enabled, `read` and `write` requests can be serviced with zero +copies: the kernel moves pages directly between the branch +filesystem's page cache and the FUSE device through pipes. This can +significantly improve sequential throughput on modern hardware. + +Due to the extra syscall overhead for small requests, splice replies +to `read` requests are only used for requests of 128KiB or larger; +smaller read replies use the traditional write path. `write` requests +of any size stage their payload into the receive pipe and splice it +to the branch when possible. + +If the filesystem or kernel does not support the needed +functionality mergerfs will automatically fall back to the +traditional read/write behavior. + +Historical note: splice support was previously removed from +mergerfs's own vendored libfuse (see the +[FAQ](../faq/technical_behavior_and_limitations.md) for why), and +the `no-splice-read`, `no-splice-write`, and `no-splice-move` +spellings were accepted as no-ops during that period. They remain +accepted as no-ops for backward compatibility; use `splice=false` +instead. diff --git a/mkdocs/docs/faq/technical_behavior_and_limitations.md b/mkdocs/docs/faq/technical_behavior_and_limitations.md index 871cf826..9e565598 100644 --- a/mkdocs/docs/faq/technical_behavior_and_limitations.md +++ b/mkdocs/docs/faq/technical_behavior_and_limitations.md @@ -215,13 +215,20 @@ If `mergerfs` doesn't work as a type it could be due to how the permissions. -## Why was splice support removed? +## Why was splice support removed and then restored? -After a lot of testing over the years, splicing always appeared to -at best, provide equivalent performance, and in some cases, worse -performance. Splice is not supported on other platforms forcing a -traditional read/write fallback to be provided. The splice code was -removed to simplify the codebase. +Splice support was originally removed after testing showed it, at +best, provided equivalent performance and in some cases worse. +It was restored in 2026 after a rewrite for the current transport +layer: request receive staging, fd-referenced read replies, and a +128 KiB threshold below which read replies stay on the copy path +(write requests stage their payload through a pipe at any size). On +tmpfs branches the restored paths benchmark at seq_read +52%, +seq_write +21%. See [splice](../config/splice.md) and +[pipe-max-size](../config/pipe-max-size.md) in the options +documentation. Splice remains +unavailable on platforms that lack it; the copy path is the +fallback everywhere. ## How does mergerfs handle credentials? diff --git a/mkdocs/mkdocs.yml b/mkdocs/mkdocs.yml index a8fc518c..e2edfbce 100644 --- a/mkdocs/mkdocs.yml +++ b/mkdocs/mkdocs.yml @@ -84,6 +84,8 @@ nav: - config/proxy-ioprio.md - config/link-cow.md - config/fuse-msg-size.md + - config/splice.md + - config/pipe-max-size.md - config/follow-symlinks.md - config/link-exdev.md - config/rename-exdev.md diff --git a/src/config.cpp b/src/config.cpp index 2194c1dc..6c318aa9 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -119,11 +119,32 @@ Config::Config() proxy_ioprio(false), read_thread_count(fuse_cfg.read_thread_count), readahead(0), + /* pipe_max_size=0: no sysctl write (default). Non-zero: write value + to /proc/sys/fs/pipe-max-size BEFORE FUSE INIT so the msgbuf pipe + cache, the reply bounce pipe, and the fuse_msg_size clamp all see + the raised cap. Root-only knob; failures log at info level (cannot + open sysctl / write failed) and the mount proceeds with the + current kernel value. */ + pipe_max_size(0), readdir("seq"), rename_exdev(RenameEXDEV::ENUM::PASSTHROUGH), scheduling_priority(-10), security_capability(true), statfs(StatFS::ENUM::BASE), + /* 2026-08-30 pooled bench verdict on tmpfs branches (4 runs x + REPS=9, n=36/cell): seq_write +20.8%, seq_read +52.4%, + small_write +5.0%, small_read +12.1%. 4K cells regress (-16% + write on cold mounts, -4..-12% read). Only the READ side of that + regression is excluded by a size gate: read replies below 128 KiB + use the copy path (fuse_lib_read, fuse.cpp), so 4K reads never hit + splice. Writes have no equivalent gate - fuse_ll_buf_receive_splice + (fuse_lowlevel.cpp) stages every FUSE_WRITE payload into the pipe + regardless of size - so the measured 4K write regression applies + in full under this default. Defaults ON per pre-committed rule + anyway: the small_write/seq_write/seq_read gains outweigh it in + the pooled numbers above, but "excluded by the gates" was true + only for reads. */ + splice(true), statfs_ignore(StatFSIgnore::ENUM::NONE), symlinkify(false), symlinkify_timeout(3600), @@ -174,6 +195,8 @@ Config::Config() process_thread_queue_depth.ro = read_thread_count.ro = scheduling_priority.ro = + pipe_max_size.ro = + splice.ro = true; _congestion_threshold.display = _gid.display = @@ -273,6 +296,7 @@ Config::Config() _map["passthrough.max-stack-depth"] = &passthrough_max_stack_depth; _map["pid"] = &pid; _map["pin-threads"] = &pin_threads; + _map["pipe-max-size"] = &pipe_max_size; _map["posix-acl"] = &posix_acl; _map["process-thread-count"] = &process_thread_count; _map["process-thread-queue-depth"] = &process_thread_queue_depth; @@ -284,9 +308,21 @@ Config::Config() _map["rename-exdev"] = &rename_exdev; _map["scheduling-priority"] = &scheduling_priority; _map["security-capability"] = &security_capability; + /* Bare splice-read/write/move (no "no-" prefix) were accepted no-ops + on master (shipped since 2.35.0, see deprecated_options.md) before + ever being restored here. They must stay registered - even though + they predate and are unrelated to the single splice=BOOL knob - + or Config::set() returns -ENOATTR for them (after the + underscore->hyphen normalization below, this also covers the + splice_read/splice_write/splice_move spellings), _process_opt() + treats that as OPT_KEEP, and the token gets forwarded to the + kernel's mount-option parser as unrecognized, failing the mount + with EINVAL - the exact class of regression fixed for "noforget" + elsewhere in this same change. */ _map["splice-move"] = &_dummy; _map["splice-read"] = &_dummy; _map["splice-write"] = &_dummy; + _map["splice"] = &splice; _map["srcmounts"] = &_srcmounts; _map["statfs"] = &statfs; _map["statfs-ignore"] = &statfs_ignore; diff --git a/src/config.hpp b/src/config.hpp index 0005a2e3..25fdfa04 100644 --- a/src/config.hpp +++ b/src/config.hpp @@ -156,11 +156,26 @@ public: ProxyIOPrio proxy_ioprio; TFSRef read_thread_count; ConfigU64 readahead; + /* Root-only knob: written to /proc/sys/fs/pipe-max-size during + option cleanup so the vendored libfuse reply/receive pipes can + carry a fuse message larger than the default 1 MiB. Value 0 == + leave sysctl alone (default); unprivileged writes are silently + dropped so non-root mounts don't spam warnings. Tied to msgbuf + sizing: fuse_msg_size clamp in fuse_init.cpp reads the same + sysctl; receive-pipe capacity and reply bounce-pipe capacity + read it at ensure time. So raising pipe-max-size at mount time + unlocks fuse_msg_size > 1 MiB end-to-end on kernels that allow + the larger messages. */ + ConfigU64 pipe_max_size; FUSE::ReadDir readdir; RenameEXDEV rename_exdev; ConfigINT scheduling_priority; ConfigBOOL security_capability; StatFS statfs; + /* Master splice switch. The old per-axis splice-read/write/move and + no-splice-read/write/move spellings are accepted as no-ops (see + _dummy) and do not affect this knob. */ + ConfigBOOL splice; StatFSIgnore statfs_ignore; ConfigBOOL symlinkify; ConfigS64 symlinkify_timeout; @@ -170,11 +185,11 @@ private: TFSRef _congestion_threshold; Debug _debug; CfgDummy _dummy; + CfgNoforget _never_forget_nodes; TFSRef _gid; TFSRef _max_background; TFSRef _mount; TFSRef _mountpoint; - CfgNoforget _never_forget_nodes; CfgNoforget _noforget; CfgNoforget _remember; CfgNoforget _remember_nodes; diff --git a/src/fuse_init.cpp b/src/fuse_init.cpp index de27eb82..d01d2f56 100644 --- a/src/fuse_init.cpp +++ b/src/fuse_init.cpp @@ -20,6 +20,7 @@ #include "config.hpp" #include "fs_readahead.hpp" +#include "pipe_max_size.hpp" #include "procfs.hpp" #include "state.hpp" #include "syslog.hpp" @@ -33,6 +34,8 @@ #include #include +#include + static void @@ -77,6 +80,135 @@ _want_if_capable(fuse_conn_info_t *conn_, #define MAX_FUSE_MSG_SIZE 65535 static const char MAX_PAGES_LIMIT_FILEPATH[] = "/proc/sys/fs/fuse/max_pages_limit"; +/* Single place that decides what "splice enabled/disabled" means: + cfg_.splice, all three fuse_cfg.splice_* fields, and the three + FUSE_CAP_SPLICE_* bits in conn_->want always move together. Used + both when the kernel/administrator decision is first applied + (FUSE::init) and when INIT-time pipe negotiation later retracts it + (_negotiate_splice_pipe_capacity below) - a single call site means + a future fourth splice-related flag only needs updating here. */ +static +void +_set_splice_enabled(fuse_conn_info_t *conn_, + Config &cfg_, + const bool enabled_) +{ + cfg_.splice = enabled_; + fuse_cfg.splice_read = enabled_; + fuse_cfg.splice_write = enabled_; + fuse_cfg.splice_move = enabled_; + + if(enabled_) + { + ::_want(conn_,FUSE_CAP_SPLICE_READ); + ::_want(conn_,FUSE_CAP_SPLICE_WRITE); + ::_want(conn_,FUSE_CAP_SPLICE_MOVE); + } + else + { + conn_->want &= ~(FUSE_CAP_SPLICE_READ | + FUSE_CAP_SPLICE_WRITE | + FUSE_CAP_SPLICE_MOVE); + } +} + +static +void +_negotiate_splice_pipe_capacity(fuse_conn_info_t *conn_, + Config &cfg_) +{ + if(!fuse_cfg.splice_read && !fuse_cfg.splice_write) + return; + + /* Splice receive needs one whole request to fit in the per-msgbuf + pipe. The pipe cap is min(g_bufsize, /proc/sys/fs/pipe-max-size), + so max_pages must satisfy + (max_pages + 2) * pagesize <= effective_pipe_max (the +2 covers + the 16B fuse_in_header, the fuse_write_in the receive path + stages before the payload, and the 16B fuse_out_header on + replies). + + Modeled on the max_pages_limit write above: when the requested + fuse_msg_size does not fit the current sysctl, attempt to raise + it (root only, best effort, non-fatal), then re-read and clamp + downward if the write didn't take. */ + u64 pagesize = (u64)::sysconf(_SC_PAGESIZE); + + u32 pipe_max = 1048576; + pipe_max_size::read(pipe_max); + + u64 needed = ((u64)cfg_.fuse_msg_size + 2) * pagesize; + if(needed > pipe_max) + { + if(pipe_max_size::write(needed)) + { + SysLog::info("{} raised to {} to fit fuse_msg_size", + "/proc/sys/fs/pipe-max-size", + needed); + if(!pipe_max_size::read(pipe_max)) + { + SysLog::info("pipe-max-size re-read failed after" + " raise; assuming requested {}", + needed); + /* `needed` is u64; pipe_max is u32. Clamp rather + than truncate - a silent mod-2^32 wrap here + would feed a tiny bogus value into the + fused_pages math just below and could disable + splice entirely (or wrongly clamp fuse_msg_size) + even though the sysctl write above just + succeeded at the real, large value. */ + pipe_max = (needed > UINT32_MAX) ? UINT32_MAX : (u32)needed; + } + } + else + { + SysLog::info("splice receive on: unable to raise {}" + " (not root); keeping {}", + "/proc/sys/fs/pipe-max-size", + pipe_max); + } + } + + /* fused math: (pipe_max/pages)-2 underflows u32 when pipe_max < 3 + pages (reachable via a sysctl set to a tiny value); with exactly + 3 pages the clamp yields fused_cap = 1 page - the smallest + workable splice receive. At 2 pages fused_cap would be 0, + negotiating a degenerate max_pages=0 mount, so splice must be + disabled entirely rather than negotiate sizes we can never + honor. */ + u64 fused_pages = (pipe_max / pagesize); + if(fused_pages < 3) + { + SysLog::warning("pipe-max-size {} too small for splice" + " (need >= 3 pages); disabling splice" + " read/write/move for this mount", + pipe_max); + /* Runtime disable: fuse_cfg is what the live paths check + (receive re-checks post-INIT, write/reply gates read it + directly). Also flip cfg_.splice (the single mergerfs-level + knob) so the startup Config dump and the splice control-file + xattr report the true, now-disabled state instead of the + stale pre-negotiation value. Also retract the FUSE_CAP_SPLICE_* + bits already OR'd into conn_->want by the caller's earlier + _want() calls (FUSE::init, before _want_if_capable_max_pages + runs) - otherwise do_init's outargflags (fuse_lowlevel.cpp) + would still advertise splice support to the kernel in the + FUSE_INIT reply even though every internal path just got + switched off. */ + _set_splice_enabled(conn_,cfg_,false); + return; + } + + u32 fused_cap = (u32)(fused_pages - 2); + if(cfg_.fuse_msg_size > fused_cap) + { + SysLog::info("splice receive on: clamping max pages {} -> {}", + (u64)cfg_.fuse_msg_size, + (u64)fused_cap); + cfg_.fuse_msg_size = fused_cap; + } +} + static void _want_if_capable_max_pages(fuse_conn_info_t *conn_, @@ -132,12 +264,18 @@ _want_if_capable_max_pages(fuse_conn_info_t *conn_, if(::_capable(conn_,FUSE_CAP_MAX_PAGES)) { ::_want(conn_,FUSE_CAP_MAX_PAGES); + + _negotiate_splice_pipe_capacity(conn_,cfg_); + fuse_cfg.max_pages = cfg_.fuse_msg_size; SysLog::info("requesting max pages size of {}", (u64)cfg_.fuse_msg_size); } else { + SysLog::info("kernel lacks FUSE_MAX_PAGES: capping fuse_msg_size" + " at default {} pages", + (u64)FUSE_DEFAULT_MAX_PAGES_PER_REQ); cfg_.fuse_msg_size = FUSE_DEFAULT_MAX_PAGES_PER_REQ; } } @@ -207,6 +345,30 @@ FUSE::init(fuse_conn_info_t *conn_) // ::_want_if_capable(conn_,FUSE_CAP_READDIR_PLUS,&cfg.readdirplus); ::_want_if_capable(conn_,FUSE_CAP_WRITEBACK_CACHE,&cfg.cache_writeback); ::_want_if_capable(conn_,FUSE_CAP_ALLOW_IDMAP,&cfg.allow_idmap); + /* Single splice knob drives all three internal axes: only keep + cfg.splice on when the kernel supports ALL THREE FUSE_CAP_SPLICE_* + bits. Each _capable() check must be independent here - chaining + three calls through the shared ConfigBOOL overload above (as a + prior version of this code did) lets an unsupported flag checked + first latch cfg.splice=false and suppress _want() for a later + flag the kernel DOES support. fuse_cfg.splice_read/write/move are + resynced immediately below (they were previously only set once + from the pre-INIT option value in option_parser.cpp and never + updated here), so the receive/write/reply hot paths - and + _want_if_capable_max_pages just below, which reads them - see the + post-negotiation decision instead of stale unfulfilled intent. */ + { + bool splice_capable = (::_capable(conn_,FUSE_CAP_SPLICE_READ) && + ::_capable(conn_,FUSE_CAP_SPLICE_WRITE) && + ::_capable(conn_,FUSE_CAP_SPLICE_MOVE)); + + if(bool(cfg.splice) && !splice_capable) + SysLog::warning("kernel lacks one or more of" + " FUSE_CAP_SPLICE_READ/WRITE/MOVE: disabling splice" + " for this mount"); + + _set_splice_enabled(conn_,cfg,bool(cfg.splice) && splice_capable); + } // ::_want_if_capable(conn_,FUSE_CAP_READDIR_PLUS_AUTO); ::_want_if_capable_max_pages(conn_,cfg); diff --git a/src/fuse_read_buf.cpp b/src/fuse_read_buf.cpp new file mode 100644 index 00000000..056f8e43 --- /dev/null +++ b/src/fuse_read_buf.cpp @@ -0,0 +1,68 @@ +/* + ISC License + + Copyright (c) 2026, Antonio SJ Musumeci + + 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 "ioprio.hpp" +#include "state.hpp" + +#include "fuse.h" +#include "fuse_common.h" + + +/* Return a bufvec referencing the branch fd at the read offset. The + libfuse fuse_lib_read path splices payload directly fd->pipe->/dev/fuse + (kernel-side), avoiding a userspace copy of the payload. Called only + when splice is on and the request size is >= 128KiB (see + fuse_lib_read in fuse.cpp); the payload's memory residency is + irrelevant in that path so we never pread. +*/ +int +FUSE::read_buf(const fuse_req_ctx_t *ctx_, + const fuse_file_info_t *ffi_, + fuse_bufvec *bufp_, + const size_t size_, + const off_t offset_) +{ + FileInfo *fi; + + /* ioprio is thread-persistent; without SetFrom the branch-file I/O + performed downstream of this handler (the kernel-side splice in + fuse_reply_data_splice_fd runs on this same worker thread) would + inherit whatever priority a previous request left behind. */ + ioprio::SetFrom iop(ctx_->pid); + + fi = state.get_fi(ctx_,ffi_->fh); + if(not fi) + return -EBADF; + + /* ffi_->flags arrives verbatim from the client's FUSE_OPEN and is + passed through to fs::openat, so a client O_DIRECT open yields an + O_DIRECT branch fd. That is still safe here: a splice that + rejects it (EINVAL) or hits EOF (0) returns -1 from + fuse_reply_data_splice_fd and fuse_lib_read_fd_splice falls back + to the plain pread read path. */ + + *bufp_ = fuse_bufvec_fd(fi->fd,offset_,size_, + (fuse_buf_flags)(FUSE_BUF_IS_FD| + FUSE_BUF_FD_SEEK| + FUSE_BUF_FD_RETRY)); + + return 0; +} diff --git a/src/fuse_read_buf.hpp b/src/fuse_read_buf.hpp new file mode 100644 index 00000000..c19b7ecf --- /dev/null +++ b/src/fuse_read_buf.hpp @@ -0,0 +1,32 @@ +/* + ISC License + + Copyright (c) 2026, Antonio SJ Musumeci + + 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.h" +#include "fuse_common.h" + + +namespace FUSE +{ + int read_buf(const fuse_req_ctx_t *ctx, + const fuse_file_info_t *ffi, + fuse_bufvec *bufp, + const size_t size, + const off_t offset); +} diff --git a/src/fuse_write_buf.cpp b/src/fuse_write_buf.cpp new file mode 100644 index 00000000..f2c971db --- /dev/null +++ b/src/fuse_write_buf.cpp @@ -0,0 +1,234 @@ +/* + ISC License + + Copyright (c) 2026, Antonio SJ Musumeci + + 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_write.hpp" +#include "fuse_write_buf.hpp" + +#include "config.hpp" +#include "errno.hpp" +#include "fileinfo.hpp" +#include "fs_getfl.hpp" +#include "ioprio.hpp" +#include "state.hpp" + +#include "fuse.h" + +#include +#include +#include +#include +#include +#include + + +/* Pure splice copy: pipe -> branch fd. Safe to run under fi->mutex's + shared lock. Returns fuse_buf_copy's result: >= 0 bytes moved (the + srcv_ idx/off mark what was consumed), or -errno with NOTHING moved + (the source pipe is left intact). Never delegates and never locks + beyond the caller's shared lock. */ +static +int +_write_buf_splice(const int fd_, + fuse_bufvec *srcv_, + const off_t offset_, + const size_t size_) +{ + fuse_bufvec dst = fuse_bufvec_fd(fd_,offset_,size_, + (fuse_buf_flags)(FUSE_BUF_IS_FD| + FUSE_BUF_FD_SEEK)); + const fuse_buf_copy_flags cpflags = + (fuse_buf_copy_flags)(FUSE_BUF_SPLICE_MOVE | FUSE_BUF_SPLICE_NONBLOCK); + + ssize_t copied = fuse_buf_copy(&dst,srcv_,cpflags); + + return (int)copied; +} + +/* Mem fallback for whatever the splice could not move (partial splice, + O_DIRECT branch fd rejecting splice, or a spliced prefix followed by + an error): read the remaining pipe payload into a heap buffer and + delegate to FUSE::write - lock-free by design, because FUSE::write + takes fi->mutex itself and owns the full move-on-enospc handling + (re-check, move, pwriten retry). Any duplication of that logic here + would re-enter the same non-recursive mutex and self-deadlock. */ +static +int +_write_buf_fallback(const fuse_req_ctx_t *ctx_, + const fuse_file_info_t *ffi_, + fuse_bufvec *srcv_, + const off_t offset_) +{ + size_t remaining = ((size_t)srcv_->buf[srcv_->idx].size - srcv_->off); + if(remaining == 0) + return 0; + + /* A failed splice attempt may have already consumed pipe bytes + without advancing srcv_: on EINVAL (e.g. O_APPEND branch fds + reject splice with an explicit offset) fuse_buf_splice falls + back to fuse_buf_fd_to_fd, which reads from the pipe into a + stack buffer and can fail (or return short) after that read, + dropping the bytes it consumed. Reading `remaining` would then + block forever on a pipe whose write end this request itself + holds. FIONREAD bounds the read; a short pipe means payload + bytes are gone, so fail the request - the app retries, and + msgbuf_free's drain cleans the pipe. */ + int avail; + if(ioctl(srcv_->buf[srcv_->idx].fd,FIONREAD,&avail) == -1) + return -errno; + /* avail is `int`; guard the sign before the size_t comparison below + widens a negative value into a huge one and defeats this exact + short-pipe check (avail should never be negative in practice, but + the cast must not silently trust that). */ + if((avail < 0) || ((size_t)avail < remaining)) + return -EIO; + + std::unique_ptr buf(new(std::nothrow) char[remaining]); + if(!buf) + return -ENOMEM; + + size_t to_read = remaining; + while(to_read > 0) + { + ssize_t nr; + + nr = ::read(srcv_->buf[srcv_->idx].fd,buf.get() + (remaining - to_read),to_read); + if(nr == -1) + { + if(errno == EINTR) + continue; + return -errno; + } + if(nr == 0) + return -EIO; + to_read -= nr; + } + + return FUSE::write(ctx_,ffi_,buf.get(),remaining,offset_); +} + +int +FUSE::write_buf(const fuse_req_ctx_t *ctx_, + const fuse_file_info_t *ffi_, + struct fuse_bufvec *srcv_, + off_t offset_) +{ + ioprio::SetFrom iop(ctx_->pid); + + FileInfo *fi = state.get_fi(ctx_,ffi_->fh); + if(fi == nullptr) + return -EBADF; + + /* O_APPEND branch fds deterministically reject splice(2) with + EINVAL (splice requires an explicit, seekable destination offset; + O_APPEND ignores any offset and always writes at EOF instead), so + _write_buf_splice would immediately fall through fuse_buf_splice + into fuse_buf_fd_to_fd's byte-at-a-time bounce copy for the WHOLE + payload. That bounce loop reads a chunk from the (unrereadable, + one-shot) pipe before writing it to the branch fd; if the write + fails partway (e.g. ENOSPC on a full branch after earlier chunks + already landed), the just-read chunk is silently lost with no way + to recover it, and _write_buf_fallback below can only refuse the + request outright (its FIONREAD check trips) rather than let + FUSE::write relocate it to another branch, because the payload it + would need to resend is already gone. Skip the splice attempt + entirely for O_APPEND: go straight to the fallback here, while + the full unread payload is still intact in the pipe, so the + lossless heap-buffer path (and FUSE::write's moveonenospc retry) + is used from the start instead of being reached only after damage + is done. cache.writeback=true strips O_APPEND from the branch + fd itself (fuse_open.cpp: _tweak_flags_cache_writeback, gated + on cfg.cache_writeback - an option independent of cache.files), + so this only fires when cache.writeback is left at its default + of false, regardless of the cache.files setting. + + O_DIRECT branch fds (ffi_->flags forwards the client's O_DIRECT + open verbatim - see fuse_read_buf.cpp) can likewise reject + splice(2) with EINVAL. Unlike O_APPEND that alone would just + route the whole payload through the same lossless + fuse_buf_fd_to_fd bounce (no data-loss hazard, since the offset + is still explicit/seekable) - but a splice that partially + succeeds before an O_DIRECT-related short count would leave + _write_buf_fallback resuming at a non-block-aligned offset/size, + which O_DIRECT destinations can reject even though the original, + client-aligned request would have succeeded. Bypass splice + entirely for O_DIRECT too so the fallback always sees the whole, + originally-aligned request. */ + if(ffi_->flags & (O_APPEND|O_DIRECT)) + return _write_buf_fallback(ctx_,ffi_,srcv_,offset_); + + /* The check above reads fuse_write_in.flags, which the kernel only + fills in for writes issued from a kiocb. Writeback flushes go + through fuse_writepage_args_setup -> fuse_write_args_fill, which + never assigns it, so a FUSE_WRITE_CACHE request (ffi_->writepage) + always arrives with flags == 0 and slips past the guard into the + lossy bounce described above. The branch fd really can be + O_APPEND/O_DIRECT there: with cache.writeback=false via a + MAP_SHARED mmap of a file opened O_APPEND (the O_APPEND strip in + fuse_open.cpp is gated on cfg.cache_writeback), and with + cache.writeback=true via an O_DIRECT handle, since writepages + picks an arbitrary write-capable fh rather than the one that + dirtied the pages. Ask the fd itself instead of trusting the + request, and treat an unreadable answer as the worst case - the + fallback is always correct, only slower. */ + if(ffi_->writepage) + { + int fl = fs::getfl(fi->fd); + + if((fl < 0) || (fl & (O_APPEND|O_DIRECT))) + return _write_buf_fallback(ctx_,ffi_,srcv_,offset_); + } + + /* Splice under the shared lock only - it makes no nested calls. + Mirrors _write's discipline (fuse_write.cpp) so parallel direct + writes serialize against mem-path writers on the same file. */ + size_t size = fuse_buf_size(srcv_); + ssize_t copied; + { + std::shared_lock slk(fi->mutex); + + copied = _write_buf_splice(fi->fd,srcv_,offset_,size); + } + + /* copied < 0: nothing moved, pipe intact (fuse_buf_copy only + returns errors when zero bytes were consumed). + srcv_->idx < srcv_->count: partial move, remainder still queued. + Either way the fallback drains the pipe and delegates to the + mem write path lock-free; FUSE::write owns ENOSPC/move/retry. */ + if(copied < 0 || srcv_->idx < srcv_->count) + { + off_t done = (copied > 0) ? (off_t)copied : (off_t)0; + + int rv = _write_buf_fallback(ctx_,ffi_,srcv_,offset_ + done); + if(rv < 0) + { + /* `done` bytes are already durably written to the branch + fd via the splice above; a request-level error here must + not discard that progress. Per this codebase's own + write() contract (fuse_write.cpp: "N bytes written + (short writes included)"), report the short write + instead of a bare failure so the kernel/application + don't believe zero bytes landed when `done` actually + did. */ + return (done > 0) ? (int)done : rv; + } + return (int)(done + rv); + } + + return (int)copied; +} diff --git a/src/fuse_write_buf.hpp b/src/fuse_write_buf.hpp new file mode 100644 index 00000000..d1f8a311 --- /dev/null +++ b/src/fuse_write_buf.hpp @@ -0,0 +1,31 @@ +/* + ISC License + + Copyright (c) 2026, Antonio SJ Musumeci + + 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.h" + + +namespace FUSE +{ + int + write_buf(const fuse_req_ctx_t *ctx, + const fuse_file_info_t *ffi, + struct fuse_bufvec *srcv, + off_t offset); +} diff --git a/src/mergerfs.cpp b/src/mergerfs.cpp index c4ad8903..4790826f 100644 --- a/src/mergerfs.cpp +++ b/src/mergerfs.cpp @@ -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" @@ -83,6 +84,7 @@ #include "fuse_unlink.hpp" #include "fuse_utimens.hpp" #include "fuse_write.hpp" +#include "fuse_write_buf.hpp" #include "fuse.h" @@ -147,6 +149,20 @@ _get_fuse_operations(struct fuse_operations &ops_, ops_.unlink = FUSE::unlink; ops_.utimens = FUSE::utimens; ops_.write = (nullrw_ ? FUSE::write_null : FUSE::write); + /* write_buf is held NULL under nullrw: FUSE::write_null discards the + buffer without reading it. NOTE the receive path still stages the + payload in the pipe when splice is on (staging is gated on + fuse_cfg.splice_write, not on ops registration) - write_null + never dereferences the data pointer, and msgbuf_free's bounded + drain discards the leftover pipe bytes. Any future nullrw write + implementation that reads the buffer must handle payload-in-pipe. */ + ops_.write_buf = ((nullrw_ || !cfg.splice) ? nullptr : FUSE::write_buf); + /* read_buf is held NULL under nullrw (read_null already skips all + I/O - nothing on the branch to splice from). When splice is on, + read_buf returns a bufvec referencing the branch fd and the + kernel splices the payload straight from the branch into /dev/fuse + via a pipe. */ + ops_.read_buf = ((nullrw_ || !cfg.splice) ? nullptr : FUSE::read_buf); return; } diff --git a/src/option_parser.cpp b/src/option_parser.cpp index 7d885722..bfb88459 100644 --- a/src/option_parser.cpp +++ b/src/option_parser.cpp @@ -17,6 +17,7 @@ #define FMT_HEADER_ONLY #include "config.hpp" +#include "fuse_cfg.hpp" #include "ef.hpp" #include "errno.hpp" #include "fmt/core.h" @@ -25,6 +26,7 @@ #include "fs_statvfs_cache.hpp" #include "hw_cpu.hpp" #include "num.hpp" +#include "pipe_max_size.hpp" #include "policy.hpp" #include "str.hpp" #include "syslog.hpp" @@ -290,6 +292,26 @@ _cleanup_options() { if(!cfg.symlinkify) cfg.symlinkify_timeout = -1; + + /* splice backing lives in fuse_cfg so fuse_lowlevel_new_common can + select the receive path before FUSE::init ever runs. fuse_init only + flips bits off if the kernel didn't advertise the capability. The + single cfg.splice knob drives all three axes. */ + fuse_cfg.splice_move = bool(cfg.splice); + fuse_cfg.splice_read = bool(cfg.splice); + fuse_cfg.splice_write = bool(cfg.splice); + + /* pipe-max-size: early sysctl write for root-run mergerfs so the + reply bounce pipe and msgbuf receive pipes see the larger capacity + when they are first created (and the fuse_msg_size clamp in + fuse_init.cpp reads the raised value when negotiating INIT). */ + if((u64)cfg.pipe_max_size != 0) + { + if(!pipe_max_size::write((u64)cfg.pipe_max_size)) + SysLog::info("pipe-max-size: unable to raise sysctl to {}" + " (not root, or write failed); keeping kernel default", + (u64)cfg.pipe_max_size); + } } namespace options diff --git a/src/pipe_max_size.cpp b/src/pipe_max_size.cpp new file mode 100644 index 00000000..e8e8b7b0 --- /dev/null +++ b/src/pipe_max_size.cpp @@ -0,0 +1,78 @@ +/* + ISC License + + Copyright (c) 2026, Antonio SJ Musumeci + + 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 "pipe_max_size.hpp" + +#include "scope_guard/scope_guard.hpp" + +#include +#include + +#include +#include + +static const char PIPE_MAX_SIZE_FILEPATH[] = "/proc/sys/fs/pipe-max-size"; + +bool +pipe_max_size::read(u32 &out_) +{ + int fd = ::open(PIPE_MAX_SIZE_FILEPATH,O_RDONLY|O_CLOEXEC); + if(fd == -1) + return false; + DEFER { ::close(fd); }; + + std::array buf; + ssize_t nr = ::read(fd,buf.data(),buf.size()); + if(nr <= 0) + return false; + + unsigned long v; + auto [end,ec] = std::from_chars(buf.data(),buf.data() + nr,v); + if(ec != std::errc()) + return false; + + /* Clamp rather than treat as a read failure: a legitimately + huge sysctl (e.g. an admin-set multi-GiB pipe-max-size, + written verbatim as a u64 by the pipe-max-size= option) + must not be mistaken for "couldn't read it" and fall back + to a small default in the caller - that fallback can then + silently shrink the admin's explicit setting when the + caller reacts to a seemingly-tiny sysctl. */ + out_ = (v > UINT32_MAX) ? UINT32_MAX : (u32)v; + + return true; +} + +bool +pipe_max_size::write(cu64 v_) +{ + int fd = ::open(PIPE_MAX_SIZE_FILEPATH,O_WRONLY|O_CLOEXEC); + if(fd == -1) + return false; + DEFER { ::close(fd); }; + + std::array buf; + auto [end,ec] = std::to_chars(buf.data(),buf.data() + buf.size(),(u64)v_); + if(ec != std::errc()) + return false; + + ssize_t len = (end - buf.data()); + ssize_t wr = ::write(fd,buf.data(),len); + + return (wr == len); +} diff --git a/src/pipe_max_size.hpp b/src/pipe_max_size.hpp new file mode 100644 index 00000000..19aedf6d --- /dev/null +++ b/src/pipe_max_size.hpp @@ -0,0 +1,27 @@ +/* + ISC License + + Copyright (c) 2026, Antonio SJ Musumeci + + 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 "base_types.h" + +namespace pipe_max_size +{ + bool read(u32 &out_); + bool write(cu64 v_); +} diff --git a/tools/bench-splice.sh b/tools/bench-splice.sh new file mode 100755 index 00000000..62d2dbbf --- /dev/null +++ b/tools/bench-splice.sh @@ -0,0 +1,415 @@ +#!/bin/bash +# bench-splice.sh -- A/B benchmark of mergerfs splice +# against the mergefs OFF baseline and a pristine-HEAD baseline binary. +# +# Run: bash tools/bench-splice.sh [REPS] +# Env: BASE_REPO (path to pristine HEAD build dir), SIZE_MIB, REPS +# note: requires `unshare -Urm` permissions for an unprivileged FUSE mount. + +# Resolve a working `stat -c %s` once: this host's unshare PATH can +# front a non-GNU stat (aurora) that rejects -c. +STAT_BIN="$(command -v stat)" +if ! "${STAT_BIN}" -c %s /dev/null >/dev/null 2>&1; then + STAT_BIN=/usr/bin/stat +fi + +set -euo pipefail +export LC_ALL=C # dd prints locale-formatted numbers; parse_mibs needs C + +REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +BIN="${REPO}/build/mergerfs" +BASE_REPO="${BASE_REPO:-/tmp/mfs-base}" +BASE_BIN="${BASE_REPO}/build/mergerfs" + +B=/dev/shm/bench-splice +REPS="${REPS:-${1:-5}}" + +# --- OOM guard: pick SIZE_MIB so mergefs-blob fits comfortably into MemAvailable +mem_available_kib() { awk '/^MemAvailable:/{print $2}' /proc/meminfo; } +pick_size_mib() { + local want=(256 128 64) + local w + for w in "${want[@]}"; do + local need=$(( w * 2 * 1024 )) # blob on branch + mergefs page cache + local have; have=$(mem_available_kib) + if (( have >= need )); then echo "$w"; return; fi + done + echo "INSUFFICIENT-MEMORY" >&2 + return 1 +} +SIZE_MIB="${SIZE_MIB:-$(pick_size_mib)}" + +# --- helpers ----------------------------------------------------------- + +die() { echo "bench-splice: $*" >&2; exit 1; } +need_binary() { [[ -x "$1" ]] || die "missing binary: $1"; } + +need_splice_binary() { + # --version comes from src/version.hpp, which incremental makes do not + # refresh; assert the binary actually contains the code under test. + # NB: consume strings fully - grep -q closes the pipe early, and with + # pipefail the resulting SIGPIPE would fail the check spuriously. + local marker="$2" + local out + out=$(strings "$1" | grep "${marker}" || true) + [[ -n "${out}" ]] \ + || die "binary $1 lacks marker '${marker}' (stale build? run make)" +} + +ensure_unshared() { + # Re-exec under unshare -Urm if we're not already root in a user ns + # (mount requires CAP_SYS_ADMIN in this host's delegate). + if (( EUID != 0 )) && [[ -z "${BENCH_INNS:-}" ]]; then + BENCH_INNS=1 exec unshare -Urm -- "$0" "$@" + fi +} + +# --- mergefs process management ----------------------------------------- + +declare -g MNT="" BR1="" BR2="" MPID="" + +mfs_stop() { + if [[ -n "${MPID}" ]]; then + kill "${MPID}" 2>/dev/null || true + wait "${MPID}" 2>/dev/null || true + MPID= + fi + pkill -9 -f "$BIN .*${B}/mnt" 2>/dev/null || true + pkill -9 -f "$BASE_BIN .*${B}/mnt" 2>/dev/null || true + if [[ -n "${MNT}" ]] && grep -qs "${B}/mnt" /proc/mounts; then + fusermount3 -u "${MNT}" >/dev/null 2>&1 || umount "${MNT}" 2>/dev/null || true + fi +} + +cleanup() { + mfs_stop + payload_src_fini + rm -rf "${B}" +} +trap cleanup EXIT +trap 'cleanup; exit 1' INT TERM + +mfs_start() { + local binary="$1"; shift + local opts="$1"; shift + + BR1="${B}/b1"; BR2="${B}/b2"; MNT="${B}/mnt" + mkdir -p "${BR1}" "${BR2}" "${MNT}" + + "${binary}" -f "${BR1}:${BR2}" "${MNT}" -o "${opts}" >/dev/null 2>&1 & + MPID=$! + + # wait for mount + local t=0 + while ! grep -qs " ${MNT} " /proc/mounts; do + sleep 0.2 + t=$(( t + 1 )) + if (( t > 50 )); then + die "mount did not come up for ${binary}" + fi + done + sleep 0.5 # let it warm INIT +} + +# --- one experiment ------------------------------------------------------ + +# run_4phases