Compare commits

..

No commits in common. "master" and "2.42.0" have entirely different histories.

90 changed files with 756 additions and 3180 deletions

View file

@ -15,6 +15,3 @@
* ./bootstrap.sh * ./bootstrap.sh
* ./b2 tools/bcp * ./b2 tools/bcp
* ./dist/bin/bcp unordered/concurrent_flat_map.hpp <target_dir> * ./dist/bin/bcp unordered/concurrent_flat_map.hpp <target_dir>
* local patch: keep unordered dummy-group storage writable with C++20
`constinit`; ARMv5 atomic loads can write back to memory (#1695).
Preserve this change when updating Boost.

View file

@ -29,8 +29,6 @@ MKDIR ?= mkdir
MKTEMP ?= mktemp MKTEMP ?= mktemp
MV ?= mv MV ?= mv
RM ?= rm RM ?= rm
RPMBUILD ?= rpmbuild
RPMBUILD_FLAGS ?=
SED ?= sed SED ?= sed
STRIP ?= strip STRIP ?= strip
TAR ?= tar TAR ?= tar
@ -39,7 +37,7 @@ TOUCH ?= touch
BUILDDIR := build BUILDDIR := build
GITHUB_REPO ?= "https://github.com/trapexit/mergerfs" GITHUB_REPO ?= "https://github.com/trapexit/mergerfs"
DEFAULT_TARGET := debian:13.amd64 DEFAULT_RELEASE := debian:13.amd64
ifndef GIT_REPO ifndef GIT_REPO
ifneq ($(shell $(GIT) --version 2> /dev/null),) ifneq ($(shell $(GIT) --version 2> /dev/null),)
@ -50,7 +48,11 @@ endif
endif endif
USE_XATTR ?= 1 USE_XATTR ?= 1
UGID_USE_RWLOCK ?= 0
ifdef NDEBUG
OPT_FLAGS := -O2 -DNDEBUG
else
ifdef SANITIZE ifdef SANITIZE
ifeq ($(SANITIZE),1) ifeq ($(SANITIZE),1)
override SANITIZE := -fsanitize=address,undefined,leak override SANITIZE := -fsanitize=address,undefined,leak
@ -58,22 +60,14 @@ else ifeq ($(filter -fsanitize=%,$(SANITIZE)),)
override SANITIZE := -fsanitize=$(SANITIZE) override SANITIZE := -fsanitize=$(SANITIZE)
endif endif
endif endif
OPT_FLAGS := -O0 \
COMMON_OPT_FLAGS += \ -g \
-fno-omit-frame-pointer \
$(SANITIZE) \
-fstack-protector-strong \ -fstack-protector-strong \
-Wextra \ -Wextra \
-Wno-unused-parameter -Wno-unused-parameter \
-DDEBUG
DEBUG_OPT_FLAGS += \
-O0 \
-g3 \
-fno-omit-frame-pointer \
$(SANITIZE)
ifdef RELEASE
OPT_FLAGS := -O3 $(COMMON_OPT_FLAGS)
else
OPT_FLAGS ?= $(DEBUG_OPT_FLAGS) $(COMMON_OPT_FLAGS)
endif endif
ifdef STATIC ifdef STATIC
@ -123,7 +117,7 @@ CXXFLAGS ?= \
-Wno-unused-result \ -Wno-unused-result \
-pipe -pipe
override CXXFLAGS += \ override CXXFLAGS += \
-std=c++20 \ -std=c++17 \
-MMD \ -MMD \
-MP -MP
override INC_FLAGS := \ override INC_FLAGS := \
@ -131,7 +125,8 @@ override INC_FLAGS := \
-Ivendored \ -Ivendored \
-Ivendored/libfuse/include -Ivendored/libfuse/include
override MFS_FLAGS := \ override MFS_FLAGS := \
-DUSE_XATTR=$(USE_XATTR) -DUSE_XATTR=$(USE_XATTR) \
-DUGID_USE_RWLOCK=$(UGID_USE_RWLOCK)
override TESTS_FLAGS := \ override TESTS_FLAGS := \
-Isrc \ -Isrc \
-Ivendored \ -Ivendored \
@ -203,7 +198,7 @@ libfuse: $(LIBFUSE)
$(MAKE) -C vendored/libfuse $(MAKE) -C vendored/libfuse
$(LIBFUSE): $(LIBFUSE):
$(MAKE) -C vendored/libfuse $(BUILDDIR)/libfuse.a RELEASE=$(RELEASE) $(MAKE) -C vendored/libfuse $(BUILDDIR)/libfuse.a
tests: $(BUILDDIR)/tests tests: $(BUILDDIR)/tests
@ -345,7 +340,7 @@ rpm: tarball
$(SED) 's/__VERSION__/$(VERSION)/g' mergerfs.spec > \ $(SED) 's/__VERSION__/$(VERSION)/g' mergerfs.spec > \
rpmbuild/SOURCES/mergerfs.spec rpmbuild/SOURCES/mergerfs.spec
cp -ar mergerfs-$(VERSION).tar.gz rpmbuild/SOURCES cp -ar mergerfs-$(VERSION).tar.gz rpmbuild/SOURCES
$(RPMBUILD) $(RPMBUILD_FLAGS) -ba rpmbuild/SOURCES/mergerfs.spec \ rpmbuild -ba rpmbuild/SOURCES/mergerfs.spec \
--define "_topdir $(CURDIR)/rpmbuild" --define "_topdir $(CURDIR)/rpmbuild"
.PHONY: install-build-pkgs .PHONY: install-build-pkgs
@ -367,16 +362,14 @@ define build_release
--branch=$(GITREF) --branch=$(GITREF)
endef endef
.PHONY: release release-all .PHONY: release
.PHONY: release-amd64 release-arm64 release-armhf release-riscv64 .PHONY: release-amd64 release-arm64 release-armhf release-riscv64
.PHONY: release-sample release-static release-tarball release-installer .PHONY: release-sample release-static release-tarball
release: release:
$(MAKE) RELEASE=1 CPPFLAGS="$(CPPFLAGS) -DNDEBUG" all
release-all:
$(call build_release,"all") $(call build_release,"all")
release-sample: release-sample:
$(if $(TARGET),,$(eval TARGET := $(shell ./buildtools/detect-local-target 2>/dev/null))) $(if $(RELEASE),,$(eval RELEASE := $(shell ./buildtools/detect-local-target 2>/dev/null)))
$(call build_release,$(if $(TARGET),$(TARGET),$(DEFAULT_TARGET))) $(call build_release,$(if $(RELEASE),$(RELEASE),$(DEFAULT_RELEASE)))
release-amd64: release-amd64:
$(call build_release,"amd64") $(call build_release,"amd64")
release-arm64: release-arm64:
@ -389,8 +382,6 @@ release-static:
$(call build_release,"static") $(call build_release,"static")
release-tarball: release-tarball:
$(call build_release,"tarball") $(call build_release,"tarball")
release-installer:
$(call build_release,"installer")
container: container:
$(eval GITREF ?= $(shell git describe --exact-match --tags HEAD 2>/dev/null || git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --short HEAD)) $(eval GITREF ?= $(shell git describe --exact-match --tags HEAD 2>/dev/null || git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --short HEAD))

View file

@ -1,19 +1,6 @@
#!/bin/sh #!/bin/sh
set -e set -e
if [ -e /tmp/build-env ]; then
. /tmp/build-env
fi
rpmbuild_flags()
{
case "$(command -v "${CXX:-g++}")" in
/opt/rh/*)
printf '%s' '--undefine _annotated_build'
;;
esac
}
if [ $# -ne 2 ]; then if [ $# -ne 2 ]; then
echo "usage: $0 <branch> <git_repo>" echo "usage: $0 <branch> <git_repo>"
echo "argv: $@" echo "argv: $@"
@ -41,9 +28,10 @@ mkdir "/build"
if [ -e /usr/bin/apt-get ]; then if [ -e /usr/bin/apt-get ]; then
make deb make deb
elif [ -e /usr/bin/dnf ]; then elif [ -e /usr/bin/dnf ]; then
make RPMBUILD_FLAGS="$(rpmbuild_flags)" rpm make rpm
elif [ -e /usr/bin/yum ]; then elif [ -e /usr/bin/yum ]; then
make RPMBUILD_FLAGS="$(rpmbuild_flags)" rpm . /opt/rh/devtoolset-9/enable
make rpm
elif [ -e /sbin/apk ]; then elif [ -e /sbin/apk ]; then
echo "NOT YET SUPPORTED" echo "NOT YET SUPPORTED"
exit 1 exit 1

View file

@ -18,7 +18,7 @@ def build(git_repo,
'--force-rm'] '--force-rm']
if os.path.exists(git_repo): if os.path.exists(git_repo):
git_repo = os.path.realpath(git_repo) git_repo = os.path.realpath(git_repo)
args += ['-v',f'{git_repo}:/tmp/mergerfs.git:ro:z'] args += ['-v',f'{git_repo}:/tmp/mergerfs.git:ro']
args += ['--build-arg=GIT_REPO=file:///tmp/mergerfs.git'] args += ['--build-arg=GIT_REPO=file:///tmp/mergerfs.git']
else: else:
args += [f'--build-arg=GIT_REPO={git_repo}'] args += [f'--build-arg=GIT_REPO={git_repo}']

View file

@ -1,4 +1,4 @@
FROM --platform=amd64 fedora:45 as build FROM --platform=amd64 debian:11 as build
COPY install-build-pkgs build-mergerfs /tmp/ COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0

View file

@ -1,4 +1,4 @@
FROM --platform=arm64 fedora:45 as build FROM --platform=arm64 debian:11 as build
COPY install-build-pkgs build-mergerfs /tmp/ COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0

View file

@ -1,4 +1,4 @@
FROM --platform=amd64 ubuntu:26.10 as build FROM --platform=armhf debian:11 as build
COPY install-build-pkgs build-mergerfs /tmp/ COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0

View file

@ -1,4 +1,4 @@
FROM --platform=arm64 ubuntu:26.10 as build FROM --platform=i386 debian:11 as build
COPY install-build-pkgs build-mergerfs /tmp/ COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0

View file

@ -1,4 +1,4 @@
FROM --platform=amd64 fedora:44 as build FROM --platform=amd64 fedora:43 as build
COPY install-build-pkgs build-mergerfs /tmp/ COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0

View file

@ -1,4 +1,4 @@
FROM --platform=arm64 fedora:44 as build FROM --platform=arm64 fedora:43 as build
COPY install-build-pkgs build-mergerfs /tmp/ COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0

View file

@ -1,9 +1,6 @@
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0
FROM --platform=linux/amd64 ubuntu:latest as build FROM --platform=linux/amd64 ubuntu:latest as build
COPY install-build-pkgs /tmp/ RUN apt-get update && apt-get install -y makeself
RUN /tmp/install-build-pkgs && \
DEBIAN_FRONTEND=noninteractive apt-get -qy --no-install-suggests --no-install-recommends install \
makeself
RUN mkdir -p /tmp/mergerfs/ RUN mkdir -p /tmp/mergerfs/
RUN ls -lhd /pkgs RUN ls -lhd /pkgs
RUN cp -v /pkgs/*static*.gz /tmp/mergerfs/ RUN cp -v /pkgs/*static*.gz /tmp/mergerfs/

View file

@ -1,10 +0,0 @@
FROM --platform=armhf ubuntu:26.10 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=riscv64 ubuntu:26.10 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,166 +1,39 @@
#!/bin/sh #!/bin/sh
set -e
BUILD_ENV=/tmp/build-env
write_gcc_env()
{
{
printf 'export CC=%s\n' "$1"
printf 'export CXX=%s\n' "$2"
} > "$BUILD_ENV"
}
write_toolset_env()
{
{
printf '. %s\n' "$1"
printf 'export CC=gcc\n'
printf 'export CXX=g++\n'
} > "$BUILD_ENV"
}
latest_apt_gxx()
{
apt-cache --names-only search '^g[+][+]-[0-9]' \
| sed -n 's/^\(g++-[0-9][0-9]*\) .*/\1/p' \
| sort -t- -k2,2V \
| tail -n 1
}
latest_dnf_toolset()
{
dnf -q list --showduplicates 'gcc-toolset-*-gcc-c++' 2>/dev/null \
| sed -n 's/^gcc-toolset-\([0-9][0-9]*\)-gcc-c++\..*/\1/p' \
| sort -V \
| tail -n 1
}
latest_yum_toolset()
{
yum -q list available 'devtoolset-*-gcc-c++' 2>/dev/null \
| sed -n 's/^devtoolset-\([0-9][0-9]*\)-gcc-c++\..*/\1/p' \
| sort -V \
| tail -n 1
}
version_gt()
{
highest="$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n 1)"
[ "$highest" = "$1" ] && [ "$1" != "$2" ]
}
check_cxx20()
{
cxx="${CXX:-g++}"
test_src=/tmp/mergerfs-cxx20-check.cpp
test_bin=/tmp/mergerfs-cxx20-check
cat > "$test_src" <<'EOF'
template <typename T>
concept Incrementable = requires(T value) { value + 1; };
static_assert(Incrementable<int>);
int main()
{
return 0;
}
EOF
if ! "$cxx" -std=c++20 "$test_src" -o "$test_bin" >/dev/null 2>&1; then
echo "error: $cxx does not support C++20" >&2
exit 1
fi
rm -f "$test_src" "$test_bin"
}
: > "$BUILD_ENV"
if [ -e /usr/bin/apt-get ]; then if [ -e /usr/bin/apt-get ]; then
export DEBIAN_FRONTEND=noninteractive export DEBIAN_FRONTEND=noninteractive
apt-get -qy update apt-get -qy update
cxx_pkg="$(latest_apt_gxx)"
if [ -n "$cxx_pkg" ]; then
gcc_pkg="gcc-${cxx_pkg#g++-}"
compiler_pkgs="$gcc_pkg $cxx_pkg"
write_gcc_env "$gcc_pkg" "$cxx_pkg"
else
compiler_pkgs="g++"
write_gcc_env gcc g++
fi
apt-get -qy --force-yes --no-install-suggests --no-install-recommends \ apt-get -qy --force-yes --no-install-suggests --no-install-recommends \
install \ install \
ca-certificates \ ca-certificates \
build-essential \ build-essential \
dpkg-dev \ dpkg-dev \
git \ git \
$compiler_pkgs \ g++ \
debhelper \ debhelper \
lsb-release \ lsb-release \
fakeroot fakeroot
. "$BUILD_ENV"
check_cxx20
elif [ -e /usr/bin/dnf ]; then elif [ -e /usr/bin/dnf ]; then
dnf -y update dnf -y update
toolset="$(latest_dnf_toolset)"
dnf -y install \ dnf -y install \
git rpm-build gcc-c++ make which libatomic git rpm-build gcc-c++ make which libatomic
default_gxx_major="$(g++ -dumpversion | cut -f1 -d.)"
if [ -n "$toolset" ] && version_gt "$toolset" "$default_gxx_major"; then
dnf -y install \
"gcc-toolset-${toolset}-gcc" \
"gcc-toolset-${toolset}-gcc-c++"
if [ -f "/usr/lib/gcc-toolset/${toolset}-env.source" ]; then
write_toolset_env "/usr/lib/gcc-toolset/${toolset}-env.source"
else
write_toolset_env "/opt/rh/gcc-toolset-${toolset}/enable"
fi
else
write_gcc_env gcc g++
fi
. "$BUILD_ENV"
check_cxx20
elif [ -e /usr/bin/yum ]; then elif [ -e /usr/bin/yum ]; then
yum -y update yum -y update
yum -y install \ yum -y install \
git rpm-build gcc-c++ make which git rpm-build gcc-c++ make which
yum -y install centos-release-scl || true yum -y install centos-release-scl
yum -y update yum -y install devtoolset-9-gcc\*
toolset="$(latest_yum_toolset)"
default_gxx_major="$(g++ -dumpversion | cut -f1 -d.)"
if [ -n "$toolset" ] && version_gt "$toolset" "$default_gxx_major"; then
yum -y install \
"devtoolset-${toolset}-gcc" \
"devtoolset-${toolset}-gcc-c++"
write_toolset_env "/opt/rh/devtoolset-${toolset}/enable"
else
write_gcc_env gcc g++
fi
. "$BUILD_ENV"
check_cxx20
elif [ -e /usr/bin/zypper ]; then elif [ -e /usr/bin/zypper ]; then
zypper update -y zypper update -y
zypper install -y \ zypper install -y \
git rpm-build gcc-c++ make which git rpm-build gcc-c++ make which
write_gcc_env gcc g++
. "$BUILD_ENV"
check_cxx20
elif [ -e /sbin/apk ]; then elif [ -e /sbin/apk ]; then
apk add \ apk add \
abuild git gcc g++ make \ abuild git gcc g++ make \
linux-headers linux-headers
write_gcc_env gcc g++
. "$BUILD_ENV"
check_cxx20
elif [ -e /usr/sbin/pkg ]; then elif [ -e /usr/sbin/pkg ]; then
pkg install \ pkg install \
git gmake gcc git gmake gcc
elif [ -e /usr/bin/pacman ]; then elif [ -e /usr/bin/pacman ]; then
pacman -Sy --noconfirm base-devel git fakeroot pacman -Sy --noconfirm base-devel git fakeroot
write_gcc_env gcc g++
. "$BUILD_ENV"
check_cxx20
fi fi

View file

@ -1,3 +1,7 @@
debian:11 amd64
debian:11 arm64
debian:11 armhf
debian:11 i386
debian:12 amd64 debian:12 amd64
debian:12 arm64 debian:12 arm64
debian:12 armhf debian:12 armhf
@ -15,10 +19,6 @@ fedora:42 amd64
fedora:42 arm64 fedora:42 arm64
fedora:43 amd64 fedora:43 amd64
fedora:43 arm64 fedora:43 arm64
fedora:44 amd64
fedora:44 arm64
fedora:45 amd64
fedora:45 arm64
quay.io/rockylinux/rockylinux:10 amd64 quay.io/rockylinux/rockylinux:10 amd64
quay.io/rockylinux/rockylinux:10 arm64 quay.io/rockylinux/rockylinux:10 arm64
quay.io/rockylinux/rockylinux:8 amd64 quay.io/rockylinux/rockylinux:8 amd64
@ -37,15 +37,3 @@ ubuntu:25.04 amd64
ubuntu:25.04 arm64 ubuntu:25.04 arm64
ubuntu:25.04 armhf ubuntu:25.04 armhf
ubuntu:25.04 riscv64 ubuntu:25.04 riscv64
ubuntu:25.10 amd64
ubuntu:25.10 arm64
ubuntu:25.10 armhf
ubuntu:25.10 riscv64
ubuntu:26.04 amd64
ubuntu:26.04 arm64
ubuntu:26.04 armhf
ubuntu:26.04 riscv64
ubuntu:26.10 amd64
ubuntu:26.10 arm64
ubuntu:26.10 armhf
ubuntu:26.10 riscv64

3
debian/rules vendored
View file

@ -6,9 +6,6 @@ export DH_VERBOSE=1
%: %:
dh $@ dh $@
override_dh_auto_build:
dh_auto_build --parallel -- release
override_dh_auto_install: override_dh_auto_install:
$(MAKE) \ $(MAKE) \
DESTDIR=$(CURDIR)/debian/mergerfs \ DESTDIR=$(CURDIR)/debian/mergerfs \

View file

@ -38,32 +38,6 @@ These files and xattrs are used to help `mergerfs` know whether or not
a directory happens to be a branch or is the underlying directory a directory happens to be a branch or is the underlying directory
mount point. mount point.
## Paths which appear after startup
The [`branches` resolution process](branches.md#resolution) runs before
this option starts waiting. A missing literal path is retained as a
branch, so a configuration such as `/mnt/hdd/disk0/foobar` can work
when `/mnt/hdd/disk0` is mounted asynchronously and `foobar` only
becomes visible afterward, provided the path then meets one of the
"mounted" conditions above.
For each branch which is not ready, mergerfs first runs `mount` once
with the full branch path as the target and then polls that same path
until the timeout expires. It does not create the path, try to mount
its parent, or rerun `mount`. In the example above, the initial
`mount /mnt/hdd/disk0/foobar` may fail while the path is absent. If
another service mounts `/mnt/hdd/disk0` and
`/mnt/hdd/disk0/foobar` appears and meets one of the "mounted"
conditions before the deadline, mergerfs detects it during polling
and continues.
Globs are different. If `/mnt/hdd/disk0/*` has no matches during
branch resolution, the literal path `/mnt/hdd/disk0/*` is retained.
The mount wait does not expand it again after `/mnt/hdd/disk0`
becomes available. Ensure the parent filesystem is mounted before
mergerfs, configure a literal branch path, or update `branches`
through the runtime API once the paths exist.
**NOTE:** If on a `systemd` based system and using `fstab` it is a **NOTE:** If on a `systemd` based system and using `fstab` it is a
good idea to set the mount option good idea to set the mount option

View file

@ -14,7 +14,7 @@ Branches currently have two options which can be set. A
included in a policy calculation and a individual included in a policy calculation and a individual
[minfreespace](#minfreespace) value. The values are set by [minfreespace](#minfreespace) value. The values are set by
prepending an `=` at the end of a branch designation and using commas prepending an `=` at the end of a branch designation and using commas
as delimiters. Example: `/mnt/hdd/disk0=RW,1234` as delimiters. Example: `/mnt/drive=RW,1234`
### branch mode ### branch mode
@ -34,33 +34,6 @@ Same purpose and syntax as the [global option](minfreespace.md) but
specific to the branch. Defaults to the global value. specific to the branch. Defaults to the global value.
### resolution
Each colon-delimited branch designation is resolved independently when
the `branches` option is parsed, both at startup and when it is updated
through the runtime API:
1. The path portion is expanded as a glob.
2. If the glob matches one or more directories, each match becomes a
branch.
3. If the glob has no matches, mergerfs logs a notice and keeps the
configured path unchanged as a single, literal branch.
4. mergerfs resolves each resulting path with `realpath`. If that
succeeds, the canonical path is stored. If it fails, typically
because the path does not exist yet, the unchanged path is stored.
5. A path which exists but is not a directory is logged and skipped. A
path which does not exist is logged but retained.
Consequently, a literal branch such as `/mnt/hdd/disk0/foobar` may be
configured before it exists and can become usable after
`/mnt/hdd/disk0` is mounted. Branch resolution is not repeated in the
background, however. If `/mnt/hdd/disk0/*` has no matches when it is
resolved, mergerfs stores the literal path `/mnt/hdd/disk0/*`;
directories which match it later are not discovered automatically.
Update `branches` through the runtime API or restart mergerfs to
resolve the glob again.
### globbing ### globbing
To make it easier to include multiple branches mergerfs supports To make it easier to include multiple branches mergerfs supports
@ -69,18 +42,18 @@ MUST be escaped when using via the shell else the shell itself will
apply the glob itself.** apply the glob itself.**
``` ```
# mergerfs /mnt/hdd/\*:/mnt/ssd/\* /media # mergerfs /mnt/hdd\*:/mnt/ssd /media
``` ```
The above line will use all directories within `/mnt/hdd` and The above line will use all directories in /mnt prefixed with **hdd**
`/mnt/ssd`. as well as **ssd**.
To have the pool mounted at boot or otherwise accessible from related To have the pool mounted at boot or otherwise accessible from related
tools use `/etc/fstab`. tools use `/etc/fstab`.
``` ```
# <file system> <mount point> <type> <options> <dump> <pass> # <file system> <mount point> <type> <options> <dump> <pass>
/mnt/hdd/*:/mnt/ssd/* /media mergerfs minfreespace=16G 0 0 /mnt/hdd*:/mnt/ssd /media mergerfs minfreespace=16G 0 0
``` ```
**NOTE:** The globbing is done at mount or when updated using the **NOTE:** The globbing is done at mount or when updated using the

View file

@ -39,9 +39,5 @@ situations.
[readdir](https://man7.org/linux/man-pages/man2/readdir.2.html) in [readdir](https://man7.org/linux/man-pages/man2/readdir.2.html) in
order to leverage larger buffers for better performance on larger order to leverage larger buffers for better performance on larger
directory reads as well as have more control in concurrent policies. directory reads as well as have more control in concurrent policies.
Individual branch `getdents64` requests are capped at 128 KiB to work
around problems with larger requests on virtiofs. This applies to
`seq`, `cosr`, and `cor`; it does not limit the total directory listing
or change [fuse-msg-size](fuse-msg-size.md).
* [readdir](https://man7.org/linux/man-pages/man2/readdir.2.html) is * [readdir](https://man7.org/linux/man-pages/man2/readdir.2.html) is
used on FreeBSD. used on FreeBSD.

View file

@ -41,13 +41,6 @@ is chosen other parts of the system does what is necessary to
accomplish the function. Such as the cloning of directories between accomplish the function. Such as the cloning of directories between
branches. branches.
When a directory path is cloned onto another branch, mergerfs attempts
to preserve its ownership, permissions (including setgid), timestamps,
and extended attributes. Permissions are restored after ownership so
new files in a setgid directory inherit its group on the new branch.
Directories which already exist on the destination branch are left
unchanged.
When using policies which are based on a branch's available space the When using policies which are based on a branch's available space the
branch base path provided is used. Not the full path to the file or branch base path provided is used. Not the full path to the file or
directory in question. Meaning that mounts within the branch will not directory in question. Meaning that mounts within the branch will not
@ -126,10 +119,10 @@ but it makes things a bit more uniform.
| lup (least used percent) | Pick the branch with the least used percentage of space | | lup (least used percent) | Pick the branch with the least used percentage of space |
| lus (least used space) | Pick the branch with the least used space. | | lus (least used space) | Pick the branch with the least used space. |
| all | Search: For **mkdir**, **mknod**, and **symlink** it will apply to all branches. **create** works like **ff**. | | all | Search: For **mkdir**, **mknod**, and **symlink** it will apply to all branches. **create** works like **ff**. |
| msppfrd (most shared path, percentage free random distribution) | Like **eppfrd** but if it fails to find a branch it will try again with the parent directory. Continues through the branch root, returning an error if no branch qualifies. | | msppfrd (most shared path, percentage free random distribution) | Like **eppfrd** but if it fails to find a branch it will try again with the parent directory. Continues this pattern till finding one. |
| mspmfs (most shared path, most free space) | Like **epmfs** but if it fails to find a branch it will try again with the parent directory. Continues through the branch root, returning an error if no branch qualifies. | | mspmfs (most shared path, most free space) | Like **epmfs** but if it fails to find a branch it will try again with the parent directory. Continues this pattern till finding one. |
| msplfs (most shared path, least free space) | Like **eplfs** but if it fails to find a branch it will try again with the parent directory. Continues through the branch root, returning an error if no branch qualifies. | | msplfs (most shared path, least free space) | Like **eplfs** but if it fails to find a branch it will try again with the parent directory. Continues this pattern till finding one. |
| msplus (most shared path, least used space) | Like **eplus** but if it fails to find a branch it will try again with the parent directory. Continues through the branch root, returning an error if no branch qualifies. | | msplus (most shared path, least used space) | Like **eplus** but if it fails to find a branch it will try again with the parent directory. Continues this pattern till finding one. |
| eppfrd (existing path, percentage free random distribution) | Like **pfrd** but limited to existing paths. | | eppfrd (existing path, percentage free random distribution) | Like **pfrd** but limited to existing paths. |
| epmfs (existing path, most free space) | Of all the branches on which the relative path exists choose the branch with the most free space. | | epmfs (existing path, most free space) | Of all the branches on which the relative path exists choose the branch with the most free space. |
| eprand (existing path, random) | Calls **epall** and then randomizes. Returns 1. | | eprand (existing path, random) | Calls **epall** and then randomizes. Returns 1. |

View file

@ -13,16 +13,5 @@ the newpath. The target value is determined by the value of
mount point. mount point.
* Defaults to `passthrough`. * Defaults to `passthrough`.
Replacement symlinks retain the source inode's UID and GID, read without
following a source symlink. Relative and pool targets use the first
`getattr`-policy source branch; absolute branch targets use the source
selected by the `open` policy. Creation uses daemon credentials, then
sets the source ownership, rather than using the link request's UID/GID,
which may be invalid when `allow-idmap` is enabled. A newly created
replacement is removed if its ownership cannot be set.
Source branch selection and path construction retain the same branch
snapshot, even when the branch list is updated at runtime.
**NOTE:** It is possible that some applications check the file they **NOTE:** It is possible that some applications check the file they
link. In those cases, it is possible it will error or complain. link. In those cases, it is possible it will error or complain.

View file

@ -23,8 +23,7 @@ will:
1. Run the policy defined by `moveonenospc` to find a target branch. 1. Run the policy defined by `moveonenospc` to find a target branch.
2. ["Move"](../faq/technical_behavior_and_limitations.md#how-does-mergerfs-handle-moving-and-copying-of-files) 2. ["Move"](../faq/technical_behavior_and_limitations.md#how-does-mergerfs-handle-moving-and-copying-of-files)
the file from the source branch to the target branch. the file from the source branch to the target branch.
3. Retry only the unwritten portion of the request, so a partially 3. Retry the `write` and continue on as normal.
completed append is not duplicated.
If at any point something fails the progress so far will be cleaned up If at any point something fails the progress so far will be cleaned up
as appropriate and the original error returned. as appropriate and the original error returned.

View file

@ -2,8 +2,7 @@
If using path preservation and a `rename` fails with `EXDEV`: If using path preservation and a `rename` fails with `EXDEV`:
1. Move file from `/mnt/hdd/disk0/a/b/c` to 1. Move file from `/branch/a/b/c` to `/branch/.mergerfs_rename_exdev/a/b/c`.
`/mnt/hdd/disk0/.mergerfs_rename_exdev/a/b/c`.
2. symlink the rename's `newpath` to the moved file. 2. symlink the rename's `newpath` to the moved file.
The `target` value is determined by the value of `rename-exdev`. The `target` value is determined by the value of `rename-exdev`.
@ -14,19 +13,6 @@ The `target` value is determined by the value of `rename-exdev`.
mount point. mount point.
* Defaults to `passthrough`. * Defaults to `passthrough`.
The staging directory is created on demand, including for files at the
pool root. Relative targets are calculated within the pool's relative
path namespace.
Replacement symlinks retain the UID and GID of the first source inode
selected by the rename action policy, read before moving the source and
without following source symlinks. Creation uses daemon credentials,
then sets the source ownership; it does not use the rename request's
UID/GID, which may be invalid when `allow-idmap` is enabled. A newly
created replacement is removed if its ownership cannot be set. If
replacement creation fails, mergerfs attempts to restore the original
source paths.
**NOTE:** It is possible that some applications check the file they **NOTE:** It is possible that some applications check the file they
rename. In those cases it is possible it will error or complain. rename. In those cases it is possible it will error or complain.

View file

@ -149,70 +149,6 @@ It is generally recommended to not use user namespacing / id mapping
given the complication it introduces. given the complication it introduces.
## Does mergerfs work with SELinux relabeling?
FUSE filesystems, including mergerfs, do not support per-inode
SELinux labels (see [Red Hat bug
1272868](https://bugzilla.redhat.com/show_bug.cgi?id=1272868) and the
[upstream fuse-devel
thread](https://sourceforge.net/p/fuse/mailman/fuse-devel/thread/CAN9vWDLGA4%3Dg3peKVWkX7gLRiVUUvJAQx9kiXHgqdeX6eh0MYA%40mail.gmail.com/)).
When a container runtime such as Podman or Docker is asked to relabel
a bind mount with the `:z` or `:Z` mount option, it first probes the
source for `security.selinux` xattr support. On a FUSE path that
probe returns `EOPNOTSUPP` and the runtime skips relabeling entirely.
Files inside the mount keep the `fusefs_t` type assigned by the
kernel. No tree walk is performed and no journal noise is produced at
default verbosity. The runtime logs `Labeling not supported on
"<path>"` only at debug level (for example
`podman --log-level=debug`). The flag is therefore a no-op against a
mergerfs mount; not harmful, but misleading.
Containers can still read and write a mergerfs pool without `:z`
because two independent access checks must succeed and both can be
satisfied without any relabel:
* **SELinux:** on Fedora, RHEL / CentOS Stream, and SUSE the shipped
[container-selinux](https://github.com/containers/container-selinux)
policy already permits the `container_t` process type to manage
files of type `fusefs_t`. See `container_selinux(8)`.
* **DAC:** the in-container UID and GID must still be able to read
and write the files on the underlying branches. With rootless
Podman this is most easily arranged by aligning the container UID
with the host owner of the branches (for example
`--userns=keep-id`, or Quadlet `UserNS=keep-id`).
The recommendation is to omit `:z` and `:Z` on bind mounts whose
source is a mergerfs (or any other FUSE) path, and to keep them on
bind mounts whose source is a regular local filesystem (ext4, btrfs,
xfs, etc.) where relabeling does real work. On distributions whose
container-selinux policy does not already include the `fusefs_t`
allow rule, the targeted fix is to set a single label at mount time
by adding `context="system_u:object_r:container_file_t:s0"` to the
mergerfs mount options (for example in `/etc/fstab`). Files inside
the pool then appear as `container_file_t`, which container-selinux
permits `container_t` to manage everywhere. See [Red Hat's mounting
file systems
guide](https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/7/html/selinux_users_and_administrators_guide/sect-security-enhanced_linux-working_with_selinux-mounting_file_systems).
This is preferred over the much broader
`--security-opt label=disable`, which removes SELinux confinement
from the container as a whole. The trade-off of `context=` is that
host-side processes touching the mount (rsync, backup tools, web
UIs, cron jobs) see `container_file_t` rather than `fusefs_t` and
may require a small SELinux policy adjustment.
To verify on your own system:
```
podman --log-level=debug run --rm \
-v /path/to/mergerfs:/data:z \
alpine true 2>&1 | grep -iE 'relabel|setfilecon|Labeling'
```
Expected output is a single line of the form
`Labeling not supported on "/path/to/mergerfs"` and nothing in
`ausearch -m AVC,SELINUX_ERR` for the mount.
## Can mergerfs be used with NFS root squash? ## Can mergerfs be used with NFS root squash?
If mergerfs is pooling a NFS mount then root squash must be disabled If mergerfs is pooling a NFS mount then root squash must be disabled

View file

@ -18,12 +18,6 @@ mergerfs [does not impact](usage_and_functionality.md) the underlying
filesystems and can be added or removed without any impact it is filesystems and can be added or removed without any impact it is
extremely easy to test and experiment with different settings. extremely easy to test and experiment with different settings.
[mergerfs-webui](../tooling.md#mergerfs-webui) provides a browser-based
way to inspect and change settings, branches, and policies on Linux,
and edit startup configuration. It does not replace understanding
what the options do or choosing policies suited to your use case.
Runtime changes alone do not persist across remounts.
Additional reading: Additional reading:
* [Config/Options](../config/options.md) * [Config/Options](../config/options.md)

View file

@ -1,218 +0,0 @@
# Downsides
## What are the downsides of using mergerfs?
mergerfs trades the features of an integrated storage system for the
flexibility of pooling independent filesystems. It is a filesystem
proxy, not RAID or a replacement for the underlying filesystems.
Some limitations are inherent to that design; others matter only for
particular workloads, configurations, or applications. Many can be
mitigated with appropriate settings or separate tools. The following
is a checklist of tradeoffs to evaluate, not a list of problems every
installation will experience.
### No built-in data protection or storage management
mergerfs does not provide redundancy, parity, integrity checks,
snapshots, or file versioning. If a drive fails, mergerfs cannot
recover the files on it. The other drives retain their independent
filesystems, but that failure isolation is not redundancy or a backup.
Protection must come from the underlying storage or separate tools,
such as [SnapRAID](https://www.snapraid.it) or
[NonRAID](https://github.com/qvr/nonraid).
It also does not automatically rebalance existing files when a branch
is added or space usage changes. If redistribution is needed, it must
be done separately.
See [Non-features](../index.md#non-features), [Project
Comparisons](../project_comparisons.md), and [How can I balance files
across the pool?](configuration_and_policies.md#how-can-i-balance-files-across-the-pool).
### No striping or contiguous pooled space
Each file lives entirely on one branch. Adding drives does not make a
single-file transfer faster, and a file must fit on one eligible
branch even if the pool reports enough total free space. For example,
two filesystems with 6GiB free each cannot hold one 10GiB file.
Concurrent access to different branches can still provide aggregate
throughput.
See [Project Comparisons](../project_comparisons.md#raid0-jbod-span-drive-concatenation-striping)
and [Performance](../performance.md#understanding-mergerfs-io-performance).
### Performance overhead
Filesystem requests generally pass through FUSE and the mergerfs
process before reaching the underlying filesystem. This adds latency
and CPU overhead compared to direct access. Directory listings and
other metadata operations can require work across multiple branches,
so their cost can grow as the pool grows. Page caching can also result
in data being cached both through mergerfs and on the underlying
filesystem.
[IO passthrough](../config/passthrough.md) can reduce data IO overhead,
but does not eliminate the work of combining branches. Databases, VM
images, and other latency-sensitive workloads should be benchmarked
with the intended configuration rather than assumed to perform like
direct access.
There is also memory overhead beyond page caching: request buffers,
temporary directory buffers, and FUSE node bookkeeping. Usage depends
on concurrency, buffer sizes, and the workload. Exporting the pool
over NFS requires retaining nodes with `never-forget-nodes=true`,
which can increase memory usage as more entries are accessed. This is
worth considering on memory-constrained systems or large NFS exports.
See [Resource Usage](../resource_usage.md) and [NFS exporting
mergerfs](../remote_filesystems.md#nfs-exporting-mergerfs).
See [Understanding mergerfs IO
Performance](../performance.md#understanding-mergerfs-io-performance),
[Benchmarking](../benchmarking.md), and [Why use
FUSE?](technical_behavior_and_limitations.md#why-use-fuse-why-not-a-kernel-based-solution).
### Placement and filesystem semantics need attention
A single mount point does not make the branches one filesystem.
[Policies](../config/functions_categories_policies.md) determine where
new files go and which copy is used when the same path exists on
multiple branches. Path-preserving policies and
[minfreespace](../config/minfreespace.md) can exclude branches from file
creation even while the pool has free space. mergerfs cannot know a
file's final size when it is created.
Hard links and renames still have underlying filesystem constraints.
Depending on the layout and policies, an operation can return `EXDEV`
(cross-device link) even within the pool. Applications which do not
handle that error may fail rather than fall back to copying.
Directory metadata is also selected by policy rather than necessarily
aggregated. With the default `getattr` policy of `ff`, a directory's
timestamp comes from the first matching branch. A media scanner which
uses that timestamp to skip unchanged directories can miss updates on
another branch. `func.getattr=newest` can help with timestamp-based
scans, but changes which branch supplies metadata; it does not change
which file other operations select.
Corresponding directories on different branches can have different
ownership or permissions. Since access uses the caller's credentials,
this can result in unexpected access errors or missing entries.
Keeping those permissions consistent and auditing with
`fsck.mergerfs` helps. Container UID/GID mappings and non-POSIX
branches may need additional attention; mergerfs does not bypass
their access restrictions.
See [Configuration and Policies](configuration_and_policies.md),
[rename and link](../config/rename_and_link.md), [Tips and
Notes](../tips_notes.md), and [How does mergerfs interact with user
namespaces?](compatibility_and_integration.md#how-does-mergerfs-interact-with-user-namespaces).
### Keeping drives spun down can be harder
Directory listings and file searches can query multiple branches,
potentially waking drives beyond the one containing the requested
file. If keeping disks asleep is important, this can increase power
usage, noise, and access latency. It is not a concern for SSDs or
drives which are kept spinning.
Caching and reducing background scans can limit some branch access,
but mergerfs alone cannot guarantee that unused disks stay asleep.
See [Limiting drive spinup](limit_drive_spinup.md) for the tradeoffs
and possible approaches.
### Direct branch changes and cached views
Using the underlying filesystems directly is supported, but changes
made outside the mergerfs mount are not forwarded as `inotify` or
`fanotify` events to applications watching the pool. Changes made
through the pool do generate notifications. If files are added
directly to branches, applications such as media servers may need
periodic scans, explicit refreshes, or watches on the branches
themselves.
Metadata caching introduces a separate visibility tradeoff: direct
branch changes may not appear through the pool until cached entries
expire. Longer cache durations can reduce filesystem queries at the
cost of less immediate visibility. Shorter durations or disabling the
relevant caches can help if direct branch changes are common. Avoid
uncoordinated writes to the same file through both paths, especially
when file caching is enabled.
See [Does inotify and fanotify
work?](compatibility_and_integration.md#does-inotify-and-fanotify-work),
[Can filesystems still be used
directly?](usage_and_functionality.md#can-filesystems-still-be-used-directly-outside-of-mergerfs-while-pooled),
and [Caching](../config/cache.md).
### Branch paths do not guarantee a particular disk is mounted
mergerfs works on paths and does not require each branch to be a
mount point. If an intended branch filesystem is not mounted but its
mount-point directory still exists, mergerfs can use that directory
on the filesystem beneath it. If writable and selected for creation,
new files can land there instead of on the intended disk, potentially
filling the root filesystem.
This is a deployment concern when pooling mounted filesystems, not a
problem with intentionally using ordinary directories as branches.
Configure mount dependencies or
`branches-mount-timeout` with `branches-mount-timeout-fail=true` if
startup should fail when branches are not ready. These are startup
safeguards, not continuous checks that the intended disks remain
mounted at runtime.
See [branches-mount-timeout](../config/branches-mount-timeout.md) and
[What happens if a filesystem disappears at
runtime?](usage_and_functionality.md#what-happens-if-a-filesystem-disappears-at-runtime).
### Dependence on branch responsiveness
mergerfs cannot make an unresponsive disk or remote filesystem
responsive. A request to a blocked branch blocks the thread handling
it. If enough threads are blocked, the pool can stop responding as
well. Independent on-disk filesystems do not guarantee that a failing
branch has no effect on access through the pool.
See [What happens if a branch filesystem
blocks?](technical_behavior_and_limitations.md#what-happens-if-a-branch-filesystem-blocks).
### Compatibility limitations
Some filesystem features are unavailable through FUSE or require
particular kernel versions and settings. For example, reflink requests
(`FICLONE` / `FICLONERANGE`) are not supported through the mergerfs
mount. Applications using `mmap` need page caching; older Linux or
mergerfs versions require it to be explicitly enabled.
Advisory locks taken through the pool are not forwarded to the
underlying branches. Local applications using only the mergerfs mount
still have kernel-managed locks, but those locks do not coordinate
with direct branch access or other hosts accessing a remote branch.
Inode identity also has tradeoffs when presenting multiple filesystems
as one. Most applications do not need special settings, but backup or
deduplication tools and NFS can be sensitive to inode values changing
when files move between branches or a policy selects a different
copy. [inodecalc](../config/inodecalc.md) offers different strategies:
for example, `path-hash` stabilizes identity by path for NFS, but
prevents applications from recognizing hard links by inode equality.
The hard links themselves still work.
On SELinux systems, per-file relabeling is unavailable through the
FUSE mount, so container bind-mount options `:z` and `:Z` do not
perform their usual relabeling. This does not mean containers cannot
use the pool: an appropriate SELinux policy or a mount-wide context
can allow access. A mount-wide context is not a substitute for
distinct per-file labels if the application requires them. See [Does
mergerfs work with SELinux
relabeling?](compatibility_and_integration.md#does-mergerfs-work-with-selinux-relabeling).
See [Technical Behavior and
Limitations](technical_behavior_and_limitations.md) and [Known Issues
and Bugs](../known_issues_bugs.md).
These tradeoffs do not require migrating data into a special format.
The underlying filesystems remain usable without mergerfs, and
mergerfs can be [removed without changing their
data](usage_and_functionality.md#can-mergerfs-be-removed-without-affecting-the-data).

View file

@ -261,12 +261,6 @@ As of v2.42.0 mergerfs now runs as root more generally. Either
changing credentials when creating files (Linux) or chown'ing them changing credentials when creating files (Linux) or chown'ing them
after creation (FreeBSD). after creation (FreeBSD).
The optional EXDEV link and rename fallbacks create replacement
symlinks under daemon credentials and then preserve the source inode's
UID and GID. They do not use the link or rename request's UID/GID:
these may be invalid with `allow-idmap`. Ordinary symlink creation
continues to use the creation request's credentials.
As a result of this change it is now necessary for the FUSE As a result of this change it is now necessary for the FUSE
`default_permissions` feature be used for proper entitlements `default_permissions` feature be used for proper entitlements
management. mergerfs does allow it to be disabled but it should only management. mergerfs does allow it to be disabled but it should only

View file

@ -81,7 +81,7 @@ where it was created.
$ sudo touch /mnt/mergerfs/new-file $ sudo touch /mnt/mergerfs/new-file
$ sudo getfattr -n user.mergerfs.allpaths /mnt/mergerfs/new-file $ sudo getfattr -n user.mergerfs.allpaths /mnt/mergerfs/new-file
# file: mnt/mergerfs/new-file # file: mnt/mergerfs/new-file
user.mergerfs.allpaths="/mnt/hdd/disk0/new-file" user.mergerfs.allpaths="/mnt/hdd/drive1/new-file"
``` ```
If the location of the file is where it should be according to the If the location of the file is where it should be according to the
@ -119,7 +119,7 @@ may be able to read some files and directories on one filesystem but
not another resulting in an incomplete set. And if one of the branches not another resulting in an incomplete set. And if one of the branches
it can access is empty then it will return an empty list. it can access is empty then it will return an empty list.
Try using [fsck.mergerfs](../tooling.md#fsckmergerfs) Try using [mergerfs.fsck](https://github.com/trapexit/mergerfs-tools)
tool to check for and fix inconsistencies in permissions. If you tool to check for and fix inconsistencies in permissions. If you
aren't seeing anything at all be sure that the basic permissions are aren't seeing anything at all be sure that the basic permissions are
correct. The user and group values are correct and that directories correct. The user and group values are correct and that directories

View file

@ -105,7 +105,7 @@ The way in which mergerfs behaves is controlled by the
``` ```
A + B = C A + B = C
/mnt/hdd/disk0 /mnt/hdd/disk1 /media /disk1 /disk2 /merged
| | | | | |
+-- /dir1 +-- /dir1 +-- /dir1 +-- /dir1 +-- /dir1 +-- /dir1
| | | | | | | | | | | |

View file

@ -92,15 +92,15 @@ If you always want the directory information from the one with the
most recent mtime then use the `newest` policy for `getattr`. most recent mtime then use the `newest` policy for `getattr`.
### 'mv /mnt/pool/foo /mnt/hdd/disk0/foo' removes 'foo' ### 'mv /mnt/pool/foo /mnt/disk1/foo' removes 'foo'
This is not a bug. This is not a bug.
Run in verbose mode to better understand what's happening: Run in verbose mode to better understand what's happening:
``` ```
$ mv -v /mnt/pool/foo /mnt/hdd/disk0/foo $ mv -v /mnt/pool/foo /mnt/disk1/foo
copied '/mnt/pool/foo' -> '/mnt/hdd/disk0/foo' copied '/mnt/pool/foo' -> '/mnt/disk1/foo'
removed '/mnt/pool/foo' removed '/mnt/pool/foo'
$ ls /mnt/pool/foo $ ls /mnt/pool/foo
ls: cannot access '/mnt/pool/foo': No such file or directory ls: cannot access '/mnt/pool/foo': No such file or directory

View file

@ -1,185 +0,0 @@
# Migration
## Unraid
mergerfs and a parity-protected Unraid array can both present
directories from multiple filesystems as a single view, but they treat
storage membership very differently. With mergerfs, membership is a
property of its **configuration**: branches are paths and can be added
or removed at runtime without modifying the underlying filesystems.
With Unraid's main array, membership is part of the **array state**:
adding a data disk to an array with active parity normally requires
clearing and formatting it, and removing one normally requires parity
to be rebuilt.
Those array-level requirements, not the User Share filesystem itself,
are what shape migrations in either direction. When moving to mergerfs,
existing data filesystems can usually be reused as-is. When moving to
Unraid, populated filesystems can normally only be brought into the
array before parity is activated. See [Project
Comparisons](project_comparisons.md#unraid) for the comparison itself.
| Operation | mergerfs | Unraid array with parity |
| --- | --- | --- |
| Add an empty filesystem | Add its mount path as a branch | Clear if necessary, then format and add |
| Add a populated filesystem | Add its mount path; data is immediately visible | Not normally possible once parity is active without destroying its contents |
| Mix filesystem types | Any filesystem the host can mount | Supported array filesystem types only |
| Mix device sizes | Arbitrary | Data disks cannot exceed the parity disk size |
| Change membership while mounted | Supported through the [runtime interface](runtime_interface.md) | Array configuration normally requires stopping and restarting the array |
| Remove a filesystem and retain it unchanged | Remove the branch | Possible, but normal array removal requires parity to be rebuilt |
| Remove a filesystem without recalculating parity | Not applicable | Requires zeroing the disk, destroying its filesystem |
### Migrating from Unraid to mergerfs
Unraid array data disks each hold a complete, individually formatted
filesystem. `shfs` only unions their top-level directories, so there
is no striped or parity-dependent layout to unwind. After cleanly
stopping the array, unencrypted data filesystems can be mounted under
Linux and their mount points used directly as mergerfs branches. The
files do not need to be rewritten merely because the pooling
implementation changed.
For [encrypted Unraid disks](https://docs.unraid.net/unraid-os/system-administration/secure-your-server/securing-your-data/),
securely retain the existing passphrase or key file before retiring
Unraid. Open each disk's existing LUKS container with `cryptsetup`
using those credentials, then mount the inner filesystem through its
`/dev/mapper/` device and use that mount point as a branch. Do not
reformat the disk or create a new LUKS container. Without a working
passphrase or key file, the encrypted data cannot be accessed.
```
Unraid:
disk1 ─┐
disk2 ─┼─> shfs ─> /mnt/user
disk3 ─┘
+
parity
mergerfs:
disk1 ─┐
disk2 ─┼─> mergerfs ─> /mnt/storage
disk3 ─┘
```
Unraid's convention of representing shares as identically named
top-level directories also maps naturally to mergerfs' union
semantics.
* The parity disk is not a data filesystem and cannot become a branch
as-is. It can be reformatted as another data disk if parity
protection is no longer desired, or a separate parity solution such
as [SnapRAID](https://www.snapraid.it) or
[NonRAID](https://github.com/qvr/nonraid) can be used alongside
mergerfs if redundancy is still wanted.
* If migrating incrementally while keeping the remaining Unraid array
operational, the normal Unraid disk-removal and parity-rebuild
requirements still apply to each disk removed.
* If the entire array is being retired at once, those intermediate
Unraid parity rebuilds are unnecessary. Stop the array cleanly and
use the existing data filesystems as branches.
* Named pools need care. A pool backed by a single filesystem can be
mounted and used as one branch. A multi-device Btrfs or ZFS pool is
not equivalent to a collection of independent Unraid array disks: it
can either remain intact and be mounted as one mergerfs branch, or
its data must be migrated elsewhere before its component devices can
be repurposed as independent filesystems.
### Migrating from mergerfs to Unraid
mergerfs places no special metadata on its branches, so their
underlying filesystems remain unchanged. Direct reuse as Unraid array
data disks requires local disks with a supported filesystem **and a
partition layout accepted by the installed Unraid version**. A
supported filesystem type alone is not sufficient.
In particular, mergerfs can use a filesystem formatted directly on a
whole device, such as `/dev/sda`, without a partition table. Unraid
array data disks require a filesystem within a compatible partition.
Such unpartitioned filesystems cannot be imported directly: back up
their data, let Unraid partition and format the disks, then restore
the files. Creating a partition table over the existing filesystem is
not a safe conversion. Check Unraid's
[partitioning guidance](https://docs.unraid.net/unraid-os/troubleshooting/faq/)
before planning a no-copy migration.
Current versions of Unraid support importing populated disks when
constructing a new array, or after resetting the array configuration,
provided that the populated data disks are added **before parity is
activated**. Such a migration can therefore often be performed without
copying the data:
1. Stop mergerfs and cleanly unmount the branch filesystems.
2. Create or reset the Unraid array configuration.
3. Assign all populated mergerfs disks as data disks while no parity
disk is active.
4. Verify that the existing filesystems and data are recognized
correctly. If a populated disk is reported as unmountable, stop and
investigate; do not format it, as formatting destroys its contents.
5. Assign a parity disk at least as large as the largest data disk.
6. Build parity over the completed array.
Once parity has been established, that convenient path is effectively
closed. Adding another populated mergerfs disk to the parity-protected
array would require Unraid to clear the disk, destroying the existing
filesystem. A staged migration in which populated mergerfs disks are
added one at a time therefore generally requires either copying their
contents into the existing array first or resetting/reconstructing the
Unraid configuration so that all populated data disks are present
before parity is established.
Additional array-level constraints to keep in mind:
* Only filesystem types supported by Unraid can be assigned as array
data disks.
* No array data disk may be larger than the parity disk.
* Array configuration changes normally require stopping and restarting
the array. Removing a data disk normally requires a parity rebuild,
and Unraid's parity-preserving removal procedure works by erasing
the filesystem and zeroing the disk, so it is unsuitable when the
goal is to retain that filesystem for use elsewhere.
When migrating into individual **Unraid array data slots**, the
following configurations require copying data to suitable array
filesystems rather than reusing the source storage directly:
* Remote filesystems or filesystem types Unraid does not support.
* Storage that cannot be presented as a single array device, such as
multi-device Btrfs or ZFS pools or `mdadm` arrays.
This restriction does not rule out retaining storage as a named pool.
A compatible multi-device ZFS pool can be
[imported into Unraid](https://docs.unraid.net/unraid-os/advanced-configurations/optimize-storage/zfs-storage/#importing-zfs-pools-created-on-other-systems)
intact, without copying its data. Stop mergerfs and cleanly export the
pool on the source system. With the Unraid array stopped, use **Add
Pool**, assign all of the pool's devices (including support vdevs),
set **File System** to **Auto**, and start the array to import it.
If it is not recognized, investigate rather than format its devices.
The imported pool remains separate from the parity-protected array;
its redundancy comes from its ZFS layout, not Unraid array parity.
A branch pointing at a subdirectory does **not** by itself require a
data copy: eligibility depends on its underlying disk and filesystem.
For example, importing compatible disks that contributed
`/mnt/disk1/media` and `/mnt/disk2/media` preserves their contents, and
Unraid combines the top-level `media` directories into a
[User Share](https://docs.unraid.net/unraid-os/using-unraid-to/manage-storage/shares/#user-shares).
Review the desired share layout; deeper branch directories may need
to be reorganized within their existing filesystems rather than
copied to new storage.
### Summary
mergerfs treats storage membership as a property of its
**configuration**, while a parity-protected Unraid array treats it as
part of the **array state**. Moving an existing filesystem into or out
of mergerfs normally does not alter that filesystem at all. Moving
populated filesystems into or out of an active Unraid parity array can
require clearing disks, rebuilding parity, moving data, or
reconstructing the array configuration.
For semi-static data, mergerfs + SnapRAID provides pooling and parity
while retaining the ability to add and remove independently formatted
filesystems without modifying them. NonRAID provides an alternative
real-time parity layer which can likewise be combined with mergerfs.

View file

@ -48,65 +48,6 @@ before changing them to understand how functionality will change.
* use LVM and LVM cache to place a SSD in front of your HDDs * use LVM and LVM cache to place a SSD in front of your HDDs
## Understanding mergerfs IO Performance
A common source of confusion when evaluating **mergerfs**' performance
is comparing it to traditional RAID or filesystem level pooling
technologies such as mdadm, ZFS, btrfs, or striped LVM. Those
solutions aggregate devices into a single virtual device and spread IO
across all members. Under favorable conditions that means the
performance of the pool is the sum of the performance of its members:
striped reads and writes hit multiple drives at once and the aggregate
throughput scales with the number of devices, up to the limits of the
interconnects (PCIe, SATA, network, etc.) which every member must
share.
**mergerfs** does not aggregate or stripe data. Every file lives
wholly on one branch and **mergerfs** simply routes access to it. As a
result **mergerfs** does not aggregate the performance of its branches
in the way RAID does. What it provides instead is **independent
performance across branches**.
* **Best case:** workloads which access different branches
concurrently perform independently of one another. If you have 3
filesystems on 3 drives and each is being actively used, the total
throughput can be A + B + C: the sum of each branch performing at
full speed. No single drive is a bottleneck for the others.
* **Worst case:** a single stream of IO - one process reading or
writing one file - performs at the speed of the single branch the
file is on, no differently than a lone filesystem. Additional
branches do not make a single file faster.
This means that when reasoning about expected performance the key
question is whether your workload is **single stream** or **multi
stream**:
* Single large file transfers, video playback, or one process doing
sequential IO will never exceed the speed of one branch regardless
of how many are mounted. If a single stream must be faster, put a
faster device (tiered cache, SSD, LVM cache) in front of the
branches or use an actual striped RAID layer beneath **mergerfs**'
branches.
* Concurrency across branches is where **mergerfs** shines. Many
parallel downloads, seeding torrents, multiple rsync streams,
multiple applications reading different files: these naturally
spread across branches and their throughput adds up.
There are practical upsides to this non-aggregated design as well:
* Drives of different sizes and speeds don't reduce the whole pool to
the slowest member. Each branch performs at its own speed.
* The failure of one drive only affects the files on that branch
rather than the integrity of the entire pool.
Finally, keep in mind that **mergerfs** is a proxy above the branches,
so measured throughput is the lesser of the branch's native performance
and any overhead introduced by **mergerfs** and FUSE. Use
[nullrw](config/options.md) or a ram disk as a branch to measure that
overhead separately, and see the [benchmarking
section](benchmarking.md) for how to benchmark meaningfully.
## Additional Reading ## Additional Reading
* [Benchmarking](benchmarking.md) * [Benchmarking](benchmarking.md)

View file

@ -2,11 +2,6 @@
There are no solutions, only trade-offs. There are no solutions, only trade-offs.
This page includes both direct pooling alternatives and adjacent storage
technologies that solve different problems. Compare their operating layer,
failure domain, redundancy model, and platform requirements rather than only
their apparent pool capacity.
## mhddfs ## mhddfs
@ -20,20 +15,17 @@ and security issues. mergerfs provides a superset of mhddfs' features
and offers better performance. As of 2020, the author of mhddfs has and offers better performance. As of 2020, the author of mhddfs has
[moved to using mergerfs.](https://romanrm.net/mhddfs#update) [moved to using mergerfs.](https://romanrm.net/mhddfs#update)
* **Better than mergerfs for:** Nothing? * **Better than mergerfs for:** legacy setups that already depend on
mhddfs-specific behavior and do not need newer features.
* **Worse than mergerfs for:** most modern deployments due to maintenance * **Worse than mergerfs for:** most modern deployments due to maintenance
status, feature coverage, and reliability. status, feature coverage, and reliability.
Below is an example of mhddfs and mergerfs set up to behave similarly. Below is an example of mhddfs and mergerfs setup to work similarly.
mhddfs falls back to the drive with the most free space when every drive
has less than `mlimit` free; mergerfs with
[minfreespace](config/minfreespace.md) filters those branches instead and
may fail the create if none qualify.
```sh ```
mhddfs -o mlimit=4G,allow_other /mnt/hdd/disk0,/mnt/hdd/disk1 /mnt/pool mhddfs -o mlimit=4G,allow_other /mnt/drive1,/mnt/drive2 /mnt/pool
mergerfs -o minfreespace=4G,category.create=ff /mnt/hdd/disk0:/mnt/hdd/disk1 /mnt/pool mergerfs -o minfreespace=4G,category.create=ff /mnt/drive1:/mnt/drive2 /mnt/pool
``` ```
@ -54,11 +46,10 @@ available in most Linux distros, making it harder to get installed for
the average user. Development has been largely dormant for years. the average user. Development has been largely dormant for years.
While aufs can often offer better peak performance due to being While aufs can often offer better peak performance due to being
primarily kernel-based (at least when primarily kernel-based (at least when `passthrough.io` is disabled in
[passthrough.io](config/passthrough.md) is disabled in mergerfs), mergerfs), mergerfs provides more configurability and is generally
mergerfs provides more configurability and is generally easier to use. easier to use. mergerfs, however, does not offer the overlay /
mergerfs, however, does not offer the overlay / copy-on-write (CoW) copy-on-write (CoW) features which aufs has.
features which aufs has.
* **Better than mergerfs for:** kernel-level overlay/CoW workloads where * **Better than mergerfs for:** kernel-level overlay/CoW workloads where
that behavior is required. that behavior is required.
@ -101,10 +92,9 @@ overlay/CoW-style layering, while mergerfs' primary feature is
policy-based pooling and placement across multiple regular writable policy-based pooling and placement across multiple regular writable
filesystems. filesystems.
As a FUSE filesystem, unionfs-fuse can often be mounted by an Since unionfs-fuse, as the name suggests, is a FUSE-based technology
unprivileged user when the system's FUSE configuration permits it. Kernel it can be used without elevated privileges that kernel solutions such
solutions such as unionfs, aufs, and overlayfs normally require additional as unionfs, aufs, and overlayfs require.
privileges.
* **Better than mergerfs for:** overlay-style unions with copy-on-write * **Better than mergerfs for:** overlay-style unions with copy-on-write
semantics in userspace. semantics in userspace.
@ -116,10 +106,10 @@ privileges.
* [https://docs.kernel.org/filesystems/overlayfs.html](https://docs.kernel.org/filesystems/overlayfs.html) * [https://docs.kernel.org/filesystems/overlayfs.html](https://docs.kernel.org/filesystems/overlayfs.html)
overlayfs is effectively the successor to unionfs, unionfs-fuse, and overlayfs is effectively the functional successor to unionfs,
aufs and is widely used by Linux container platforms such as Docker and unionfs-fuse, and aufs and is widely used by Linux container platforms
Podman. Both overlayfs and FUSE were originally created by Miklos such as Docker and Podman. Both overlayfs and FUSE were originally
Szeredi. created by Miklos Szeredi.
If your use case is layering a writable filesystem on top of read-only If your use case is layering a writable filesystem on top of read-only
filesystems then you should look first to overlayfs. Its feature set filesystems then you should look first to overlayfs. Its feature set
@ -131,24 +121,6 @@ however is very different from mergerfs and solves different problems.
flexible branch selection policies across many existing filesystems. flexible branch selection policies across many existing filesystems.
## fuse-overlayfs
* [https://github.com/containers/fuse-overlayfs](https://github.com/containers/fuse-overlayfs)
fuse-overlayfs implements overlayfs-style lower, upper, and work directories
in userspace. Its primary use case is rootless containers, where a kernel
overlayfs mount may not be available.
Like unionfs-fuse and kernel overlayfs, it provides layering and copy-up
semantics rather than mergerfs-style placement across a pool of writable
filesystems.
* **Better than mergerfs for:** rootless container and other unprivileged
overlay workloads.
* **Worse than mergerfs for:** general storage pooling across independent
writable filesystems.
## RAID0, JBOD, SPAN, drive concatenation, striping ## RAID0, JBOD, SPAN, drive concatenation, striping
* [RAID0](https://en.wikipedia.org/wiki/Standard_RAID_levels#RAID_0) * [RAID0](https://en.wikipedia.org/wiki/Standard_RAID_levels#RAID_0)
@ -156,10 +128,6 @@ filesystems.
* [SPAN](https://en.wikipedia.org/wiki/Non-RAID_drive_architectures#Concatenation_(SPAN,_BIG)) * [SPAN](https://en.wikipedia.org/wiki/Non-RAID_drive_architectures#Concatenation_(SPAN,_BIG))
* [striping](https://en.wikipedia.org/wiki/Data_striping) * [striping](https://en.wikipedia.org/wiki/Data_striping)
"JBOD" is ambiguous: it can also mean disks exposed independently with
no aggregation. In this section it refers only to concatenated or spanned
layouts.
These are block device technologies which, in some form, aggregate These are block device technologies which, in some form, aggregate
devices into what appears to be a single device on which a traditional devices into what appears to be a single device on which a traditional
filesystem can be used. The filesystem has no understanding of the filesystem can be used. The filesystem has no understanding of the
@ -194,12 +162,12 @@ allow the pool to continue to run should one device fail and rebuild
the data once the device is replaced. the data once the device is replaced.
mergerfs offers no parity or redundancy features so in that regard the mergerfs offers no parity or redundancy features so in that regard the
technologies are not comparable. [SnapRAID](https://www.snapraid.it) or technologies are not comparable. [SnapRAID](https://www.snapraid.it)
NonRAID (see [below](#nonraid)) can be used in combination with mergerfs or [NonRAID](https://github.com/qvr/nonraid) can be used in
to provide redundancy. Unlike traditional RAID5 or RAID6, SnapRAID works combination with mergerfs to provide redundancy. Unlike traditional
with drives of different sizes and can have more than 2 parity drives. RAID5 or RAID6 SnapRAID works with drives of different sizes and can
Parity calculations with SnapRAID are not done in real-time but have more than 2 parity drives. Parity calculations with SnapRAID are
NonRAID's are. not done in real-time but NonRAID's are.
For more details and comparison of SnapRAID to related technologies For more details and comparison of SnapRAID to related technologies
see [https://www.snapraid.it/compare](https://www.snapraid.it/compare). see [https://www.snapraid.it/compare](https://www.snapraid.it/compare).
@ -236,7 +204,7 @@ data on that disk.
## mdadm ## mdadm
* [https://en.wikipedia.org/wiki/Mdadm](https://en.wikipedia.org/wiki/Mdadm) * [https://en.wikipedia.org/wiki/Mdadm](https://en.wikipedia.org/wiki/Mdadm)
* [https://docs.kernel.org/admin-guide/md.html](https://docs.kernel.org/admin-guide/md.html) * [https://raid.wiki.kernel.org/index.php/A_guide_to_mdadm](https://raid.wiki.kernel.org/index.php/A_guide_to_mdadm)
`mdadm` is Linux userspace tooling for configuring and managing software `mdadm` is Linux userspace tooling for configuring and managing software
RAID arrays provided by the kernel `md` driver. It can build RAID0/1/4/5/6/10 RAID arrays provided by the kernel `md` driver. It can build RAID0/1/4/5/6/10
@ -258,7 +226,7 @@ be combined with tools like SnapRAID or NonRAID when redundancy is needed.
## device mapper ## device mapper
* [https://en.wikipedia.org/wiki/Device_mapper](https://en.wikipedia.org/wiki/Device_mapper) * [https://en.wikipedia.org/wiki/Device_mapper](https://en.wikipedia.org/wiki/Device_mapper)
* [https://docs.kernel.org/admin-guide/device-mapper/index.html](https://docs.kernel.org/admin-guide/device-mapper/index.html) * [https://docs.kernel.org/admin-guide/device-mapper](https://docs.kernel.org/admin-guide/device-mapper)
Device mapper is a kernel framework for creating virtual block devices Device mapper is a kernel framework for creating virtual block devices
from one or more underlying devices. Technologies such as LVM, from one or more underlying devices. Technologies such as LVM,
@ -276,11 +244,11 @@ later pool if desired.
across many independent, already-formatted filesystems. across many independent, already-formatted filesystems.
## Unraid ## UnRAID
* [https://unraid.net](https://unraid.net) * [https://unraid.net](https://unraid.net)
Unraid is a full OS platform that offers pooled storage with integrated UnRAID is a full OS platform that offers pooled storage with integrated
real-time parity. Compared with mergerfs, its main advantage is that it real-time parity. Compared with mergerfs, its main advantage is that it
bundles pooling and parity in one product, while mergerfs is a bundles pooling and parity in one product, while mergerfs is a
standalone Linux pooling filesystem without built-in redundancy. For standalone Linux pooling filesystem without built-in redundancy. For
@ -289,20 +257,14 @@ approach is also preferable.
For semi-static data, mergerfs + [SnapRAID](https://www.snapraid.it) For semi-static data, mergerfs + [SnapRAID](https://www.snapraid.it)
provides a similar, but not real-time, solution. provides a similar, but not real-time, solution.
[NonRAID](https://github.com/qvr/nonraid) (see [below](#nonraid)) is a [NonRAID](https://github.com/qvr/nonraid) (see below) is a
fork of Unraid's parity calculation solution and can also be used with fork of UnRAID's parity calculation solution and can also be used with
mergerfs. mergerfs.
Moving between the two is not symmetric because mergerfs membership is
a configuration change while Unraid array membership is part of the
array state. See [Migration](migration.md) for details.
* **Better than mergerfs for:** turnkey pooling plus integrated real-time * **Better than mergerfs for:** turnkey pooling plus integrated real-time
parity in one product. parity in one product.
* **Worse than mergerfs for:** non-destructive incremental addition and * **Worse than mergerfs for:** users who prefer a Linux distro-agnostic,
removal of populated filesystems, arbitrary branch types and filesystem fully open-source component approach.
layouts, and users who prefer a Linux distro-agnostic, fully open-source
component approach.
## NonRAID ## NonRAID
@ -310,7 +272,7 @@ array state. See [Migration](migration.md) for details.
* [https://github.com/qvr/nonraid](https://github.com/qvr/nonraid) * [https://github.com/qvr/nonraid](https://github.com/qvr/nonraid)
[NonRAID](https://github.com/qvr/nonraid#how-it-works) is a fork of [NonRAID](https://github.com/qvr/nonraid#how-it-works) is a fork of
Unraid's storage array kernel driver. Effectively it is like RAID5 at UnRAID's storage array kernel driver. Effectively it is like RAID5 at
the block device layer without treating the collection of devices as a the block device layer without treating the collection of devices as a
single device. Each device gets a virtual block device associated with single device. Each device gets a virtual block device associated with
it which can be formatted with the filesystem of the user's choice and it which can be formatted with the filesystem of the user's choice and
@ -331,7 +293,7 @@ be used with mergerfs for those looking for a unified view.
## ZFS ## ZFS
* [https://openzfs.github.io/openzfs-docs](https://openzfs.github.io/openzfs-docs) * [https://en.wikipedia.org/wiki/ZFS](https://en.wikipedia.org/wiki/ZFS)
ZFS is an advanced filesystem that combines storage pooling, ZFS is an advanced filesystem that combines storage pooling,
snapshots, data integrity checking, and built-in RAID-like redundancy snapshots, data integrity checking, and built-in RAID-like redundancy
@ -351,78 +313,72 @@ without built-in redundancy.
## ZFS AnyRAID ## ZFS AnyRAID
* [Announcement](https://docs.hexos.com/blog/2025-05-22) * [https://github.com/openzfs/zfs/discussions/16773](https://github.com/openzfs/zfs/discussions/16773)
* [Development update](https://docs.hexos.com/blog/2026-7-15)
ZFS AnyRAID is under development to support mixed-capacity disks while [ZFS AnyRAID](https://github.com/openzfs/zfs/discussions/16773)
retaining ZFS redundancy. The planned layouts include mirrored and RAID-Z ([announcement](https://hexos.com/blog/introducing-zfs-anyraid-sponsored-by-eshtek))
variants, along with rebalancing and pool contraction work. is a feature under development for ZFS intended to provide more
flexibility in pools by allowing mixed-capacity disks while
maintaining live redundancy.
Availability is still landing in OpenZFS. Published notes indicate initial If released, ZFS AnyRAID would offer some of the flexibility associated
mirror layouts may ship in a 2.4.x release, with broader RAID-Z variants, with mergerfs-style mixed-capacity expansion, but with built-in
rebalancing, and pool contraction targeted for later releases. Treat redundancy inside ZFS. mergerfs already provides that mixed-size,
release and downstream product-integration dates as roadmap targets add-drives-anytime flexibility today, albeit without built-in
rather than commitments. redundancy. If you need redundancy with that flexibility, ZFS AnyRAID
could become an option when available; until then, mergerfs remains the
Where available, AnyRAID would offer some of the mixed-size flexibility simpler currently available choice for mixed-capacity pooling, with
associated with mergerfs while retaining redundancy inside ZFS. mergerfs redundancy and integrity available via SnapRAID and/or NonRAID.
provides mixed-size, add-drives-anytime pooling today, but without
built-in redundancy; SnapRAID or NonRAID can provide separate
protection.
* **Better than mergerfs for:** users who want mixed-capacity flexibility * **Better than mergerfs for:** users who want mixed-capacity flexibility
and built-in live redundancy in one filesystem stack. and built-in live redundancy in one filesystem stack.
* **Worse than mergerfs for:** users who need production availability now or * **Worse than mergerfs for:** users who need mature availability now and
want to pool existing filesystems without migrating data. the simplest add-drives-anytime workflow without redundancy overhead.
## bcachefs ## Bcachefs
* [https://bcachefs.org](https://bcachefs.org) * [https://bcachefs.org](https://bcachefs.org)
bcachefs is a modern copy-on-write filesystem for Linux designed for Bcachefs is a modern copy-on-write filesystem for Linux designed for
multi-device storage aggregation. It includes integrated features such as multi-device storage aggregation. It includes integrated features such
checksumming, snapshots, compression, encryption, and redundancy. as checksumming, snapshots, compression, encryption, and redundancy.
Compared with mergerfs, bcachefs is a full integrated filesystem, while Compared with mergerfs, bcachefs is a full integrated filesystem with
mergerfs is a lightweight pooling layer over existing filesystems. Beginning built-in checksumming, snapshots, compression, and redundancy, while
with Linux 6.18, bcachefs is no longer distributed in the mainline kernel; the mergerfs is a lightweight pooling layer over existing filesystems.
project now distributes it as an external DKMS module. It remains actively Bcachefs is still evolving and should be evaluated carefully for
developed, but deployments must account for kernel compatibility and its production use.
shorter operational history.
* **Better than mergerfs for:** integrated CoW filesystem features, * **Better than mergerfs for:** integrated CoW filesystem features,
checksumming, snapshots, compression, and built-in multi-device checksumming, snapshots, compression, and built-in multi-device
redundancy. redundancy.
* **Worse than mergerfs for:** pooling existing filesystems without * **Worse than mergerfs for:** conservative production setups prioritizing
reformatting, mainline-kernel availability, and per-disk native access. maturity, simplicity, and broad long-term deployment stability.
## Btrfs multi-device filesystems ## Btrfs Single Data Profile
* [https://btrfs.readthedocs.io/en/latest/Volume-management.html](https://btrfs.readthedocs.io/en/latest/Volume-management.html) * [https://btrfs.readthedocs.io](https://btrfs.readthedocs.io)
Btrfs can combine multiple devices in one filesystem and select separate [Btrfs'](https://btrfs.readthedocs.io) `single` data profile is a
allocation profiles for data and metadata. The `single` data profile spreads multi-device Btrfs mode that can spread data across drives without
one copy of data across available devices without redundancy; other profiles adding redundancy.
provide mirroring, striping, or parity with different capacity and failure
trade-offs.
Compared with mergerfs, multi-device Btrfs is one integrated filesystem, Compared with mergerfs, Btrfs `single` is managed as one integrated
while mergerfs pools separate existing filesystems. Losing a device from a filesystem, while mergerfs pools separate existing filesystems. In
`single` profile can make the whole Btrfs filesystem incomplete. Redundant Btrfs `single`, losing one device can impact the whole filesystem;
profiles change that risk, but the member devices still are not independently with mergerfs, loss is typically limited to data on the failed disk.
mountable filesystems.
* **Better than mergerfs for:** integrated checksumming, snapshots, balancing, * **Better than mergerfs for:** integrated multi-device management in one
and selectable redundancy profiles. filesystem namespace.
* **Worse than mergerfs for:** pooling existing mixed filesystem types, * **Worse than mergerfs for:** users who value per-disk failure isolation
per-disk native access, and failure isolation without redundancy. and easy independent recovery.
## StableBit's DrivePool ## StableBit's DrivePool
* [https://stablebit.com/DrivePool/Features](https://stablebit.com/DrivePool/Features) * [https://stablebit.com](https://stablebit.com)
DrivePool is a commercial storage pooling product for Windows that DrivePool is a commercial storage pooling product for Windows that
combines multiple drives into a single volume and includes balancing combines multiple drives into a single volume and includes balancing
@ -443,17 +399,19 @@ external-tool composability.
* [https://learn.microsoft.com/en-us/windows-server/storage/storage-spaces/overview](https://learn.microsoft.com/en-us/windows-server/storage/storage-spaces/overview) * [https://learn.microsoft.com/en-us/windows-server/storage/storage-spaces/overview](https://learn.microsoft.com/en-us/windows-server/storage/storage-spaces/overview)
Windows Storage Spaces is Microsoft's block-level storage virtualization Windows Storage Spaces is Microsoft's software-defined storage
platform for Windows. It aggregates physical disks into storage pools from platform for Windows Server and Windows Pro. It aggregates multiple
which virtual disks can be created with simple, mirror, or parity layouts. physical disks into logical storage pools with built-in redundancy
Supported Windows Server configurations can also use faster media as a options (mirroring, parity) and automatic performance optimization
Storage Bus Cache. through tiered caching.
Unlike mergerfs, Storage Spaces manages the member devices below the Storage Spaces is Windows-only and requires more planning upfront due
filesystem and stripes or mirrors data according to the selected layout. to redundancy options and RAID-like features. mergerfs is
This can provide integrated resilience and one contiguous volume, but member Linux-focused and takes a simpler approach, pooling existing
disks are not independently readable filesystems. mergerfs instead pools filesystems without built-in redundancy. If you need a Windows
existing filesystems and leaves their files directly accessible. solution with integrated data protection, Storage Spaces is a good
choice. For Linux users seeking lightweight pooling without redundancy
overhead, mergerfs is the better option.
* **Better than mergerfs for:** Windows environments needing integrated * **Better than mergerfs for:** Windows environments needing integrated
pooling, resilience, and tiering in the platform stack. pooling, resilience, and tiering in the platform stack.
@ -481,25 +439,6 @@ Plan 9 isn't a widely used OS so this comparison is mostly academic.
practical deployment availability. practical deployment availability.
## 9P
* [https://en.wikipedia.org/wiki/9P_(protocol)](https://en.wikipedia.org/wiki/9P_(protocol))
[9P](https://en.wikipedia.org/wiki/9P_(protocol)) is a filesystem
protocol from the Plan 9 operating system used to access files over a
network between systems.
Compared with mergerfs, 9P is a network filesystem protocol, while
mergerfs is a local Linux FUSE filesystem for pooling directories and
filesystems under one mount with branch policies. Like the Plan 9 binds
comparison above, this is mostly academic for typical mergerfs users.
* **Better than mergerfs for:** lightweight network filesystem protocol
use between compatible systems.
* **Worse than mergerfs for:** local Linux filesystem pooling because it
does not provide mergerfs-like branch policies or pooling semantics.
## SnapRAID pooling ## SnapRAID pooling
* [https://www.snapraid.it/manual](https://www.snapraid.it/manual) * [https://www.snapraid.it/manual](https://www.snapraid.it/manual)
@ -559,7 +498,7 @@ given the differing feature sets and focuses of the two projects.
## distributed filesystems ## distributed filesystems
* [AFS](https://www.openafs.org) * [AFS](https://www.openafs.org)
* [Ceph/CephFS](https://docs.ceph.com/en/latest/cephfs/) * [Ceph/CephFS](https://ceph.io)
* [GlusterFS](https://www.gluster.org) * [GlusterFS](https://www.gluster.org)
* [LizardFS](https://lizardfs.com) * [LizardFS](https://lizardfs.com)
* [MooseFS](https://moosefs.com) * [MooseFS](https://moosefs.com)
@ -600,8 +539,8 @@ pooling through normal POSIX filesystem calls.
Given its design nofs is not suited for general usage as third-party Given its design nofs is not suited for general usage as third-party
applications will not be able to take advantage of the unioning applications will not be able to take advantage of the unioning
behavior it offers. It is primarily for simpler situations where behavior it offers. It is primarily for more simple situations where
mergerfs cannot be used. something like mergerfs is unable to be used.
* **Better than mergerfs for:** constrained environments where a FUSE * **Better than mergerfs for:** constrained environments where a FUSE
mount is not possible but command-style union behavior is acceptable. mount is not possible but command-style union behavior is acceptable.
@ -609,34 +548,32 @@ mergerfs cannot be used.
usable by arbitrary third-party applications. usable by arbitrary third-party applications.
## PolicyFS ## policyfs
* [https://policyfs.org](https://policyfs.org) * [https://policyfs.org](https://policyfs.org)
* [https://github.com/hieutdo/policyfs](https://github.com/hieutdo/policyfs) * [https://github.com/hieutdo/policyfs](https://github.com/hieutdo/policyfs)
PolicyFS is a Linux FUSE storage daemon that unifies multiple storage policyfs is a Linux FUSE storage daemon that unifies multiple storage
paths under a single mountpoint, similarly to mergerfs. Its paths under a single mountpoint, similarly to mergerfs. Its
distinguishing features are explicit path-pattern-based routing rules distinguishing features are explicit path-pattern-based routing rules
for placement, and an optional SQLite metadata index that can serve for placement, and an optional SQLite metadata index that can serve
`readdir` and `getattr` operations without spinning up HDDs. `readdir` and `getattr` operations without spinning up HDDs.
Compared with mergerfs, PolicyFS emphasizes explicit path-based routing, Compared with mergerfs, policyfs emphasizes explicit path-based routing
scheduled SSD-to-HDD movement, and optional metadata indexing. mergerfs and optional metadata indexing, while mergerfs emphasizes a broad,
emphasizes a broader policy-driven pooling model with longer operational policy-driven pooling model with longer operational history and wider
history and wider application compatibility. mergerfs does not try to prevent adoption. It doesn't try limiting spinup as doing so fundimentally is
metadata operations from waking branches because doing so fundamentally in [conflict with other features.](faq/limit_drive_spinup.md)
[conflicts with other features.](faq/limit_drive_spinup.md)
PolicyFS's indexed storage deliberately defers some delete, rename, and Due to the nature of PolicyFS it can not really be used while changing
attribute operations until a maintenance job runs. Out-of-band changes require files out-of-band and with the delayed writeback of metadata and
the index to be refreshed, and its documentation identifies limits around unlinking there is a greater risk of inconsistancy in error
`O_DIRECT`, advisory locks, NFS re-export, and full POSIX coverage. Those are conditions.
material trade-offs, not only maturity differences.
* **Better than mergerfs for:** explicit path-based routing, scheduled * **Better than mergerfs for:** explicit path-based routing and optional
tiering, and metadata indexing designed to reduce HDD spin-ups. metadata indexing to reduce HDD spin-ups.
* **Worse than mergerfs for:** broad POSIX compatibility, immediate mutation * **Worse than mergerfs for:** users prioritizing project maturity,
semantics on every branch, and long-established operational behavior. adoption, performance, and long-established operational behavior.
## Greyhole ## Greyhole
@ -656,4 +593,22 @@ Linux FUSE mount for local pooling via standard POSIX filesystem calls.
* **Better than mergerfs for:** Samba-centric environments that need * **Better than mergerfs for:** Samba-centric environments that need
built-in per-share redundancy in the same tool. built-in per-share redundancy in the same tool.
* **Worse than mergerfs for:** general-purpose local filesystem pooling * **Worse than mergerfs for:** general-purpose local filesystem pooling
outside Samba, and for heavy small-file churn workloads. outside Samba and heavy small-file churn workloads.
## 9P
* [https://en.wikipedia.org/wiki/9P_(protocol)](https://en.wikipedia.org/wiki/9P_(protocol))
[9P](https://en.wikipedia.org/wiki/9P_(protocol)) is a filesystem
protocol from the Plan 9 operating system used to access files over a
network between systems.
Compared with mergerfs, 9P is a network filesystem protocol, while
mergerfs is a local Linux FUSE filesystem for pooling directories and
filesystems under one mount with branch policies.
* **Better than mergerfs for:** lightweight network filesystem protocol
use between compatible systems.
* **Worse than mergerfs for:** local Linux filesystem pooling because it
does not provide mergerfs-like branch policies or pooling semantics.

View file

@ -62,84 +62,28 @@ For some suggestions on branch setup see [the page on
branches](config/branches.md#branch-setup). branches](config/branches.md#branch-setup).
### Web UI
[mergerfs-webui](tooling.md#mergerfs-webui) provides a browser-based
alternative for creating and managing mounts on Linux. It can edit
startup configuration and inspect and change settings on running
mounts. See the
[mergerfs-webui documentation](https://github.com/trapexit/mergerfs-webui#readme)
for installation and secure access guidance. Runtime changes alone do
not persist across remounts.
### Command Line ### Command Line
``` ```
# Two positional options: `:` colon separated branches and mountpoint # Two positional options: `:` colon separated branches and mountpoint
mergerfs -o opt[,opt...] /mnt/hdd/disk0:/mnt/hdd/disk1:/mnt/hdd/disk2 /media mergerfs -o opt[,opt...] /branch0:/branch1 /mountpoint
# or list of positional options where the last is the mountpoint # or list of positional options where the last is the mountpoint
mergerfs -o opt[,opt...] /mnt/hdd/disk0 /mnt/hdd/disk1 /mnt/hdd/disk2 /media mergerfs -o opt[,opt...] /branch0 /branch1 /mountpoint
# or set mountpoint via -o mountpoint # or set mountpoint via -o mountpoint
mergerfs -o mountpoint=/media /mnt/hdd/disk0 /mnt/hdd/disk1 /mnt/hdd/disk2 mergerfs -o mountpoint=/mountpoint /branch0 /branch1
``` ```
``` ```
mergerfs -o cache.files=off,category.create=pfrd,func.getattr=newest,dropcacheonclose=false /mnt/hdd/disk0:/mnt/hdd/disk1:/mnt/hdd/disk2 /media mergerfs -o cache.files=off,category.create=pfrd,func.getattr=newest,dropcacheonclose=false /mnt/hdd0:/mnt/hdd1 /media
``` ```
### /etc/fstab ### /etc/fstab
``` ```
/mnt/hdd/disk0:/mnt/hdd/disk1:/mnt/hdd/disk2 /media mergerfs cache.files=off,category.create=pfrd,func.getattr=newest,dropcacheonclose=false 0 0 /mnt/hdd0:/mnt/hdd1 /media mergerfs cache.files=off,category.create=pfrd,func.getattr=newest,dropcacheonclose=false 0 0
``` ```
### systemd mount dependencies
On a `systemd` based system, no custom service or setup script is
needed when the branch filesystems and mergerfs are all configured in
`/etc/fstab`. Add
[`x-systemd.requires-mounts-for=`](https://www.freedesktop.org/software/systemd/man/latest/systemd.mount.html#x-systemd.wants-mounts-for=)
once for each branch mount target in the mergerfs entry:
```fstab
LABEL=disk0 /mnt/hdd/disk0 ext4 defaults 0 2
LABEL=disk1 /mnt/hdd/disk1 ext4 defaults 0 2
LABEL=disk2 /mnt/hdd/disk2 ext4 defaults 0 2
/mnt/hdd/disk0:/mnt/hdd/disk1:/mnt/hdd/disk2 /media mergerfs cache.files=off,category.create=pfrd,func.getattr=newest,dropcacheonclose=false,x-systemd.requires-mounts-for=/mnt/hdd/disk0,x-systemd.requires-mounts-for=/mnt/hdd/disk1,x-systemd.requires-mounts-for=/mnt/hdd/disk2 0 0
```
Replace the example labels and filesystem types with those used by the
system. `systemd` creates `Requires=` and `After=` dependencies from
the mergerfs mount to `mnt-hdd-disk0.mount`,
`mnt-hdd-disk1.mount`, and `mnt-hdd-disk2.mount`. It starts those
mounts first and does not start the mergerfs mount if a required mount
fails. This checks the mount units, not merely whether the
`/mnt/hdd/diskN` directories exist.
After editing `/etc/fstab`, reload the generated units:
```shell
sudo systemctl daemon-reload
```
The dependencies apply the next time `/media` is mounted and on
subsequent boots.
When using a service such as the
[`mergerfs-media.service`](#systemd-simple) example below instead of an
`/etc/fstab` mergerfs entry, add the equivalent directive to its
`[Unit]` section:
```systemd
RequiresMountsFor=/mnt/hdd/disk0 /mnt/hdd/disk1 /mnt/hdd/disk2
```
`RequiresMountsFor=` adds both the requirement and ordering
dependencies, so separate `Requires=` and `After=` entries for these
mounts are unnecessary.
### /etc/fstab w/ config file ### /etc/fstab w/ config file
For more complex setups it can be useful to separate out the config. For more complex setups it can be useful to separate out the config.
@ -170,9 +114,10 @@ resolve the symlinks and use the real path.
`ls -lh /etc/mergerfs/branches/media/*` `ls -lh /etc/mergerfs/branches/media/*`
```text ```text
lrwxrwxrwx 1 root root 14 Aug 4 2023 disk0 -> /mnt/hdd/disk0 lrwxrwxrwx 1 root root 21 Aug 4 2023 hdd00 -> /mnt/hdd/hdd00
lrwxrwxrwx 1 root root 14 Aug 4 2023 disk1 -> /mnt/hdd/disk1 lrwxrwxrwx 1 root root 21 Aug 4 2023 hdd01 -> /mnt/hdd/hdd01
lrwxrwxrwx 1 root root 14 Aug 4 2023 disk2 -> /mnt/hdd/disk2 lrwxrwxrwx 1 root root 21 Aug 4 2023 hdd02 -> /mnt/hdd/hdd02
lrwxrwxrwx 1 root root 21 Aug 4 2023 hdd03 -> /mnt/hdd/hdd03
``` ```
### systemd (simple) ### systemd (simple)
@ -182,7 +127,6 @@ lrwxrwxrwx 1 root root 14 Aug 4 2023 disk2 -> /mnt/hdd/disk2
```systemd title="mergerfs-media.service" linenums="1" ```systemd title="mergerfs-media.service" linenums="1"
[Unit] [Unit]
Description=mergerfs /media service Description=mergerfs /media service
RequiresMountsFor=/mnt/hdd/disk0 /mnt/hdd/disk1 /mnt/hdd/disk2
After=local-fs.target network.target After=local-fs.target network.target
[Service] [Service]
@ -194,9 +138,8 @@ ExecStart=/usr/bin/mergerfs \
-o category.create=pfrd \ -o category.create=pfrd \
-o func.getattr=newest \ -o func.getattr=newest \
-o dropcacheonclose=false \ -o dropcacheonclose=false \
/mnt/hdd/disk0 \ /mnt/hdd0 \
/mnt/hdd/disk1 \ /mnt/hdd1 \
/mnt/hdd/disk2 \
/media /media
ExecStop=/usr/bin/umount /media ExecStop=/usr/bin/umount /media
# Or if you need fusermount # Or if you need fusermount
@ -250,9 +193,8 @@ WantedBy=default.target
```systemd title="mergerfs-media.service" linenums="1" ```systemd title="mergerfs-media.service" linenums="1"
[Unit] [Unit]
Description=mergerfs /media service Description=mergerfs /media service
RequiresMountsFor=/mnt/hdd/disk0 /mnt/hdd/disk1 /mnt/hdd/disk2
Requires=setup-for-mergerfs.service Requires=setup-for-mergerfs.service
After=local-fs.target network.target setup-for-mergerfs.service After=local-fs.target network.target prepare-for-mergerfs.service
[Service] [Service]
Type=simple Type=simple
@ -263,9 +205,8 @@ ExecStart=/usr/bin/mergerfs \
-o category.create=pfrd \ -o category.create=pfrd \
-o func.getattr=newest \ -o func.getattr=newest \
-o dropcacheonclose=false \ -o dropcacheonclose=false \
/mnt/hdd/disk0 \ /mnt/hdd0 \
/mnt/hdd/disk1 \ /mnt/hdd1 \
/mnt/hdd/disk2 \
/media /media
ExecStop=/usr/bin/umount /media ExecStop=/usr/bin/umount /media
# Or if you need fusermount # Or if you need fusermount

View file

@ -23,16 +23,13 @@
## Software and services commonly used with mergerfs ## Software and services commonly used with mergerfs
* [mergerfs-webui](tooling.md#mergerfs-webui): a browser-based tool for
managing mergerfs mounts, runtime settings, and startup configuration
on Linux.
* [snapraid](https://www.snapraid.it): a backup program designed for * [snapraid](https://www.snapraid.it): a backup program designed for
disk arrays, storing parity information for data recovery in the disk arrays, storing parity information for data recovery in the
event of up to six disk failures. event of up to six disk failures.
* [nonraid](https://github.com/qvr/nonraid): NonRAID is a fork of the * [nonraid](https://github.com/qvr/nonraid): NonRAID is a fork of the
Unraid system's open-source md_unraid kernel driver enabling unRAID system's open-source md_unraid kernel driver enabling
Unraid-style storage arrays with parity protection outside of the UnRAID-style storage arrays with parity protection outside of the
commercial Unraid system. commercial UnRAID system.
* [rclone](https://rclone.org): a command-line program to manage * [rclone](https://rclone.org): a command-line program to manage
files on cloud storage. It is a feature-rich alternative to cloud files on cloud storage. It is a feature-rich alternative to cloud
vendors' web storage interfaces. rclone's vendors' web storage interfaces. rclone's
@ -46,10 +43,10 @@
* [Proxmox](https://www.proxmox.com): Proxmox is a popular, Debian * [Proxmox](https://www.proxmox.com): Proxmox is a popular, Debian
based, virtualization platform. Users tend to install mergerfs on based, virtualization platform. Users tend to install mergerfs on
the host and pass the mount into containers. the host and pass the mount into containers.
* [Unraid](https://unraid.net): "Unraid is a powerful, easy-to-use * [UnRAID](https://unraid.net): "Unraid is a powerful, easy-to-use
operating system for self-hosted servers and network-attached operating system for self-hosted servers and network-attached
storage." While Unraid has its own union filesystem it isn't storage." While UnRAID has its own union filesystem it isn't
uncommon to see Unraid users leverage mergerfs given the differences uncommon to see UnRAID users leverage mergerfs given the differences
in the technologies. There is a [plugin available by in the technologies. There is a [plugin available by
Rysz](https://forums.unraid.net/topic/144999-plugin-mergerfs-for-unraid-support-topic) Rysz](https://forums.unraid.net/topic/144999-plugin-mergerfs-for-unraid-support-topic)
to ease installation and setup. to ease installation and setup.

View file

@ -14,11 +14,6 @@ getting and setting config and issuing certain commands. The other are
files found on the filesystem for querying certain `mergerfs` specific files found on the filesystem for querying certain `mergerfs` specific
information about them. information about them.
For a browser-based interface to inspect and change runtime settings,
manage branches and policies, and issue commands, see
[mergerfs-webui](tooling.md#mergerfs-webui). Runtime changes still need
to be saved in startup configuration if they should persist.
## .mergerfs pseudo file ## .mergerfs pseudo file
@ -115,7 +110,7 @@ situation and continue to be able to access the xattr interface.
``` ```
[trapexit:/mnt/mergerfs] $ getfattr -d .mergerfs [trapexit:/mnt/mergerfs] $ getfattr -d .mergerfs
user.mergerfs.branches="/mnt/hdd/disk0=RW:/mnt/hdd/disk1=RW" user.mergerfs.branches="/mnt/a=RW:/mnt/b=RW"
user.mergerfs.minfreespace="4294967295" user.mergerfs.minfreespace="4294967295"
user.mergerfs.moveonenospc="false" user.mergerfs.moveonenospc="false"
... ...
@ -127,9 +122,9 @@ user.mergerfs.category.search="mfs"
[trapexit:/mnt/mergerfs] $ getfattr -n user.mergerfs.category.create .mergerfs [trapexit:/mnt/mergerfs] $ getfattr -n user.mergerfs.category.create .mergerfs
user.mergerfs.category.search="prfd" user.mergerfs.category.search="prfd"
[trapexit:/mnt/mergerfs] $ setfattr -n user.mergerfs.branches -v '+</mnt/hdd/disk2=RO' .mergerfs [trapexit:/mnt/mergerfs] $ setfattr -n user.mergerfs.branches -v '+</mnt/c=RO' .mergerfs
[trapexit:/mnt/mergerfs] $ getfattr -n user.mergerfs.branches .mergerfs [trapexit:/mnt/mergerfs] $ getfattr -n user.mergerfs.branches .mergerfs
user.mergerfs.branches="/mnt/hdd/disk2=RO:/mnt/hdd/disk0=RW:/mnt/hdd/disk1=RW" user.mergerfs.branches="/mnt/c=RO:/mnt/a=RW:/mnt/b=RW"
``` ```
### Commands ### Commands
@ -177,7 +172,7 @@ to set them will result in an error.
``` ```
[trapexit:/mnt/mergerfs] $ getfattr -n user.mergerfs.fullpath test [trapexit:/mnt/mergerfs] $ getfattr -n user.mergerfs.fullpath test
user.mergerfs.fullpath="/mnt/hdd/disk0/test" user.mergerfs.fullpath="/mnt/a/test"
[trapexit:/mnt/mergerfs] $ getfattr -n user.mergerfs.allpaths . [trapexit:/mnt/mergerfs] $ getfattr -n user.mergerfs.allpaths .
user.mergerfs.allpaths="/mnt/hdd/disk0\000/mnt/hdd/disk1\000/mnt/hdd/disk2" user.mergerfs.allpaths="/mnt/a\000/mnt/b\000/mnt/c"
``` ```

View file

@ -23,13 +23,6 @@ $ make deb
$ sudo dpkg -i ../mergerfs_<version>_<arch>.deb $ sudo dpkg -i ../mergerfs_<version>_<arch>.deb
``` ```
Debian package compilation uses the available CPUs by default. To limit
parallelism, set `DEB_BUILD_OPTIONS`:
```
$ DEB_BUILD_OPTIONS=parallel=4 make deb
```
## RHEL / CentOS / Rocky / Fedora ## RHEL / CentOS / Rocky / Fedora
``` ```
@ -40,24 +33,6 @@ $ su -
# rpm -i rpmbuild/RPMS/<arch>/mergerfs-<version>.<arch>.rpm # rpm -i rpmbuild/RPMS/<arch>/mergerfs-<version>.<arch>.rpm
``` ```
Fedora 45 rejects unsigned RPMs by default. When installing a locally
built RPM that you trust, pass `--nosignature` to `rpm` to allow that
unsigned package.
Rocky Linux container builds activate newer GCC Toolsets when available.
Both the Rocky 10 `/usr/lib/gcc-toolset/<version>-env.source` activation
script and the older `/opt/rh/gcc-toolset-<version>/enable` layout are
supported.
## Container packages
Package build targets are defined in `buildtools/containerfiles/`, with
the standard distro targets listed in `buildtools/target-containers.txt`.
Debian release builds target Debian 12 and 13. Other targets include
Fedora 45 on `amd64` and `arm64`, and Ubuntu 26.10 on `amd64`, `arm64`,
`armhf`, and `riscv64`. Foreign-architecture builds require QEMU/binfmt
support.
## Generic Linux ## Generic Linux
Have git, g++ or clang, make, python installed. Have git, g++ or clang, make, python installed.

View file

@ -44,11 +44,11 @@ sudo dpkg -i mergerfs_<ver>.debian-<rel>_<arch>.deb
#### Ubuntu #### Ubuntu
Package build targets include selected Ubuntu LTS and interim releases. Given non-LTS releases are rarely used for servers and only have [9
Check the [release assets](https://github.com/trapexit/mergerfs/releases) months of support](https://ubuntu.com/about/release-cycle) we do not
for your Ubuntu version and architecture. If no matching package is build packages for them by default. It is recommended that you first
available, try the `deb` file for the LTS release most closely related try the `deb` file for the LTS release most closely related to your
to your non-LTS release. If that does not work you can use the [static non-LTS release. If that does not work you can use the [static
build](#static-linux-binaries) or [file a build](#static-linux-binaries) or [file a
ticket](https://github.com/trapexit/mergerfs/issues) requesting a ticket](https://github.com/trapexit/mergerfs/issues) requesting a
package built. package built.
@ -135,33 +135,11 @@ docker pull ghcr.io/trapexit/mergerfs:TAG
docker run --device=/dev/fuse --cap-add=SYS_ADMIN -v /mnt/to-merge:/mnt/to-merge:rshared -v /mnt/mergerfs:/mnt/mergerfs:z,shared ghcr.io/trapexit/mergerfs:TAG -f '/mnt/to-merge/*' '/mnt/mergerfs' docker run --device=/dev/fuse --cap-add=SYS_ADMIN -v /mnt/to-merge:/mnt/to-merge:rshared -v /mnt/mergerfs:/mnt/mergerfs:z,shared ghcr.io/trapexit/mergerfs:TAG -f '/mnt/to-merge/*' '/mnt/mergerfs'
``` ```
or with docker compose
```
services:
mergerfs:
image: ghcr.io/trapexit/mergerfs:TAG
container_name: mergerfs
restart: unless-stopped
privileged: true
cap_add:
- SYS_ADMIN
devices:
- /dev/fuse:/dev/fuse
command: -f '/mnt/to-merge/*' '/mnt/mergerfs'
volumes:
- /mnt/to-merge:/mnt/to-merge:rshared
- /mnt/mergerfs:/mnt/mergerfs:z,shared
```
* `--device=/dev/fuse`: Pass in host FUSE device. * `--device=/dev/fuse`: Pass in host FUSE device.
* `--cap-add=SYS_ADMIN`: Give proper permissions to mount. * `--cap-add=SYS_ADMIN`: Give proper permissions to mount.
* `-v /mnt/mergerfs:/mnt/mergerfs:z,shared`: `z` and `shared` will * `-v /mnt/mergerfs:/mnt/mergerfs:z,shared`: `z` and `shared` will
allow the mount to be shared between the container and host and allow the mount to be shared between the container and host and
therefore other containers. Note that once mergerfs is mounted therefore other containers.
inside the container the resulting FUSE filesystem does not
support SELinux relabeling. See [Does mergerfs work with SELinux
relabeling?](../faq/compatibility_and_integration.md#does-mergerfs-work-with-selinux-relabeling)
* `-v /mnt/to-merge:/mnt/to-merge:rshared`: The mounts from the host * `-v /mnt/to-merge:/mnt/to-merge:rshared`: The mounts from the host
to merge within the container. to merge within the container.

View file

@ -14,8 +14,7 @@
* If you do not see some directories and files you expect, policies * If you do not see some directories and files you expect, policies
seem to skip branches, you get strange permission errors, etc. be seem to skip branches, you get strange permission errors, etc. be
sure the underlying filesystems' permissions are all the same. Use sure the underlying filesystems' permissions are all the same. Use
[fsck.mergerfs](tooling.md#fsckmergerfs) to audit the filesystem for `mergerfs.fsck` to audit the filesystem for out of sync permissions.
out of sync permissions.
* If you still have permission issues be sure you are using POSIX * If you still have permission issues be sure you are using POSIX
compliant filesystems. mergerfs doesn't generally make exceptions compliant filesystems. mergerfs doesn't generally make exceptions
for FAT, NTFS, or other non-POSIX filesystem. for FAT, NTFS, or other non-POSIX filesystem.

View file

@ -1,28 +1,5 @@
# Tooling # Tooling
## mergerfs-webui
[mergerfs-webui](https://github.com/trapexit/mergerfs-webui) is a
browser-based tool for viewing and managing mergerfs mounts on Linux.
It is a separate project with a single executable containing both the
web server and the web page.
It can:
* Install mergerfs and create mounts through `/etc/fstab` or systemd
`.mount` units.
* Discover running mounts, mount and unmount them, and inspect and
change their runtime settings, branches, and policies.
* Edit startup configuration in `/etc/fstab`, systemd `.mount` units,
and referenced mergerfs ini files, with previews of structured
changes before saving.
* Issue runtime commands and set up the web UI as a systemd service.
[Runtime changes](runtime_interface.md) are not automatically
persistent; startup configuration must also be updated if changes
should survive a remount.
## mergerfs.collect-info ## mergerfs.collect-info
A tool included in recent releases of `mergerfs` which collects A tool included in recent releases of `mergerfs` which collects
@ -128,8 +105,7 @@ to `.bashrc`.
### Docker and Podman usage ### Docker and Podman usage
Assume `/mnt/hdd/disk0` and `/mnt/hdd/disk1` are pooled with mergerfs Assume `/mnt/fs0` and `/mnt/fs1` are pooled with mergerfs at `/media`.
at `/media`.
All mergerfs branch paths _must_ be bind mounted into the container at All mergerfs branch paths _must_ be bind mounted into the container at
the same path as found on the host so the preload library can see the same path as found on the host so the preload library can see
@ -158,8 +134,8 @@ docker run \
-e LD_PRELOAD=/usr/lib/mergerfs/preload.so \ -e LD_PRELOAD=/usr/lib/mergerfs/preload.so \
-v /usr/lib/mergerfs/preload.so:/usr/lib/mergerfs/preload.so:ro \ -v /usr/lib/mergerfs/preload.so:/usr/lib/mergerfs/preload.so:ro \
-v /media:/media \ -v /media:/media \
-v /mnt/hdd/disk0:/mnt/hdd/disk0 \ -v /mnt/fs0:/mnt/fs0 \
-v /mnt/hdd/disk1:/mnt/hdd/disk1 \ -v /mnt/fs1:/mnt/fs1 \
ubuntu:latest \ ubuntu:latest \
bash bash
``` ```
@ -184,6 +160,8 @@ Environment=LD_PRELOAD=/usr/lib/mergerfs/preload.so
behaviors that can be build on top of mergerfs. They may not behaviors that can be build on top of mergerfs. They may not
have all the features you are looking for.** have all the features you are looking for.**
* mergerfs.ctl: A tool to make it easier to query and configure mergerfs at runtime * mergerfs.ctl: A tool to make it easier to query and configure mergerfs at runtime
* mergerfs.fsck: Provides permissions and ownership auditing and
the ability to fix them (should use `fsck.mergerfs` instead)
* mergerfs.dedup: Will help identify and optionally remove duplicate files * mergerfs.dedup: Will help identify and optionally remove duplicate files
* mergerfs.dup: Ensure there are at least N copies of a file across the pool * mergerfs.dup: Ensure there are at least N copies of a file across the pool
* mergerfs.balance: Rebalance files across filesystems by moving them from the most filled to the least filled * mergerfs.balance: Rebalance files across filesystems by moving them from the most filled to the least filled

View file

@ -103,7 +103,6 @@ nav:
- Tips and Notes: tips_notes.md - Tips and Notes: tips_notes.md
- Known Issues and Bugs: known_issues_bugs.md - Known Issues and Bugs: known_issues_bugs.md
- Project Comparisons: project_comparisons.md - Project Comparisons: project_comparisons.md
- Migration: migration.md
- Benchmarking: benchmarking.md - Benchmarking: benchmarking.md
- Performance: performance.md - Performance: performance.md
- Tooling: tooling.md - Tooling: tooling.md
@ -116,7 +115,6 @@ nav:
- faq/compatibility_and_integration.md - faq/compatibility_and_integration.md
- faq/technical_behavior_and_limitations.md - faq/technical_behavior_and_limitations.md
- faq/have_you_considered.md - faq/have_you_considered.md
- faq/downsides.md
- faq/limit_drive_spinup.md - faq/limit_drive_spinup.md
- Related Projects: related_projects.md - Related Projects: related_projects.md
- Media and Publicity: media_and_publicity.md - Media and Publicity: media_and_publicity.md

View file

@ -28,10 +28,8 @@
#include "str.hpp" #include "str.hpp"
#include "syslog.hpp" #include "syslog.hpp"
#include <mutex>
#include <optional>
#include <shared_mutex>
#include <string> #include <string>
#include <optional>
#include <fnmatch.h> #include <fnmatch.h>
@ -439,44 +437,24 @@ Branches::from_string(const std::string_view str_)
Branches::Ptr impl; Branches::Ptr impl;
Branches::Ptr new_impl; Branches::Ptr new_impl;
impl = std::atomic_load(&_impl);
new_impl = std::make_shared<Branches::Impl>(&minfreespace); new_impl = std::make_shared<Branches::Impl>(&minfreespace);
for(;;)
{
{
std::shared_lock<std::shared_mutex> lk(_mutex);
impl = _impl;
}
*new_impl = *impl; *new_impl = *impl;
rv = new_impl->from_string(str_); rv = new_impl->from_string(str_);
if(rv < 0) if(rv < 0)
return rv; return rv;
{ std::atomic_store(&_impl,new_impl);
std::unique_lock<std::shared_mutex> lk(_mutex);
if(impl != _impl)
continue;
_impl = std::move(new_impl);
}
return 0; return 0;
} }
}
std::string std::string
Branches::to_string(void) const Branches::to_string(void) const
{ {
Branches::Ptr impl; return std::atomic_load(&_impl)->to_string();
{
std::shared_lock<std::shared_mutex> lk(_mutex);
impl = _impl;
}
return impl->to_string();
} }
void void
@ -484,21 +462,13 @@ Branches::find_and_set_mode_ro()
{ {
Branches::Ptr impl; Branches::Ptr impl;
Branches::Ptr new_impl; Branches::Ptr new_impl;
std::vector<fs::path> ro_paths;
impl = std::atomic_load(&_impl);
new_impl = std::make_shared<Branches::Impl>(&minfreespace); new_impl = std::make_shared<Branches::Impl>(&minfreespace);
for(;;)
{
ro_paths.clear();
{
std::shared_lock<std::shared_mutex> lk(_mutex);
impl = _impl;
}
*new_impl = *impl; *new_impl = *impl;
bool changed = false;
for(auto &branch : *new_impl) for(auto &branch : *new_impl)
{ {
if(branch.mode != Branch::Mode::RW) if(branch.mode != Branch::Mode::RW)
@ -507,27 +477,17 @@ Branches::find_and_set_mode_ro()
if(!fs::is_rofs_but_not_mounted_ro(branch.path)) if(!fs::is_rofs_but_not_mounted_ro(branch.path))
continue; continue;
branch.mode = Branch::Mode::RO;
ro_paths.emplace_back(branch.path);
}
if(ro_paths.empty())
return;
{
std::unique_lock<std::shared_mutex> lk(_mutex);
if(impl != _impl)
continue;
_impl = std::move(new_impl);
}
for(const auto &path : ro_paths)
SysLog::warning("branch `{}` found to be readonly - setting its mode=RO", SysLog::warning("branch `{}` found to be readonly - setting its mode=RO",
path.string()); branch.path.string());
return; branch.mode = Branch::Mode::RO;
changed = true;
} }
if(not changed)
return;
std::atomic_store(&_impl,new_impl);
} }
SrcMounts::SrcMounts(Branches &b_) SrcMounts::SrcMounts(Branches &b_)

View file

@ -23,9 +23,9 @@
#include "strvec.hpp" #include "strvec.hpp"
#include "tofrom_string.hpp" #include "tofrom_string.hpp"
#include <atomic>
#include <cstdint> #include <cstdint>
#include <memory> #include <memory>
#include <shared_mutex>
#include <string> #include <string>
#include <vector> #include <vector>
@ -69,8 +69,7 @@ public:
u64 minfreespace = MINFREESPACE_DEFAULT; u64 minfreespace = MINFREESPACE_DEFAULT;
private: private:
Branches::Ptr _impl; mutable std::shared_ptr<Impl> _impl;
mutable std::shared_mutex _mutex;
public: public:
Branches() Branches()
@ -83,17 +82,8 @@ public:
std::string to_string(void) const final; std::string to_string(void) const final;
public: public:
operator Ptr() const operator Ptr() const { return std::atomic_load(&_impl); }
{ Ptr operator->() const { return std::atomic_load(&_impl); }
std::shared_lock<std::shared_mutex> lk(_mutex);
return _impl;
}
Ptr operator->() const
{
std::shared_lock<std::shared_mutex> lk(_mutex);
return _impl;
}
public: public:
void find_and_set_mode_ro(); void find_and_set_mode_ro();

View file

@ -48,9 +48,9 @@
#include "fh.hpp" #include "fh.hpp"
#include "fs_path.hpp" #include "fs_path.hpp"
#include "base_types.h" #include "mutex.hpp"
#include <shared_mutex> #include "base_types.h"
class FileInfo : public FH class FileInfo : public FH
@ -97,16 +97,7 @@ public:
int fd; int fd;
Branch branch; Branch branch;
u32 direct_io:1; u32 direct_io:1;
// Serializes the fd state across concurrent writes on the same open Mutex mutex;
// file. Concurrent writes happen with:
// 1) writeback-cache + page-cache mode
// 2) parallel_direct_writes + direct_io=true
//
// 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.
std::shared_mutex mutex;
}; };
inline inline

View file

@ -21,7 +21,6 @@
#include "errno.h" #include "errno.h"
#include "fs_attr.hpp" #include "fs_attr.hpp"
#include "fs_clonepath.hpp" #include "fs_clonepath.hpp"
#include "fs_lchmod.hpp"
#include "fs_lchown.hpp" #include "fs_lchown.hpp"
#include "fs_lstat.hpp" #include "fs_lstat.hpp"
#include "fs_lutimens.hpp" #include "fs_lutimens.hpp"
@ -112,13 +111,6 @@ fs::clonepath(const fs::path &srcpath_,
if(return_metadata_errors_ && (rv < 0)) if(return_metadata_errors_ && (rv < 0))
return rv; return rv;
// mkdir(2) on Linux ignores S_ISUID/S_ISGID in mode and may
// inherent S_ISGID from the parent. Explicitly set the mode after
// chown so the clone matches the source.
rv = fs::lchmod_check_on_error(dstpath,st.st_mode);
if(return_metadata_errors_ && (rv < 0))
return rv;
rv = fs::lutimens(dstpath,st); rv = fs::lutimens(dstpath,st);
if(return_metadata_errors_ && (rv < 0)) if(return_metadata_errors_ && (rv < 0))
return rv; return rv;

View file

@ -18,7 +18,6 @@
#include "to_neg_errno.hpp" #include "to_neg_errno.hpp"
#include <algorithm>
#include <sys/types.h> #include <sys/types.h>
#if defined __linux__ #if defined __linux__
@ -37,10 +36,7 @@ namespace fs
#if defined SYS_getdents64 #if defined SYS_getdents64
ssize_t rv; ssize_t rv;
// Avoid oversized requests on virtiofs-backed branches. rv = ::syscall(SYS_getdents64,fd_,dirp_,count_);
const size_t count = std::min<size_t>(count_,128 * 1024);
rv = ::syscall(SYS_getdents64,fd_,dirp_,count);
return ::to_neg_errno(rv); return ::to_neg_errno(rv);
#else #else

View file

@ -21,8 +21,8 @@
#include "fs_statvfs.hpp" #include "fs_statvfs.hpp"
#include "statvfs_util.hpp" #include "statvfs_util.hpp"
#include <mutex> #include "mutex.hpp"
#include <shared_mutex>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
@ -38,11 +38,9 @@ struct Element
typedef std::unordered_map<std::string,Element> statvfs_cache; typedef std::unordered_map<std::string,Element> statvfs_cache;
// Cache is read heavy. Use a shared mutex so concurrent reads can
// work in parallel and only inserts or refreshes take a unique lock.
static std::shared_mutex g_cache_mutex;
static u64 g_timeout = 0; static u64 g_timeout = 0;
static statvfs_cache g_cache; static statvfs_cache g_cache;
static Mutex g_cache_lock;
static static
@ -72,35 +70,29 @@ int
fs::statvfs_cache(const std::string &path_, fs::statvfs_cache(const std::string &path_,
struct statvfs *st_) struct statvfs *st_)
{ {
int rv;
Element *e;
u64 now; u64 now;
if(g_timeout == 0) if(g_timeout == 0)
return fs::statvfs(path_,st_); return fs::statvfs(path_,st_);
rv = 0;
now = ::_get_time(); now = ::_get_time();
{ mutex_lock(g_cache_lock);
std::shared_lock<std::shared_mutex> lk(g_cache_mutex);
auto it = g_cache.find(path_); e = &g_cache[path_];
if((it != g_cache.end()) && ((now - it->second.time) <= g_timeout))
if((now - e->time) > g_timeout)
{ {
*st_ = it->second.st; e->time = now;
return 0; rv = fs::statvfs(path_,&e->st);
}
} }
int rv = 0; *st_ = e->st;
std::unique_lock<std::shared_mutex> lk(g_cache_mutex);
Element &e = g_cache[path_]; mutex_unlock(g_cache_lock);
if((now - e.time) > g_timeout)
{
e.time = now;
rv = fs::statvfs(path_,&e.st);
}
*st_ = e.st;
return rv; return rv;
} }

View file

@ -334,7 +334,7 @@ _create(const fuse_req_ctx_t *ctx_,
delete fi; delete fi;
ffi_->fh = 0; ffi_->fh = 0;
SysLog::crit("{}",msg); SysLog::crit(msg);
fmt::println(stderr,"{}",msg); fmt::println(stderr,"{}",msg);
return -EIO; return -EIO;

View file

@ -45,9 +45,6 @@ _fchmod(const int fd_,
// since the request is outstanding the kernel won't be releasing the // since the request is outstanding the kernel won't be releasing the
// node and therefore the entry will be valid over the lifetime of // node and therefore the entry will be valid over the lifetime of
// this function. // this function.
//
// With neither a `fh` nor an open file return ENOENT. See fgetattr in
// fuse.h and #1693.
int int
FUSE::fchmod(const fuse_req_ctx_t *ctx_, FUSE::fchmod(const fuse_req_ctx_t *ctx_,
cu64 fh_, cu64 fh_,
@ -57,7 +54,7 @@ FUSE::fchmod(const fuse_req_ctx_t *ctx_,
fi = state.get_fi(ctx_,fh_); fi = state.get_fi(ctx_,fh_);
if(not fi) if(not fi)
return -ENOENT; return -EBADF;
return ::_fchmod(fi->fd,mode_); return ::_fchmod(fi->fd,mode_);
} }

View file

@ -48,9 +48,6 @@ _fchown(const int fd_,
// since the request is outstanding the kernel won't be releasing the // since the request is outstanding the kernel won't be releasing the
// node and therefore the entry will be valid over the lifetime of // node and therefore the entry will be valid over the lifetime of
// this function. // this function.
//
// With neither a `fh` nor an open file return ENOENT. See fgetattr in
// fuse.h and #1693.
int int
FUSE::fchown(const fuse_req_ctx_t *ctx_, FUSE::fchown(const fuse_req_ctx_t *ctx_,
cu64 fh_, cu64 fh_,
@ -61,7 +58,7 @@ FUSE::fchown(const fuse_req_ctx_t *ctx_,
fi = state.get_fi(ctx_,fh_); fi = state.get_fi(ctx_,fh_);
if(not fi) if(not fi)
return -ENOENT; return -EBADF;
return ::_fchown(fi->fd,uid_,gid_); return ::_fchown(fi->fd,uid_,gid_);
} }

View file

@ -53,9 +53,6 @@ _fgetattr(const FileInfo *fi_,
// since the request is outstanding the kernel won't be releasing the // since the request is outstanding the kernel won't be releasing the
// node and therefore the entry will be valid over the lifetime of // node and therefore the entry will be valid over the lifetime of
// this function. // this function.
//
// With neither a `fh` nor an open file return ENOENT. See fgetattr in
// fuse.h and #1693.
int int
FUSE::fgetattr(const fuse_req_ctx_t *ctx_, FUSE::fgetattr(const fuse_req_ctx_t *ctx_,
cu64 fh_, cu64 fh_,
@ -67,7 +64,7 @@ FUSE::fgetattr(const fuse_req_ctx_t *ctx_,
fi = state.get_fi(ctx_,fh_); fi = state.get_fi(ctx_,fh_);
if(not fi) if(not fi)
return -ENOENT; return -EBADF;
rv = ::_fgetattr(fi,st_); rv = ::_fgetattr(fi,st_);

View file

@ -45,9 +45,6 @@ _ftruncate(const int fd_,
// since the request is outstanding the kernel won't be releasing the // since the request is outstanding the kernel won't be releasing the
// node and therefore the entry will be valid over the lifetime of // node and therefore the entry will be valid over the lifetime of
// this function. // this function.
//
// With neither a `fh` nor an open file return ENOENT. See fgetattr in
// fuse.h and #1693.
int int
FUSE::ftruncate(const fuse_req_ctx_t *ctx_, FUSE::ftruncate(const fuse_req_ctx_t *ctx_,
cu64 fh_, cu64 fh_,
@ -57,7 +54,7 @@ FUSE::ftruncate(const fuse_req_ctx_t *ctx_,
fi = state.get_fi(ctx_,fh_); fi = state.get_fi(ctx_,fh_);
if(not fi) if(not fi)
return -ENOENT; return -EBADF;
return ::_ftruncate(fi->fd,size_); return ::_ftruncate(fi->fd,size_);
} }

View file

@ -47,9 +47,6 @@ _futimens(const int fd_,
// since the request is outstanding the kernel won't be releasing the // since the request is outstanding the kernel won't be releasing the
// node and therefore the entry will be valid over the lifetime of // node and therefore the entry will be valid over the lifetime of
// this function. // this function.
//
// With neither a `fh` nor an open file return ENOENT. See fgetattr in
// fuse.h and #1693.
int int
FUSE::futimens(const fuse_req_ctx_t *ctx_, FUSE::futimens(const fuse_req_ctx_t *ctx_,
cu64 fh_, cu64 fh_,
@ -59,7 +56,7 @@ FUSE::futimens(const fuse_req_ctx_t *ctx_,
fi = state.get_fi(ctx_,fh_); fi = state.get_fi(ctx_,fh_);
if(not fi) if(not fi)
return -ENOENT; return -EBADF;
return ::_futimens(fi->fd,ts_); return ::_futimens(fi->fd,ts_);
} }

View file

@ -194,7 +194,8 @@ _link(const fs::path &oldpath_,
static static
int int
_link(const fs::path &oldpath_, _link(const fuse_req_ctx_t *ctx_,
const fs::path &oldpath_,
const fs::path &newpath_, const fs::path &newpath_,
struct stat *st_, struct stat *st_,
fuse_timeouts_t *timeouts_) fuse_timeouts_t *timeouts_)
@ -210,7 +211,7 @@ _link(const fs::path &oldpath_,
static static
int int
_link_exdev_rel_symlink(const ugid_t owner_, _link_exdev_rel_symlink(const fuse_req_ctx_t *ctx_,
const fs::path &oldpath_, const fs::path &oldpath_,
const fs::path &newpath_, const fs::path &newpath_,
struct stat *st_, struct stat *st_,
@ -222,9 +223,9 @@ _link_exdev_rel_symlink(const ugid_t owner_,
target = target.lexically_relative(linkpath.parent_path()); target = target.lexically_relative(linkpath.parent_path());
rv = FUSE::symlink_owned(owner_,target.c_str(),linkpath); rv = FUSE::symlink(ctx_,target.c_str(),linkpath);
if(rv == 0) if(rv == 0)
rv = FUSE::getattr(oldpath_,st_,timeouts_); rv = FUSE::getattr(ctx_,oldpath_,st_,timeouts_);
// Disable caching since we created a symlink but should be a regular. // Disable caching since we created a symlink but should be a regular.
timeouts_->attr = 0; timeouts_->attr = 0;
@ -235,30 +236,9 @@ _link_exdev_rel_symlink(const ugid_t owner_,
static static
int int
_link_exdev_abs_base_symlink(const ugid_t owner_, _link_exdev_abs_base_symlink(const fuse_req_ctx_t *ctx_,
const fs::path &target_, const Policy::Search &openPolicy_,
const fs::path &oldpath_, const Branches::Ptr ibranches_,
const fs::path &newpath_,
struct stat *st_,
fuse_timeouts_t *timeouts_)
{
int rv;
rv = FUSE::symlink_owned(owner_,target_.c_str(),newpath_);
if(rv == 0)
rv = FUSE::getattr(oldpath_,st_,timeouts_);
// Disable caching since we created a symlink but should be a regular.
timeouts_->attr = 0;
timeouts_->entry = 0;
return rv;
}
static
int
_link_exdev_abs_pool_symlink(const ugid_t owner_,
const fs::path &mount_,
const fs::path &oldpath_, const fs::path &oldpath_,
const fs::path &newpath_, const fs::path &newpath_,
struct stat *st_, struct stat *st_,
@ -266,12 +246,19 @@ _link_exdev_abs_pool_symlink(const ugid_t owner_,
{ {
int rv; int rv;
fs::path target; fs::path target;
std::vector<Branch*> obranches;
target = mount_ / oldpath_; rv = openPolicy_(ibranches_,oldpath_,obranches);
if(rv < 0)
return rv;
if(obranches.empty())
return -ENOENT;
rv = FUSE::symlink_owned(owner_,target.c_str(),newpath_); target = obranches[0]->path / oldpath_;
rv = FUSE::symlink(ctx_,target.c_str(),newpath_);
if(rv == 0) if(rv == 0)
rv = FUSE::getattr(oldpath_,st_,timeouts_); rv = FUSE::getattr(ctx_,oldpath_,st_,timeouts_);
// Disable caching since we created a symlink but should be a regular. // Disable caching since we created a symlink but should be a regular.
timeouts_->attr = 0; timeouts_->attr = 0;
@ -282,63 +269,58 @@ _link_exdev_abs_pool_symlink(const ugid_t owner_,
static static
int int
_link_exdev(const fs::path &oldpath_, _link_exdev_abs_pool_symlink(const fuse_req_ctx_t *ctx_,
const fs::path &mount_,
const fs::path &oldpath_,
const fs::path &newpath_, const fs::path &newpath_,
struct stat *st_, struct stat *st_,
fuse_timeouts_t *timeouts_) fuse_timeouts_t *timeouts_)
{ {
int rv; int rv;
struct stat source; StrVec basepaths;
fs::path oldfullpath; fs::path target;
std::vector<Branch*> oldbranches;
const Policy::Search *sourcePolicy;
switch(cfg.link_exdev) target = mount_ / oldpath_;
{
case LinkEXDEV::ENUM::REL_SYMLINK: rv = FUSE::symlink(ctx_,target.c_str(),newpath_);
case LinkEXDEV::ENUM::ABS_POOL_SYMLINK: if(rv == 0)
sourcePolicy = &cfg.func.getattr.policy; rv = FUSE::getattr(ctx_,oldpath_,st_,timeouts_);
break;
case LinkEXDEV::ENUM::ABS_BASE_SYMLINK: // Disable caching since we created a symlink but should be a regular.
sourcePolicy = &cfg.func.open.policy; timeouts_->attr = 0;
break; timeouts_->entry = 0;
default:
return -EXDEV; return rv;
} }
const Branches::Ptr branches = cfg.branches; static
rv = (*sourcePolicy)(branches,oldpath_,oldbranches); int
if(rv < 0) _link_exdev(const fuse_req_ctx_t *ctx_,
return rv; const fs::path &oldpath_,
if(oldbranches.empty()) const fs::path &newpath_,
return -ENOENT; struct stat *st_,
fuse_timeouts_t *timeouts_)
oldfullpath = oldbranches[0]->path / oldpath_; {
rv = fs::lstat(oldfullpath,&source);
if(rv < 0)
return rv;
const ugid_t owner{source.st_uid,source.st_gid};
switch(cfg.link_exdev) switch(cfg.link_exdev)
{ {
case LinkEXDEV::ENUM::PASSTHROUGH: case LinkEXDEV::ENUM::PASSTHROUGH:
return -EXDEV; return -EXDEV;
case LinkEXDEV::ENUM::REL_SYMLINK: case LinkEXDEV::ENUM::REL_SYMLINK:
return ::_link_exdev_rel_symlink(owner, return ::_link_exdev_rel_symlink(ctx_,
oldpath_, oldpath_,
newpath_, newpath_,
st_, st_,
timeouts_); timeouts_);
case LinkEXDEV::ENUM::ABS_BASE_SYMLINK: case LinkEXDEV::ENUM::ABS_BASE_SYMLINK:
return ::_link_exdev_abs_base_symlink(owner, return ::_link_exdev_abs_base_symlink(ctx_,
oldfullpath, cfg.func.open.policy,
cfg.branches,
oldpath_, oldpath_,
newpath_, newpath_,
st_, st_,
timeouts_); timeouts_);
case LinkEXDEV::ENUM::ABS_POOL_SYMLINK: case LinkEXDEV::ENUM::ABS_POOL_SYMLINK:
return ::_link_exdev_abs_pool_symlink(owner, return ::_link_exdev_abs_pool_symlink(ctx_,
cfg.mountpoint, cfg.mountpoint,
oldpath_, oldpath_,
newpath_, newpath_,
@ -360,9 +342,9 @@ FUSE::link(const fuse_req_ctx_t *ctx_,
const fs::path oldpath{oldpath_}; const fs::path oldpath{oldpath_};
const fs::path newpath{newpath_}; const fs::path newpath{newpath_};
rv = ::_link(oldpath,newpath,st_,timeouts_); rv = ::_link(ctx_,oldpath,newpath,st_,timeouts_);
if(rv == -EXDEV) if(rv == -EXDEV)
rv = ::_link_exdev(oldpath,newpath,st_,timeouts_); rv = ::_link_exdev(ctx_,oldpath,newpath,st_,timeouts_);
return rv; return rv;
} }

View file

@ -367,19 +367,10 @@ _open(const fuse_req_ctx_t *ctx_,
// The ref increment keeps fuse_release.cpp from erasing and // The ref increment keeps fuse_release.cpp from erasing and
// freeing the canonical entry while we duplicate its fd. // freeing the canonical entry while we duplicate its fd.
//
// memory_order_relaxed is sufficient for the increment. The
// concurrent_flat_map bucket lock held inside visit() already
// provides the happens-before relationship with other mutators
// of the same key (the release() erase_if() callback and other
// open() visitors.) The lock's release/acquire semantics
// publish the ref_count update to subsequent observers of the
// same entry, so we only need atomicity from the fetch_add
// itself.
of.visit(ctx_->nodeid, of.visit(ctx_->nodeid,
[&](auto &v_) [&](auto &v_)
{ {
v_.second.ref_count.fetch_add(1,std::memory_order_relaxed); v_.second.ref_count++;
fi = v_.second.fi; fi = v_.second.fi;
backing_id = v_.second.backing_id; backing_id = v_.second.backing_id;
}); });

View file

@ -48,29 +48,30 @@ FUSE::ReadDir::ReadDir(const std::string_view s_)
std::string std::string
FUSE::ReadDir::to_string() const FUSE::ReadDir::to_string() const
{ {
std::shared_lock<std::shared_mutex> lk(_mutex); std::shared_ptr<std::string> str;
return _str; str = std::atomic_load(&_str);
return (*str);
} }
int int
FUSE::ReadDir::from_string(const std::string_view str_) FUSE::ReadDir::from_string(const std::string_view str_)
{ {
std::shared_ptr<std::string> tmp_str;
std::shared_ptr<FUSE::ReadDirBase> tmp_readdir; std::shared_ptr<FUSE::ReadDirBase> tmp_readdir;
tmp_readdir = FUSE::ReadDirFactory::make(str_); tmp_readdir = FUSE::ReadDirFactory::make(str_);
if(!tmp_readdir) if(!tmp_readdir)
return -EINVAL; return -EINVAL;
{ tmp_str = std::make_shared<std::string>(str_);
std::unique_lock<std::shared_mutex> lk(_mutex); std::atomic_store(&_str,tmp_str);
_str = str_;
if(_initialized == false) if(_initialized == false)
return 0; return 0;
_impl = std::move(tmp_readdir); std::atomic_store(&_impl,tmp_readdir);
}
return 0; return 0;
} }
@ -113,10 +114,7 @@ FUSE::ReadDir::operator()(const fuse_req_ctx_t *ctx_,
int rv; int rv;
std::shared_ptr<FUSE::ReadDirBase> readdir; std::shared_ptr<FUSE::ReadDirBase> readdir;
{ readdir = std::atomic_load(&_impl);
std::shared_lock<std::shared_mutex> lk(_mutex);
readdir = _impl;
}
if(!readdir) if(!readdir)
fatal::abort("readdir impl is null"); fatal::abort("readdir impl is null");
@ -130,14 +128,10 @@ FUSE::ReadDir::operator()(const fuse_req_ctx_t *ctx_,
void void
FUSE::ReadDir::initialize() FUSE::ReadDir::initialize()
{ {
std::string str; std::shared_ptr<std::string> str;
{ str = std::atomic_load(&_str);
std::unique_lock<std::shared_mutex> lk(_mutex);
str = _str;
_initialized = true; _initialized = true;
}
from_string(str); from_string(*str);
} }

View file

@ -22,9 +22,9 @@
#include "tofrom_string.hpp" #include "tofrom_string.hpp"
#include "fuse_readdir_base.hpp" #include "fuse_readdir_base.hpp"
#include <atomic>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <shared_mutex>
namespace FUSE namespace FUSE
@ -59,9 +59,8 @@ namespace FUSE
void initialize(); void initialize();
private: private:
bool _initialized = false; std::atomic<bool> _initialized = false;
mutable std::shared_mutex _mutex; std::shared_ptr<std::string> _str;
std::string _str;
std::shared_ptr<FUSE::ReadDirBase> _impl; std::shared_ptr<FUSE::ReadDirBase> _impl;
}; };
} }

View file

@ -43,12 +43,6 @@ FUSE::ReadDirCOR::~ReadDirCOR()
#include "fuse_readdir_cor_readdir.icpp" #include "fuse_readdir_cor_readdir.icpp"
#endif #endif
// Uses a per-call mutex. Lifetime is one readdir operation. It
// serializes the dirent-merge step (dedup'ing of names + append to
// dirents list) across at-most-branches-worth of parallel worker
// tasks. Per-branch opendir + getdents64 run fully outside the
// critical section, so the lock holds only long enough to merge each
// batch.
static static
inline inline
int int

View file

@ -81,21 +81,11 @@ FUSE::release(cu64 nodeid_,
FileInfo *canonical_fi = nullptr; FileInfo *canonical_fi = nullptr;
FileInfo *fh_fi_to_free = nullptr; FileInfo *fh_fi_to_free = nullptr;
// memory_order_acq_rel on the decrement gives us the canonical
// refcount-publication pattern:
// - release: prior writes to the OpenFile by this thread are
// visible to whichever thread observes the final 0.
// - acquire: the thread that drops the last ref acquires every
// prior ref holder's writes before tearing down the entry.
// The concurrent_flat_map bucket lock already serializes concurrent
// visitors of this key so the acq_rel is good for any observer that
// might examine ref_count outside a visit().
of.erase_if(nodeid_, of.erase_if(nodeid_,
[&](auto &v_) [&](auto &v_)
{ {
const int prev = v_.second.ref_count--;
v_.second.ref_count.fetch_sub(1,std::memory_order_acq_rel); if(v_.second.ref_count > 0)
if(prev > 1)
{ {
if(fi_ != v_.second.fi) if(fi_ != v_.second.fi)
fh_fi_to_free = fi_; fh_fi_to_free = fi_;

View file

@ -23,7 +23,6 @@
#include "errno.hpp" #include "errno.hpp"
#include "fs_clonepath.hpp" #include "fs_clonepath.hpp"
#include "fs_link.hpp" #include "fs_link.hpp"
#include "fs_lstat.hpp"
#include "fs_mkdir_as.hpp" #include "fs_mkdir_as.hpp"
#include "fs_path.hpp" #include "fs_path.hpp"
#include "fs_remove.hpp" #include "fs_remove.hpp"
@ -205,20 +204,13 @@ int
_rename_exdev_rename_target(const Policy::Action &actionPolicy_, _rename_exdev_rename_target(const Policy::Action &actionPolicy_,
const Branches::Ptr ibranches_, const Branches::Ptr ibranches_,
const fs::path &oldfusepath_, const fs::path &oldfusepath_,
std::vector<Branch*> &obranches_, std::vector<Branch*> &obranches_)
struct stat &source_)
{ {
int rv; int rv;
fs::path clonesrc; fs::path clonesrc;
fs::path clonedst; fs::path clonedst;
rv = actionPolicy_(ibranches_,oldfusepath_,obranches_); rv = actionPolicy_(ibranches_,oldfusepath_,obranches_);
if(rv < 0)
return rv;
if(obranches_.empty())
return -ENOENT;
rv = fs::lstat(obranches_[0]->path / oldfusepath_,&source_);
if(rv < 0) if(rv < 0)
return rv; return rv;
@ -228,11 +220,12 @@ _rename_exdev_rename_target(const Policy::Action &actionPolicy_,
clonedst = branch->path; clonedst = branch->path;
clonedst /= ".mergerfs_rename_exdev"; clonedst /= ".mergerfs_rename_exdev";
rv = fs::mkdir_as({0,0},clonedst,01777);
if((rv < 0) && (rv != -EEXIST))
goto error;
rv = fs::clonepath(clonesrc,clonedst,oldfusepath_.parent_path()); rv = fs::clonepath(clonesrc,clonedst,oldfusepath_.parent_path());
if(rv == -ENOENT)
{
fs::mkdir_as({0,0},clonedst,01777);
rv = fs::clonepath(clonesrc,clonedst,oldfusepath_.parent_path());
}
if(rv < 0) if(rv < 0)
goto error; goto error;
@ -255,31 +248,27 @@ _rename_exdev_rename_target(const Policy::Action &actionPolicy_,
static static
int int
_rename_exdev_rel_symlink(const Policy::Action &actionPolicy_, _rename_exdev_rel_symlink(const fuse_req_ctx_t *ctx_,
const Policy::Action &actionPolicy_,
const Branches::Ptr branches_, const Branches::Ptr branches_,
const fs::path &oldfusepath_, const fs::path &oldfusepath_,
const fs::path &newfusepath_) const fs::path &newfusepath_)
{ {
int rv; int rv;
struct stat source;
fs::path target; fs::path target;
fs::path linkpath; fs::path linkpath;
std::vector<Branch*> branches; std::vector<Branch*> branches;
rv = ::_rename_exdev_rename_target(actionPolicy_, rv = ::_rename_exdev_rename_target(actionPolicy_,branches_,oldfusepath_,branches);
branches_,
oldfusepath_,
branches,
source);
if(rv < 0) if(rv < 0)
return rv; return rv;
linkpath = newfusepath_; linkpath = newfusepath_;
target = ".mergerfs_rename_exdev"; target = "/.mergerfs_rename_exdev";
target /= oldfusepath_; target /= oldfusepath_;
target = target.lexically_relative(linkpath.parent_path()); target = target.lexically_relative(linkpath.parent_path());
rv = FUSE::symlink_owned({source.st_uid,source.st_gid},target.c_str(),linkpath); rv = FUSE::symlink(ctx_,target.c_str(),linkpath);
if(rv < 0) if(rv < 0)
::_rename_exdev_rename_back(branches,oldfusepath_); ::_rename_exdev_rename_back(branches,oldfusepath_);
@ -288,23 +277,19 @@ _rename_exdev_rel_symlink(const Policy::Action &actionPolicy_,
static static
int int
_rename_exdev_abs_symlink(const Policy::Action &actionPolicy_, _rename_exdev_abs_symlink(const fuse_req_ctx_t *ctx_,
const Policy::Action &actionPolicy_,
const Branches::Ptr branches_, const Branches::Ptr branches_,
const fs::path &mount_, const fs::path &mount_,
const fs::path &oldfusepath_, const fs::path &oldfusepath_,
const fs::path &newfusepath_) const fs::path &newfusepath_)
{ {
int rv; int rv;
struct stat source;
fs::path target; fs::path target;
fs::path linkpath; fs::path linkpath;
std::vector<Branch*> branches; std::vector<Branch*> branches;
rv = ::_rename_exdev_rename_target(actionPolicy_, rv = ::_rename_exdev_rename_target(actionPolicy_,branches_,oldfusepath_,branches);
branches_,
oldfusepath_,
branches,
source);
if(rv < 0) if(rv < 0)
return rv; return rv;
@ -313,7 +298,7 @@ _rename_exdev_abs_symlink(const Policy::Action &actionPolicy_,
target /= ".mergerfs_rename_exdev"; target /= ".mergerfs_rename_exdev";
target /= oldfusepath_; target /= oldfusepath_;
rv = FUSE::symlink_owned({source.st_uid,source.st_gid},target.c_str(),linkpath); rv = FUSE::symlink(ctx_,target.c_str(),linkpath);
if(rv < 0) if(rv < 0)
::_rename_exdev_rename_back(branches,oldfusepath_); ::_rename_exdev_rename_back(branches,oldfusepath_);
@ -322,7 +307,8 @@ _rename_exdev_abs_symlink(const Policy::Action &actionPolicy_,
static static
int int
_rename_exdev(const fs::path &oldfusepath_, _rename_exdev(const fuse_req_ctx_t *ctx_,
const fs::path &oldfusepath_,
const fs::path &newfusepath_) const fs::path &newfusepath_)
{ {
switch(cfg.rename_exdev) switch(cfg.rename_exdev)
@ -330,12 +316,14 @@ _rename_exdev(const fs::path &oldfusepath_,
case RenameEXDEV::ENUM::PASSTHROUGH: case RenameEXDEV::ENUM::PASSTHROUGH:
return -EXDEV; return -EXDEV;
case RenameEXDEV::ENUM::REL_SYMLINK: case RenameEXDEV::ENUM::REL_SYMLINK:
return ::_rename_exdev_rel_symlink(cfg.func.rename.policy, return ::_rename_exdev_rel_symlink(ctx_,
cfg.func.rename.policy,
cfg.branches, cfg.branches,
oldfusepath_, oldfusepath_,
newfusepath_); newfusepath_);
case RenameEXDEV::ENUM::ABS_SYMLINK: case RenameEXDEV::ENUM::ABS_SYMLINK:
return ::_rename_exdev_abs_symlink(cfg.func.rename.policy, return ::_rename_exdev_abs_symlink(ctx_,
cfg.func.rename.policy,
cfg.branches, cfg.branches,
cfg.mountpoint, cfg.mountpoint,
oldfusepath_, oldfusepath_,
@ -374,7 +362,7 @@ FUSE::rename(const fuse_req_ctx_t *ctx_,
rv = ::_rename(oldfusepath,newfusepath); rv = ::_rename(oldfusepath,newfusepath);
if(rv == -EXDEV) if(rv == -EXDEV)
return ::_rename_exdev(oldfusepath,newfusepath); return ::_rename_exdev(ctx_,oldfusepath,newfusepath);
return rv; return rv;
} }

View file

@ -254,8 +254,6 @@ FUSE::statx(const fuse_req_ctx_t *ctx_,
timeout_); timeout_);
} }
// See fgetattr in fuse.h for why a node with no `fh` and no open file
// returns ENOENT.
int int
FUSE::statx_fh(const fuse_req_ctx_t *ctx_, FUSE::statx_fh(const fuse_req_ctx_t *ctx_,
const uint64_t fh_, const uint64_t fh_,
@ -269,7 +267,7 @@ FUSE::statx_fh(const fuse_req_ctx_t *ctx_,
fi = state.get_fi(ctx_,fh_); fi = state.get_fi(ctx_,fh_);
if(not fi) if(not fi)
return -ENOENT; return -EBADF;
rv = ::_statx(fi, rv = ::_statx(fi,
flags_|AT_STATX_DONT_SYNC, flags_|AT_STATX_DONT_SYNC,

View file

@ -22,13 +22,10 @@
#include "errno.hpp" #include "errno.hpp"
#include "error.hpp" #include "error.hpp"
#include "fs_clonepath.hpp" #include "fs_clonepath.hpp"
#include "fs_lchown.hpp"
#include "fs_lstat.hpp" #include "fs_lstat.hpp"
#include "fs_path.hpp" #include "fs_path.hpp"
#include "fs_inode.hpp" #include "fs_inode.hpp"
#include "fs_symlink.hpp"
#include "fs_symlink_as.hpp" #include "fs_symlink_as.hpp"
#include "fs_unlink.hpp"
#include "fuse_getattr.hpp" #include "fuse_getattr.hpp"
#include "ugid.hpp" #include "ugid.hpp"
@ -37,17 +34,10 @@
#include <sys/types.h> #include <sys/types.h>
#include <unistd.h> #include <unistd.h>
enum class SymlinkMode
{
CREATE_AS,
PRESERVE_OWNER
};
static static
int int
_symlink_loop_core(const ugid_t ugid_, _symlink_loop_core(const ugid_t ugid_,
const SymlinkMode mode_,
const fs::path &newbranch_, const fs::path &newbranch_,
const char *target_, const char *target_,
const fs::path &linkpath_, const fs::path &linkpath_,
@ -58,27 +48,7 @@ _symlink_loop_core(const ugid_t ugid_,
fullnewpath = newbranch_ / linkpath_; fullnewpath = newbranch_ / linkpath_;
if(mode_ == SymlinkMode::PRESERVE_OWNER)
{
struct stat owner{};
owner.st_uid = ugid_.uid;
owner.st_gid = ugid_.gid;
rv = fs::symlink(target_,fullnewpath.native());
if(rv < 0)
return rv;
rv = fs::lchown_check_on_error(fullnewpath.native(),owner);
if(rv < 0)
{
fs::unlink(fullnewpath.native());
return rv;
}
}
else
rv = fs::symlink_as(ugid_,target_,fullnewpath); rv = fs::symlink_as(ugid_,target_,fullnewpath);
if((rv >= 0) && (st_ != NULL) && (st_->st_ino == 0)) if((rv >= 0) && (st_ != NULL) && (st_->st_ino == 0))
{ {
fs::lstat(fullnewpath,st_); fs::lstat(fullnewpath,st_);
@ -94,7 +64,6 @@ _symlink_loop_core(const ugid_t ugid_,
static static
int int
_symlink_loop(const ugid_t ugid_, _symlink_loop(const ugid_t ugid_,
const SymlinkMode mode_,
const fs::path &existingbranch_, const fs::path &existingbranch_,
const std::vector<Branch*> &newbranches_, const std::vector<Branch*> &newbranches_,
const char *target_, const char *target_,
@ -114,7 +83,6 @@ _symlink_loop(const ugid_t ugid_,
err = rv; err = rv;
else else
err = ::_symlink_loop_core(ugid_, err = ::_symlink_loop_core(ugid_,
mode_,
newbranch->path, newbranch->path,
target_, target_,
linkpath_, linkpath_,
@ -127,7 +95,6 @@ _symlink_loop(const ugid_t ugid_,
static static
int int
_symlink(const ugid_t ugid_, _symlink(const ugid_t ugid_,
const SymlinkMode mode_,
const Policy::Search &searchFunc_, const Policy::Search &searchFunc_,
const Policy::Create &createFunc_, const Policy::Create &createFunc_,
const Branches::Ptr branches_, const Branches::Ptr branches_,
@ -155,7 +122,6 @@ _symlink(const ugid_t ugid_,
return -ENOENT; return -ENOENT;
return ::_symlink_loop(ugid_, return ::_symlink_loop(ugid_,
mode_,
existingbranches[0]->path, existingbranches[0]->path,
newbranches, newbranches,
target_, target_,
@ -164,10 +130,8 @@ _symlink(const ugid_t ugid_,
st_); st_);
} }
static
int int
_symlink_with_config(const ugid_t ugid_, FUSE::symlink(const fuse_req_ctx_t *ctx_,
const SymlinkMode mode_,
const char *target_, const char *target_,
const fs::path &linkpath_, const fs::path &linkpath_,
struct stat *st_, struct stat *st_,
@ -175,8 +139,7 @@ _symlink_with_config(const ugid_t ugid_,
{ {
int rv; int rv;
rv = ::_symlink(ugid_, rv = ::_symlink(ctx_,
mode_,
cfg.func.getattr.policy, cfg.func.getattr.policy,
cfg.func.symlink.policy, cfg.func.symlink.policy,
cfg.branches, cfg.branches,
@ -186,8 +149,7 @@ _symlink_with_config(const ugid_t ugid_,
if(rv == -EROFS) if(rv == -EROFS)
{ {
cfg.branches.find_and_set_mode_ro(); cfg.branches.find_and_set_mode_ro();
rv = ::_symlink(ugid_, rv = ::_symlink(ctx_,
mode_,
cfg.func.getattr.policy, cfg.func.getattr.policy,
cfg.func.symlink.policy, cfg.func.symlink.policy,
cfg.branches, cfg.branches,
@ -216,21 +178,6 @@ _symlink_with_config(const ugid_t ugid_,
return rv; return rv;
} }
int
FUSE::symlink_owned(const ugid_t owner_,
const char *target_,
const fs::path &linkpath_,
struct stat *st_,
fuse_timeouts_t *timeouts_)
{
return ::_symlink_with_config(owner_,
SymlinkMode::PRESERVE_OWNER,
target_,
linkpath_,
st_,
timeouts_);
}
int int
FUSE::symlink(const fuse_req_ctx_t *ctx_, FUSE::symlink(const fuse_req_ctx_t *ctx_,
const char *target_, const char *target_,
@ -240,8 +187,7 @@ FUSE::symlink(const fuse_req_ctx_t *ctx_,
{ {
const fs::path linkpath{linkpath_}; const fs::path linkpath{linkpath_};
return ::_symlink_with_config(ctx_, return FUSE::symlink(ctx_,
SymlinkMode::CREATE_AS,
target_, target_,
linkpath, linkpath,
st_, st_,

View file

@ -21,7 +21,6 @@
#include "fuse.h" #include "fuse.h"
#include "fs_path.hpp" #include "fs_path.hpp"
#include "ugid.hpp"
#include <string> #include <string>
@ -37,7 +36,7 @@ namespace FUSE
fuse_timeouts_t *timeouts = NULL); fuse_timeouts_t *timeouts = NULL);
int int
symlink_owned(const ugid_t owner, symlink(const fuse_req_ctx_t *ctx,
const char *target, const char *target,
const fs::path &linkpath, const fs::path &linkpath,
struct stat *st = NULL, struct stat *st = NULL,

View file

@ -33,9 +33,6 @@
#include "fuse.h" #include "fuse.h"
#include <mutex>
#include <shared_mutex>
static static
bool bool
@ -120,11 +117,47 @@ _move_and_pwriten(char const *buf_,
// N bytes written (short writes included) // N bytes written (short writes included)
// -errno on error // -errno on error
// See libfuse/include/fuse.h for more details // See libfuse/include/fuse.h for more details
static
int
_write_direct_io(const char *buf_,
const size_t count_,
const off_t offset_,
FileInfo *fi_)
{
ssize_t rv;
rv = fs::pwrite(fi_->fd,buf_,count_,offset_);
if(::_out_of_space(rv))
rv = ::_move_and_pwrite(buf_,count_,offset_,fi_,rv);
return rv;
}
// When not in direct_io mode write's return value is more complex. // When not in direct_io mode write's return value is more complex.
// 0 or less than `count` on EOF // 0 or less than `count` on EOF
// `count` on non-errors // `count` on non-errors
// -errno on error // -errno on error
// See libfuse/include/fuse.h for more details // See libfuse/include/fuse.h for more details
static
int
_write_cached(const char *buf_,
const size_t count_,
const off_t offset_,
FileInfo *fi_)
{
int err;
ssize_t rv;
rv = fs::pwriten(fi_->fd,buf_,count_,offset_,&err);
if(err == 0)
return rv;
if(err && !::_out_of_space(err))
return err;
rv = ::_move_and_pwriten(buf_,count_,offset_,fi_,err,rv);
return rv;
}
static static
int int
@ -142,61 +175,19 @@ _write(const fuse_req_ctx_t *ctx_,
// Concurrent writes can only happen if: // Concurrent writes can only happen if:
// 1) writeback-cache is enabled and using page caching // 1) writeback-cache is enabled and using page caching
// 2) parallel_direct_writes is enabled and file has // 2) parallel_direct_writes is enabled and file has `direct_io=true`
// `direct_io=true` // Will look into selectively locking in the future
// A reader/writer lock would probably be the best option given
ssize_t rv; // the expense of the write itself in comparison. Alternatively,
// could change the move file behavior to use a known target file
// and have threads use O_EXCL and back off and wait for the
// transfer to complete before retrying.
mutex_lockguard(fi->mutex);
if(fi->direct_io) if(fi->direct_io)
{ return ::_write_direct_io(buf_,count_,offset_,fi);
{
std::shared_lock<std::shared_mutex> slk(fi->mutex);
rv = fs::pwrite(fi->fd,buf_,count_,offset_);
}
if(not ::_out_of_space(rv)) return ::_write_cached(buf_,count_,offset_,fi);
return rv;
std::unique_lock<std::shared_mutex> ulk(fi->mutex);
// 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.
rv = fs::pwrite(fi->fd,buf_,count_,offset_);
if(::_out_of_space(rv))
rv = ::_move_and_pwrite(buf_,count_,offset_,fi,rv);
return rv;
}
else
{
int err;
ssize_t written;
{
std::shared_lock<std::shared_mutex> slk(fi->mutex);
written = fs::pwriten(fi->fd,buf_,count_,offset_,&err);
}
if(err == 0)
return written;
if(err && not ::_out_of_space(err))
return err;
std::unique_lock<std::shared_mutex> ulk(fi->mutex);
// Re-check the remaining suffix under exclusive lock as another move
// may have already run. Replaying a written prefix would duplicate
// data on O_APPEND handles.
written += fs::pwriten(fi->fd,
buf_ + written,
count_ - written,
offset_ + written,
&err);
if(err == 0)
return written;
if(err && not ::_out_of_space(err))
return err;
return ::_move_and_pwriten(buf_,count_,offset_,fi,err,written);
}
} }
int int

View file

@ -32,12 +32,8 @@ enum
IOPRIO_WHO_PROCESS = 1 IOPRIO_WHO_PROCESS = 1
}; };
namespace ioprio
{
std::atomic<bool> _enabled{false};
}
thread_local int ioprio::SetFrom::thread_prio = -1; thread_local int ioprio::SetFrom::thread_prio = -1;
bool _enabled = false;
int int
ioprio::get(const int who_) ioprio::get(const int who_)
@ -73,14 +69,22 @@ ioprio::set(const int who_,
void void
ioprio::enable(const bool enable_) ioprio::enable(const bool enable_)
{ {
_enabled.store(enable_,std::memory_order_relaxed); _enabled = enable_;
} }
void bool
ioprio::SetFrom::_slow_apply(const pid_t pid_) ioprio::enabled()
{
return _enabled;
}
ioprio::SetFrom::SetFrom(const pid_t pid_)
{ {
int client_prio; int client_prio;
if(!_enabled)
return;
client_prio = ioprio::get(pid_); client_prio = ioprio::get(pid_);
if(client_prio < 0) if(client_prio < 0)
return; return;

View file

@ -18,27 +18,13 @@
#pragma once #pragma once
#include <atomic>
#include <sys/types.h> #include <sys/types.h>
namespace ioprio namespace ioprio
{ {
// Exposed so the disabled-path check in SetFrom can inline into
// every fuse_read/fuse_write as an atomic load + branch, with no
// function overhead.
extern std::atomic<bool> _enabled;
[[gnu::always_inline]]
inline
bool
enabled()
{
return _enabled.load(std::memory_order_relaxed);
}
void enable(const bool); void enable(const bool);
bool enabled();
int get(const int who); int get(const int who);
int set(const int who, const int ioprio); int set(const int who, const int ioprio);
@ -47,15 +33,6 @@ namespace ioprio
{ {
static thread_local int thread_prio; static thread_local int thread_prio;
[[gnu::always_inline]] SetFrom(const pid_t pid);
inline
SetFrom(const pid_t pid_)
{
if(ioprio::enabled())
_slow_apply(pid_);
}
private:
void _slow_apply(const pid_t);
}; };
}; };

View file

@ -301,7 +301,7 @@ _warn_if_not_root()
"mergerfs is not running as root" "mergerfs is not running as root"
" and may not work correctly"; " and may not work correctly";
fmt::println(stderr,"* WARNING: {}",s); fmt::println(stderr,"* WARNING: {}",s);
SysLog::warning("{}",s); SysLog::warning(s);
} }
int int

View file

@ -86,7 +86,7 @@ _create(const Branches::Ptr &branches_,
branch = ::_create_1(branches_,fusepath,&error); branch = ::_create_1(branches_,fusepath,&error);
if(branch) if(branch)
break; break;
if(fusepath.empty()) if(fusepath == "/")
break; break;
fusepath = fusepath.parent_path(); fusepath = fusepath.parent_path();
} }

View file

@ -83,7 +83,7 @@ _create(const Branches::Ptr &branches_,
branch = ::_create_1(branches_,fusepath,&err); branch = ::_create_1(branches_,fusepath,&err);
if(branch) if(branch)
break; break;
if(fusepath.empty()) if(fusepath == "/")
break; break;
fusepath = fusepath.parent_path(); fusepath = fusepath.parent_path();
} }

View file

@ -86,7 +86,7 @@ _create(const Branches::Ptr &branches_,
branch = ::_create_1(branches_,fusepath,&error); branch = ::_create_1(branches_,fusepath,&error);
if(branch) if(branch)
break; break;
if(fusepath.empty()) if(fusepath == "/")
break; break;
fusepath = fusepath.parent_path(); fusepath = fusepath.parent_path();

View file

@ -91,7 +91,7 @@ _get_branchinfo(const Branches::Ptr &branches_,
rv = ::_create_1(branches_,fusepath,branchinfo_,sum_); rv = ::_create_1(branches_,fusepath,branchinfo_,sum_);
if(branchinfo_->size()) if(branchinfo_->size())
break; break;
if(fusepath.empty()) if(fusepath == "/")
break; break;
fusepath = fusepath.parent_path(); fusepath = fusepath.parent_path();
} }

View file

@ -103,12 +103,8 @@ public:
{ {
} }
// Move constructor runs during initial insertion into the
// concurrent_flat_map before the new entry is reachable by the
// other threads. There is no concurrent observer of the moved
// value at this point so relaxed load is sufficient.
OpenFile(OpenFile &&o_) noexcept OpenFile(OpenFile &&o_) noexcept
: ref_count(o_.ref_count.load(std::memory_order_relaxed)), : ref_count(o_.ref_count.load()),
backing_id(o_.backing_id), backing_id(o_.backing_id),
fi(o_.fi) fi(o_.fi)
{ {

View file

@ -4,10 +4,11 @@ import errno
import os import os
import sys import sys
import uuid import uuid
from os.path import join
from posix_parity import cleanup_dir from posix_parity import cleanup_dir
from posix_parity import fail from posix_parity import fail
from posix_parity import join
from posix_parity import mergerfs_branches
from posix_parity import mergerfs_get_option from posix_parity import mergerfs_get_option
from posix_parity import mergerfs_mount from posix_parity import mergerfs_mount
from posix_parity import mergerfs_set_option from posix_parity import mergerfs_set_option
@ -25,136 +26,123 @@ def get_errno(func):
return exc.errno return exc.errno
def require_symlink(path, expected, label): def symlink_resolves(path):
# Inspect the backend: rename/link can leave a cached regular pool inode.
if not os.path.islink(path):
return f"{label}: expected backend symlink fallback"
target = os.readlink(path) target = os.readlink(path)
if target != expected: if os.path.isabs(target):
return f"{label}: target {target!r} != {expected!r}" return os.path.realpath(target)
return os.path.realpath(join(os.path.dirname(path), target))
def require_symlink(path, label):
if not os.path.islink(path):
return f"{label}: expected symlink fallback"
if not os.path.exists(path):
return f"{label}: symlink target does not exist: {os.readlink(path)!r}"
return None return None
def require_payload(path, label): def setup_paths(branches, mount, rel_base, name):
with open(path, "rb") as fp: src_rel = join(rel_base, f"{name}.src")
if fp.read() != b"src": dst_rel = join(rel_base, "dst", name)
return f"{label}: backend payload mismatch"
return None
def setup_paths(branches, mount, rel_base, name, root=False):
src_rel = f"{rel_base}_{name}.src" if root else join(rel_base, f"{name}.src")
dst_rel = join(rel_base, "dst", "nested", name)
src = join(mount, src_rel) src = join(mount, src_rel)
dst = join(mount, dst_rel) dst = join(mount, dst_rel)
cleanup_dir(join(branches[0], rel_base)) cleanup_dir(join(branches[0], rel_base))
cleanup_dir(join(branches[1], rel_base)) cleanup_dir(join(branches[1], rel_base))
os.makedirs(join(branches[0], rel_base), exist_ok=True) os.makedirs(join(branches[0], rel_base), exist_ok=True)
os.makedirs(join(branches[1], rel_base, "dst", "nested"), exist_ok=True) os.makedirs(join(branches[1], rel_base, "dst"), exist_ok=True)
touch(join(branches[0], src_rel), b"src") touch(join(branches[0], src_rel), b"src")
return src, dst, src_rel, dst_rel return src, dst, join(branches[0], src_rel)
def main(): def main():
try: try:
with mergerfs_mount( with mergerfs_mount(num_branches=2) as (mount, branches):
num_branches=2, options="defaults,use_ino,category.create=mfs,minfreespace=0"
) as (mount, branches):
rel_base = f".mergerfs_exdev_test_{os.getpid()}_{uuid.uuid4().hex}" rel_base = f".mergerfs_exdev_test_{os.getpid()}_{uuid.uuid4().hex}"
root_sources = []
if len(branches) < 2: if len(branches) < 2:
print("EXDEV fallback test requires at least 2 branches", end="") print("EXDEV fallback test requires at least 2 branches", end="")
return SKIP return SKIP
branches = branches[:2] branches = branches[:2]
if os.stat(branches[0]).st_dev == os.stat(branches[1]).st_dev:
print("EXDEV fallback test requires branches on different devices", end="")
return SKIP
try:
try: try:
orig_create = mergerfs_get_option(mount, "category.create") orig_create = mergerfs_get_option(mount, "category.create")
orig_link = mergerfs_get_option(mount, "link-exdev") orig_link = mergerfs_get_option(mount, "link-exdev")
orig_rename = mergerfs_get_option(mount, "rename-exdev") orig_rename = mergerfs_get_option(mount, "rename-exdev")
except (PermissionError, FileNotFoundError, OSError):
print("EXDEV fallback runtime options unavailable", end="")
return SKIP
try: try:
mergerfs_set_option(mount, "category.create", "epmfs") mergerfs_set_option(mount, "category.create", "epmfs")
src, dst, src_rel, _ = setup_paths(branches, mount, rel_base, "link_pass") src, dst, src_base = setup_paths(branches, mount, rel_base, "link_pass")
mergerfs_set_option(mount, "link-exdev", "passthrough") mergerfs_set_option(mount, "link-exdev", "passthrough")
err = get_errno(lambda: os.link(src, dst + ".link.pass")) err = get_errno(lambda: os.link(src, dst + ".link.pass"))
if err != errno.EXDEV: if err != errno.EXDEV:
return fail(f"link-exdev passthrough expected EXDEV, errno={err}") print(f"link-exdev passthrough did not exercise EXDEV, errno={err}", end="")
return SKIP
for mode in ("rel-symlink", "abs-base-symlink", "abs-pool-symlink"): for mode in ("rel-symlink", "abs-base-symlink", "abs-pool-symlink"):
src, dst, src_rel, dst_rel = setup_paths(branches, mount, rel_base, f"link_{mode}") src, dst, src_base = setup_paths(branches, mount, rel_base, f"link_{mode}")
mergerfs_set_option(mount, "link-exdev", mode) mergerfs_set_option(mount, "link-exdev", mode)
err = get_errno(lambda: os.link(src, dst)) link_path = dst + ".link"
err = get_errno(lambda: os.link(src, link_path))
if err != 0: if err != 0:
return fail(f"link-exdev={mode} returned errno={err}") return fail(f"link-exdev={mode} returned errno={err}")
src_base = join(branches[0], src_rel) err_msg = require_symlink(link_path, f"link-exdev={mode}")
if mode == "rel-symlink":
expected = os.path.relpath(src, os.path.dirname(dst))
elif mode == "abs-base-symlink":
expected = src_base
else:
expected = src
err_msg = require_symlink(join(branches[1], dst_rel), expected, f"link-exdev={mode}")
if err_msg: if err_msg:
return fail(err_msg) return fail(err_msg)
err_msg = require_payload(src_base, f"link-exdev={mode}") resolved = symlink_resolves(link_path)
if err_msg: if mode == "abs-base-symlink" and resolved != os.path.realpath(src_base):
return fail(err_msg) return fail(f"link-exdev={mode}: target {resolved!r} != {os.path.realpath(src_base)!r}")
if os.path.lexists(join(branches[0], dst_rel)): if mode != "abs-base-symlink" and resolved != os.path.realpath(src):
return fail(f"link-exdev={mode}: destination unexpectedly created on source branch") return fail(f"link-exdev={mode}: target {resolved!r} != {os.path.realpath(src)!r}")
src, dst, _, _ = setup_paths(branches, mount, rel_base, "rename_pass") src_ren, dst_ren, _ = setup_paths(branches, mount, rel_base, "rename_pass")
mergerfs_set_option(mount, "rename-exdev", "passthrough") mergerfs_set_option(mount, "rename-exdev", "passthrough")
err = get_errno(lambda: os.rename(src, dst)) err = get_errno(lambda: os.rename(src_ren, dst_ren + ".ren.pass"))
if err != errno.EXDEV: if err != errno.EXDEV:
return fail(f"rename-exdev passthrough expected EXDEV, errno={err}") print(f"rename-exdev passthrough did not exercise EXDEV, errno={err}", end="")
return SKIP
# Run root sources first, before any fallback creates staging.
for root in (True, False):
for mode in ("rel-symlink", "abs-symlink"): for mode in ("rel-symlink", "abs-symlink"):
# Each root case must start without a staging directory. src_ren, dst_ren, _ = setup_paths(branches, mount, rel_base, f"rename_{mode}")
if root:
cleanup_dir(join(branches[0], ".mergerfs_rename_exdev"))
name = f"rename_{mode}_{root}"
if root:
root_sources.append(f"{rel_base}_{name}.src")
src, dst, src_rel, dst_rel = setup_paths(branches, mount, rel_base, name, root=root)
mergerfs_set_option(mount, "rename-exdev", mode) mergerfs_set_option(mount, "rename-exdev", mode)
err = get_errno(lambda: os.rename(src, dst)) ren_path = dst_ren + ".ren"
err = get_errno(lambda: os.rename(src_ren, ren_path))
if err != 0: if err != 0:
return fail(f"rename-exdev={mode}, root={root} returned errno={err}") return fail(f"rename-exdev={mode} returned errno={err}")
staged_rel = join(".mergerfs_rename_exdev", src_rel) err_msg = require_symlink(ren_path, f"rename-exdev={mode}")
pool_target = join(mount, staged_rel)
expected = os.path.relpath(pool_target, os.path.dirname(dst)) if mode == "rel-symlink" else pool_target
label = f"rename-exdev={mode}, root={root}"
err_msg = require_symlink(join(branches[1], dst_rel), expected, label)
if err_msg:
return fail(err_msg)
if os.path.lexists(join(branches[0], src_rel)):
return fail(f"{label}: source was not moved")
err_msg = require_payload(join(branches[0], staged_rel), label)
if err_msg: if err_msg:
return fail(err_msg) return fail(err_msg)
target = symlink_resolves(ren_path)
if ".mergerfs_rename_exdev" not in target:
return fail(f"rename-exdev={mode}: target not moved under .mergerfs_rename_exdev: {target!r}")
with open(ren_path, "rb") as fp:
if fp.read() != b"src":
return fail(f"rename-exdev={mode}: symlink target content mismatch")
except (PermissionError, FileNotFoundError, OSError):
return SKIP
finally: finally:
try:
mergerfs_set_option(mount, "category.create", orig_create) mergerfs_set_option(mount, "category.create", orig_create)
mergerfs_set_option(mount, "link-exdev", orig_link) mergerfs_set_option(mount, "link-exdev", orig_link)
mergerfs_set_option(mount, "rename-exdev", orig_rename) mergerfs_set_option(mount, "rename-exdev", orig_rename)
except OSError:
pass
return 0 return 0
finally: finally:
for branch in branches: for branch in branches:
cleanup_dir(join(branch, rel_base)) cleanup_dir(join(branch, rel_base))
cleanup_dir(join(branch, ".mergerfs_rename_exdev", rel_base))
for src_rel in root_sources:
for path in (join(branch, src_rel), join(branch, ".mergerfs_rename_exdev", src_rel)):
if os.path.lexists(path):
os.unlink(path)
except RuntimeError as exc: except RuntimeError as exc:
if str(exc) in ("mergerfs binary not found", "fusermount3/fusermount not found"):
print(str(exc), end="") print(str(exc), end="")
return SKIP return 77
return fail(f"EXDEV fallback test failed: {exc}")
except OSError as exc:
return fail(f"EXDEV fallback test failed: {exc}")
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -1,101 +1,84 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import errno
import os import os
import shutil
import subprocess
import sys import sys
import tempfile
from posix_parity import cleanup_dir
from posix_parity import fail from posix_parity import fail
from posix_parity import find_fusermount from posix_parity import join
from posix_parity import find_mergerfs from posix_parity import mergerfs_branches
from posix_parity import mount_mergerfs from posix_parity import mergerfs_get_option
from posix_parity import unmount_mergerfs from posix_parity import mergerfs_mount
from posix_parity import mergerfs_set_option
from posix_parity import temp_dir
from posix_parity import touch
SKIP = 77 SKIP = 77
def test_partial_append():
with tempfile.TemporaryDirectory(prefix="mergerfs-enospc-") as root:
source, destination, pool = [os.path.join(root, name) for name in ("source", "destination", "pool")]
for directory in (source, destination, pool):
os.mkdir(directory)
result = subprocess.run(
["mount", "-t", "tmpfs", "-o", "size=1m", "tmpfs", source],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
if result.returncode:
print(f"constrained tmpfs unavailable: {result.stderr.decode(errors='replace')}", end="")
return SKIP
mounted = False
try:
block_size = os.statvfs(source).f_frsize
initial = b"initial\n" * (block_size // 8)
with open(os.path.join(source, "target"), "wb") as stream:
stream.write(initial)
stat = os.statvfs(source)
remaining = block_size
available = stat.f_bavail * stat.f_frsize
with open(os.path.join(source, "filler"), "wb") as stream:
stream.write(b"F" * (available - remaining))
mount_mergerfs(
[source, destination], pool,
"minfreespace=0,cache.files=full,cache.writeback=false,moveonenospc=mfs",
)
mounted = True
# The first write appends a prefix before ENOSPC. Relocation must
# preserve that progress instead of replaying it on the new branch.
payload = bytes(range(256)) * (block_size // 64)
fd = os.open(os.path.join(pool, "target"), os.O_WRONLY | os.O_APPEND)
try:
written = os.write(fd, payload)
finally:
os.close(fd)
if written != len(payload):
return fail(f"append returned {written}, expected {len(payload)}")
relocated = os.path.join(destination, "target")
if os.path.exists(os.path.join(source, "target")) or not os.path.isfile(relocated):
return fail("ENOSPC append did not relocate the file")
with open(relocated, "rb") as stream:
actual = stream.read()
expected = initial + payload
if actual != expected:
return fail(f"relocated append corrupted data: expected {len(expected)} bytes, got {len(actual)}")
with open(os.path.join(pool, "target"), "rb") as stream:
if stream.read() != expected:
return fail("relocated append differs through the pool")
return 0
finally:
if mounted:
unmount_mergerfs(pool)
subprocess.run(["umount", source], check=True)
def main(): def main():
if len(sys.argv) == 2 and sys.argv[1] == "--isolated": try:
return test_partial_append() with mergerfs_mount(num_branches=2) as (mount, branches):
try:
if find_mergerfs() is None or find_fusermount() is None: orig_moveonenospc = mergerfs_get_option(mount, "moveonenospc")
print("mergerfs or fusermount unavailable", end="") except (PermissionError, FileNotFoundError):
print("moveonenospc runtime option unavailable", end="")
return SKIP return SKIP
if any(shutil.which(tool) is None for tool in ("unshare", "mount", "umount")): except OSError as exc:
print("unshare/mount/umount unavailable", end="") if exc.errno == errno.EOPNOTSUPP:
print("moveonenospc runtime option unsupported", end="")
return SKIP
raise
if len(branches) < 2:
print("moveonenospc test requires at least 2 branches", end="")
return SKIP return SKIP
# Limit disk usage inside a private namespace, including for non-root runs. merge_base = temp_dir(mount)
namespace = ["unshare", "-Urnm"]
probe = subprocess.run(namespace + ["true"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) try:
if probe.returncode: mergerfs_set_option(mount, "moveonenospc", "mfs")
print("private user/mount namespaces unavailable", end="") if mergerfs_get_option(mount, "moveonenospc") != "mfs":
return fail("moveonenospc: failed to set documented policy value")
merge_file = join(merge_base, "enospc_test")
touch(merge_file, b"test data for enospc")
if not os.path.exists(merge_file):
return fail("moveonenospc: file was not created")
fullpath = None
try:
fullpath = os.getxattr(merge_file, "user.mergerfs.fullpath").decode()
except OSError:
pass
if fullpath and not os.path.exists(fullpath):
return fail(f"moveonenospc: fullpath does not exist on disk: {fullpath}")
with open(merge_file, "r") as f:
content = f.read()
if content != "test data for enospc":
return fail(f"moveonenospc: file content mismatch: got {content!r}")
mergerfs_set_option(mount, "moveonenospc", orig_moveonenospc)
print("moveonenospc ENOSPC path requires a constrained branch", end="")
return SKIP return SKIP
return subprocess.run(namespace + [sys.executable, os.path.realpath(__file__), "--isolated"]).returncode except Exception as exc:
try:
mergerfs_set_option(mount, "moveonenospc", orig_moveonenospc)
except Exception:
pass
return fail(str(exc))
finally:
cleanup_dir(merge_base)
except RuntimeError as exc:
print(str(exc), end="")
return 77
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -1,95 +0,0 @@
#!/usr/bin/env python3
# The two cases reported in #1693. lstat() of a directory, or of a path
# below it, while rm -rf removes it must succeed or return ENOENT. And
# rm -rf of a directory together with rm -rf of the directory above it
# must both succeed and leave nothing behind. When one rm removes a
# directory the other still has open, the kernel sends GETATTR for it
# in the other's permission checks, which mergerfs answered with EBADF,
# so lstat() returned EBADF and rm failed with "Bad file descriptor".
#
# cache.attr=0 makes the kernel send GETATTR every time. The lstat()
# case then fails in every run without the fix. The rm -rf case is a
# narrower race met in only a few runs; TEST_use_dirfd_after_rmdir
# covers its cause, a call through the dirfd of a removed directory,
# without a race.
import collections
import os
import subprocess
import time
from posix_parity import errno_name
from posix_parity import fail
from posix_parity import mergerfs_mount
OPTIONS = "defaults,cache.attr=0"
SECONDS = 2.0
def make_tree(path, width=4, depth=3):
os.makedirs(path, exist_ok=True)
for k in range(width):
open(os.path.join(path, f"f{k}"), "w").close()
if depth > 0:
for k in range(width):
make_tree(os.path.join(path, f"d{k}"), width, depth - 1)
def lstat_during_rm(mount):
counts = collections.Counter()
deadline = time.monotonic() + SECONDS
while time.monotonic() < deadline:
top = os.path.join(mount, "l")
make_tree(os.path.join(top, "inner", "sub"), width=3, depth=0)
rm = subprocess.Popen(["rm", "-rf", os.path.join(top, "inner")])
while rm.poll() is None:
for rel in ("inner", "inner/sub"):
try:
os.lstat(os.path.join(top, rel))
counts["ok"] += 1
except OSError as exc:
counts[errno_name(exc.errno)] += 1
del counts["ok"]
counts.pop("ENOENT", None)
return counts
def concurrent_rm(mount):
failures = collections.Counter()
deadline = time.monotonic() + SECONDS
while time.monotonic() < deadline:
top = os.path.join(mount, "c")
make_tree(os.path.join(top, "inner"))
procs = [subprocess.Popen(["rm", "-rf", path], stderr=subprocess.PIPE)
for path in (os.path.join(top, "inner"), top)]
for proc in procs:
_, err = proc.communicate()
if proc.returncode != 0:
failures[err.decode().strip().splitlines()[-1].split(": ")[-1]] += 1
if os.path.lexists(top):
failures["left behind"] += 1
subprocess.run(["rm", "-rf", top])
return failures
def main():
try:
with mergerfs_mount(num_branches=1, options=OPTIONS) as (mount, _):
errors = lstat_during_rm(mount)
if errors:
summary = " ".join(f"{k}={v}" for k, v in sorted(errors.items()))
return fail(f"lstat during rm -rf: {summary}")
failures = concurrent_rm(mount)
if failures:
summary = ", ".join(f"{k}: {v}" for k, v in sorted(failures.items()))
return fail(f"concurrent rm -rf: {summary}")
return 0
except RuntimeError as exc:
print(str(exc), end="")
return 77
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -1,151 +0,0 @@
#!/usr/bin/env python3
# Issue #1693: once a file or directory is removed (unlink, rmdir, or a
# rename over it), libfuse has no path for its node, but the kernel can
# still hold it: an open dirfd, a cwd, an O_PATH fd, or a dentry it
# resolved just before the removal. It then sends GETATTR or SETATTR with
# no file handle, for example in the permission check of an *at() call.
# Those requests used to fail with EBADF, so lstat() could return EBADF
# and rm -rf reported "Bad file descriptor" and left entries behind.
#
# mergerfs now answers ENOENT. A local filesystem returns ENOENT for
# *at() calls in a removed directory, so those must match it. It
# succeeds on the removed object itself, but mergerfs has nothing left
# on the branches to act on, so ENOENT is accepted there. EBADF and
# ESTALE never are: the kernel retries ESTALE once, but a call through
# a dirfd or cwd of a removed directory meets the same node again.
#
# cache.attr=0 makes the kernel send GETATTR every time, so this shows up
# deterministically instead of only in a race.
import os
import stat
import tempfile
from posix_parity import cleanup_dir
from posix_parity import errno_name
from posix_parity import fail
from posix_parity import mergerfs_mount
OPTIONS = "defaults,use_ino,category.create=mfs,cache.attr=0"
# A local filesystem returns ENOENT for these: the kernel refuses lookups
# in a removed directory. Not compared against the native run since that
# may be on NFS, which can return ESTALE.
AT_CALLS = (
"unlinkat(dead, x)",
"rmdirat(dead, x)",
"fstatat(dead, x)",
"openat(dead, x, O_CREAT)",
"mkdirat(dead, x)",
)
# Must give the local filesystem's result or ENOENT.
ON_REMOVED = (
"fstat(dead)",
"fchmod(dead)",
"readdir(dead)",
'lstat(".") in removed cwd',
"fstat(dir replaced by rename)",
"fstat(O_PATH fd of unlinked file)",
)
def outcome(func):
try:
rv = func()
except OSError as exc:
return errno_name(exc.errno)
if isinstance(rv, os.stat_result):
return ("ok", rv.st_nlink, stat.S_IFMT(rv.st_mode))
return ("ok", rv)
def removed_dirfd(root, name):
path = os.path.join(root, name)
os.mkdir(path)
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
os.rmdir(path)
return fd
def scenarios(root):
results = {}
fd = removed_dirfd(root, "dead")
try:
results["unlinkat(dead, x)"] = outcome(lambda: os.unlink("x", dir_fd=fd))
results["rmdirat(dead, x)"] = outcome(lambda: os.rmdir("x", dir_fd=fd))
results["fstatat(dead, x)"] = outcome(lambda: os.lstat("x", dir_fd=fd))
results["openat(dead, x, O_CREAT)"] = outcome(
lambda: os.close(os.open("x", os.O_CREAT | os.O_WRONLY, 0o644, dir_fd=fd)))
results["mkdirat(dead, x)"] = outcome(lambda: os.mkdir("x", dir_fd=fd))
results["fstat(dead)"] = outcome(lambda: os.fstat(fd))
results["fchmod(dead)"] = outcome(lambda: os.chmod(fd, 0o755))
results["readdir(dead)"] = outcome(lambda: os.listdir(fd))
finally:
os.close(fd)
path = os.path.join(root, "cwd")
os.mkdir(path)
here = os.getcwd()
os.chdir(path)
try:
os.rmdir(path)
results['lstat(".") in removed cwd'] = outcome(lambda: os.lstat("."))
finally:
os.chdir(here)
src = os.path.join(root, "src")
dst = os.path.join(root, "dst")
os.mkdir(src)
os.mkdir(dst)
fd = os.open(dst, os.O_RDONLY | os.O_DIRECTORY)
try:
os.rename(src, dst)
results["fstat(dir replaced by rename)"] = outcome(lambda: os.fstat(fd))
finally:
os.close(fd)
os.rmdir(dst)
# O_PATH sends no OPEN, so mergerfs has no open file to fall back on.
path = os.path.join(root, "file")
open(path, "w").close()
fd = os.open(path, os.O_PATH)
try:
os.unlink(path)
results["fstat(O_PATH fd of unlinked file)"] = outcome(lambda: os.fstat(fd))
finally:
os.close(fd)
return results
def main():
try:
with mergerfs_mount(num_branches=1, options=OPTIONS) as (mount, branches):
native = tempfile.mkdtemp(dir=os.path.dirname(branches[0]))
try:
merged = scenarios(mount)
expected = scenarios(native)
for name in AT_CALLS:
if merged[name] != "ENOENT":
return fail(f"{name}: mergerfs={merged[name]} "
"expected ENOENT")
for name in ON_REMOVED:
if merged[name] not in (expected[name], "ENOENT"):
return fail(f"{name}: mergerfs={merged[name]} "
f"expected {expected[name]} or ENOENT")
return 0
except Exception as exc:
return fail(str(exc))
finally:
cleanup_dir(native)
except RuntimeError as exc:
print(str(exc), end="")
return 77
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -188,10 +188,6 @@ def fail(msg):
return 1 return 1
def errno_name(err):
return errno.errorcode.get(err, str(err))
def join(root, rel): def join(root, rel):
return os.path.join(root, rel) return os.path.join(root, rel)

View file

@ -1,22 +1,16 @@
#include "acutest/acutest.h" #include "acutest/acutest.h"
#include "config.hpp" #include "config.hpp"
#include "fs_clonepath.hpp"
#include "fs_copyfile.hpp" #include "fs_copyfile.hpp"
#include "fs_inode.hpp" #include "fs_inode.hpp"
#include "from_string.hpp" #include "from_string.hpp"
#include "fuse_link.hpp"
#include "fuse_rename.hpp"
#include "fuse_symlink.hpp"
#include "hashset.hpp" #include "hashset.hpp"
#include "num.hpp" #include "num.hpp"
#include "policies.hpp"
#include "rapidhash/rapidhash.h" #include "rapidhash/rapidhash.h"
#include "rnd.hpp" #include "rnd.hpp"
#include "str.hpp" #include "str.hpp"
#include "thread_pool.hpp" #include "thread_pool.hpp"
#include <boost/unordered/concurrent_flat_map.hpp>
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
#include <cstring> #include <cstring>
@ -24,7 +18,6 @@
#include <fcntl.h> #include <fcntl.h>
#include <fstream> #include <fstream>
#include <future> #include <future>
#include <limits>
#include <mutex> #include <mutex>
#include <numeric> #include <numeric>
#include <optional> #include <optional>
@ -33,7 +26,6 @@
#include <errno.h> #include <errno.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h> #include <unistd.h>
template<typename Predicate> template<typename Predicate>
@ -58,15 +50,6 @@ test_nop()
TEST_CHECK(true); TEST_CHECK(true);
} }
void
test_boost_concurrent_flat_map_empty_lookup()
{
boost::concurrent_flat_map<int,int> map;
// An unallocated map uses dummy metadata; atomic reads must be safe on ARMv5.
TEST_CHECK(map.count(42) == 0);
}
void void
test_config_bool() test_config_bool()
{ {
@ -2980,553 +2963,6 @@ test_config_prune_cmd_xattr()
TEST_CHECK(Config::prune_cmd_xattr("") == sv("")); TEST_CHECK(Config::prune_cmd_xattr("") == sv(""));
} }
static
void
test_msp_create_rejected(const Policy::CreateImpl &policy_)
{
char tmp_template[] = "/tmp/mergerfs-test-msp-rejected-XXXXXX";
if(::mkdtemp(tmp_template) == nullptr)
{
TEST_CHECK(false);
return;
}
const fs::path tmp_dir = tmp_template;
const fs::path first = tmp_dir / "first";
const fs::path second = tmp_dir / "second";
for(const auto &path : {first,second})
{
std::error_code ec;
const bool created = std::filesystem::create_directory(path,ec);
TEST_CHECK(created && !ec);
if(!created || ec)
{
std::filesystem::remove_all(tmp_dir);
return;
}
}
Branches branches;
branches.minfreespace = 0;
const int rv = branches.from_string(first.string() + ":" + second.string());
TEST_CHECK(rv == 0);
Branches::Ptr ptr = branches;
TEST_CHECK(ptr->size() == 2);
if((rv != 0) || (ptr->size() != 2))
{
std::filesystem::remove_all(tmp_dir);
return;
}
for(const auto mode : {Branch::Mode::RW,Branch::Mode::RO,Branch::Mode::NC})
{
for(auto &branch : *ptr)
{
branch.mode = mode;
branch.set_minfreespace(std::numeric_limits<u64>::max());
}
for(const auto &path : {fs::path("missing/child"),fs::path("")})
{
std::vector<Branch*> selected;
const int expected = (mode == Branch::Mode::RW) ? -ENOSPC : -EROFS;
TEST_CHECK(policy_(ptr,path,selected) == expected);
TEST_MSG("policy: %s; path: '%s'; mode: %d",
policy_.name.c_str(),path.c_str(),static_cast<int>(mode));
TEST_CHECK(selected.empty());
}
}
std::filesystem::remove_all(tmp_dir);
}
void
test_msppfrd_create_rejected_relative()
{
test_msp_create_rejected(Policies::Create::msppfrd);
}
void
test_mspmfs_create_rejected_relative()
{
test_msp_create_rejected(Policies::Create::mspmfs);
}
void
test_msplfs_create_rejected_relative()
{
test_msp_create_rejected(Policies::Create::msplfs);
}
void
test_msplus_create_rejected_relative()
{
test_msp_create_rejected(Policies::Create::msplus);
}
void
test_msp_create_relative_fallback()
{
char tmp_template[] = "/tmp/mergerfs-test-msp-fallback-XXXXXX";
if(::mkdtemp(tmp_template) == nullptr)
{
TEST_CHECK(false);
return;
}
const fs::path tmp_dir = tmp_template;
const fs::path farther = tmp_dir / "farther";
const fs::path closer = tmp_dir / "closer";
for(const auto &path : {farther / "parent",closer / "parent/child",
farther / "rejected/child",closer / "rejected"})
{
std::error_code ec;
const bool created = std::filesystem::create_directories(path,ec);
TEST_CHECK(created && !ec);
if(!created || ec)
{
std::filesystem::remove_all(tmp_dir);
return;
}
}
Branches branches;
branches.minfreespace = 0;
const int rv = branches.from_string(farther.string() + ":" + closer.string());
TEST_CHECK(rv == 0);
Branches::Ptr ptr = branches;
TEST_CHECK(ptr->size() == 2);
if((rv != 0) || (ptr->size() != 2))
{
std::filesystem::remove_all(tmp_dir);
return;
}
const Policy::CreateImpl *policies[] = {
&Policies::Create::msppfrd,
&Policies::Create::mspmfs,
&Policies::Create::msplfs,
&Policies::Create::msplus
};
for(const auto policy : policies)
{
(*ptr)[0].set_minfreespace(std::numeric_limits<u64>::max());
for(const auto &path : {fs::path("missing/child"),fs::path(""),
fs::path("rejected/child")})
{
std::vector<Branch*> selected;
TEST_CHECK((*policy)(ptr,path,selected) == 0);
TEST_MSG("policy: %s; path: '%s'",policy->name.c_str(),path.c_str());
TEST_CHECK(selected.size() == 1);
if(selected.size() == 1)
TEST_CHECK(selected[0] == &(*ptr)[1]);
}
(*ptr)[0].set_minfreespace(0);
std::vector<Branch*> selected;
TEST_CHECK((*policy)(ptr,"parent/child/missing",selected) == 0);
TEST_MSG("policy: %s",policy->name.c_str());
TEST_CHECK(selected.size() == 1);
if(selected.size() == 1)
TEST_CHECK(selected[0] == &(*ptr)[1]);
}
std::filesystem::remove_all(tmp_dir);
}
struct ExdevFixture
{
std::vector<std::pair<ToFromString*,std::string>> saved;
const fs::path old_mountpoint = cfg.mountpoint;
const u64 old_minfreespace = cfg.branches.minfreespace;
fs::path root;
fs::path first;
fs::path second;
fs::path source = "source/nested/file";
fs::path destination = "destination/nested/file";
bool ready = false;
ExdevFixture(const bool root_source_ = false)
{
for(ToFromString *option : std::vector<ToFromString*>{&cfg.branches,
&cfg.func.create,&cfg.func.symlink,
&cfg.func.getattr,&cfg.func.open,
&cfg.func.rename,&cfg.func.link,
&cfg.ignorepponrename,&cfg.allow_idmap,
&cfg.rename_exdev,&cfg.link_exdev,
&cfg.follow_symlinks})
saved.emplace_back(option,option->to_string());
char tmp_template[] = "/tmp/mergerfs-test-exdev-XXXXXX";
const auto tmp = ::mkdtemp(tmp_template);
TEST_CHECK(tmp != nullptr);
if(tmp == nullptr)
return;
root = tmp;
first = root / "first";
second = root / "second";
if(root_source_)
source = "file";
for(const auto &path : {first / source.parent_path(),
second / destination.parent_path()})
{
std::error_code ec;
std::filesystem::create_directories(path,ec);
TEST_CHECK(!ec);
if(ec)
return;
}
std::ofstream output(first / source);
output << "exdev payload";
output.close();
TEST_CHECK(!output.fail());
if(output.fail())
return;
cfg.branches.minfreespace = 0;
const int rv = cfg.branches.from_string(first.string() + ":" + second.string());
TEST_CHECK(rv == 0);
if(rv != 0)
return;
cfg.mountpoint = root / "pool";
cfg.func.create.from_string("epff");
cfg.func.symlink.from_string("epff");
cfg.func.getattr.from_string("ff");
cfg.func.open.from_string("ff");
cfg.func.rename.from_string("epall");
cfg.func.link.from_string("epall");
cfg.ignorepponrename = false;
cfg.allow_idmap = true;
cfg.follow_symlinks.from_string("never");
ready = true;
}
~ExdevFixture()
{
cfg.branches.minfreespace = old_minfreespace;
for(auto &option : saved)
option.first->from_string(option.second);
cfg.mountpoint = old_mountpoint;
if(!root.empty())
{
std::error_code ec;
std::filesystem::remove_all(root,ec);
TEST_CHECK(!ec);
}
}
fs::path staged() const
{
return fs::path(".mergerfs_rename_exdev") / source;
}
};
static
void
check_exdev_absent(const fs::path &path_)
{
struct stat st = {};
errno = 0;
TEST_CHECK(::lstat(path_.c_str(),&st) == -1);
TEST_CHECK(errno == ENOENT);
}
static
void
check_exdev_payload(const fs::path &path_,
const char *expected_ = "exdev payload")
{
std::ifstream input(path_);
TEST_CHECK(input.is_open());
std::stringstream data;
data << input.rdbuf();
TEST_CHECK(data.str() == expected_);
}
static
void
check_exdev_symlink(const fs::path &path_,
const fs::path &target_,
const struct stat &source_st_)
{
struct stat st = {};
const int rv = ::lstat(path_.c_str(),&st);
TEST_CHECK(rv == 0);
if(rv != 0)
return;
TEST_CHECK(S_ISLNK(st.st_mode));
TEST_CHECK(st.st_uid == source_st_.st_uid);
TEST_CHECK(st.st_gid == source_st_.st_gid);
std::error_code ec;
const auto target = std::filesystem::read_symlink(path_,ec);
TEST_CHECK(!ec);
TEST_CHECK(target == target_);
}
static
fuse_req_ctx_t
exdev_context(const unsigned invalid_fields_)
{
fuse_req_ctx_t ctx = {};
ctx.uid = (invalid_fields_ & 1) ? FUSE_INVALID_UIDGID : ::geteuid();
ctx.gid = (invalid_fields_ & 2) ? FUSE_INVALID_UIDGID : ::getegid();
ctx.pid = ::getpid();
return ctx;
}
static
void
test_rename_exdev_case(const char *mode_,
const bool root_source_,
const unsigned invalid_fields_,
const bool occupied_ = false,
const bool distinct_owner_ = false)
{
ExdevFixture fixture(root_source_);
if(!fixture.ready)
return;
TEST_CASE(mode_);
cfg.rename_exdev.from_string(mode_);
const auto ctx = exdev_context(invalid_fields_);
if(distinct_owner_)
{
TEST_CHECK(::chown((fixture.first / fixture.source).c_str(),12345,23456) == 0);
TEST_CHECK(::chown((fixture.second / fixture.destination.parent_path()).c_str(),0,34567) == 0);
TEST_CHECK(::chmod((fixture.second / fixture.destination.parent_path()).c_str(),02770) == 0);
}
struct stat source_st = {};
TEST_CHECK(::lstat((fixture.first / fixture.source).c_str(),&source_st) == 0);
check_exdev_absent(fixture.first / ".mergerfs_rename_exdev");
check_exdev_absent(fixture.second / fixture.source);
check_exdev_absent(fixture.first / fixture.destination.parent_path());
if(occupied_)
{
std::ofstream output(fixture.second / fixture.destination);
output << "existing destination";
}
const int rv = FUSE::rename(&ctx,fixture.source.c_str(),fixture.destination.c_str());
TEST_CHECK(rv == (occupied_ ? -EEXIST : 0));
if(occupied_)
{
check_exdev_payload(fixture.first / fixture.source);
check_exdev_payload(fixture.second / fixture.destination,"existing destination");
check_exdev_absent(fixture.first / fixture.staged());
struct stat restored = {};
TEST_CHECK(::lstat((fixture.first / fixture.source).c_str(),&restored) == 0);
TEST_CHECK(restored.st_ino == source_st.st_ino);
return;
}
if(rv != 0)
return;
check_exdev_absent(fixture.first / fixture.source);
check_exdev_absent(fixture.first / fixture.destination);
check_exdev_payload(fixture.first / fixture.staged());
struct stat staged_st = {};
TEST_CHECK(::lstat((fixture.first / fixture.staged()).c_str(),&staged_st) == 0);
TEST_CHECK(staged_st.st_ino == source_st.st_ino);
TEST_CHECK(staged_st.st_uid == source_st.st_uid);
TEST_CHECK(staged_st.st_gid == source_st.st_gid);
const fs::path expected = (std::string(mode_) == "rel-symlink") ?
fixture.staged().lexically_relative(fixture.destination.parent_path()) :
cfg.mountpoint / fixture.staged();
check_exdev_symlink(fixture.second / fixture.destination,expected,source_st);
}
static
void
test_link_exdev_case(const char *mode_,
const unsigned invalid_fields_,
const bool occupied_ = false,
const bool distinct_owner_ = false)
{
ExdevFixture fixture;
if(!fixture.ready)
return;
TEST_CASE(mode_);
cfg.link_exdev.from_string(mode_);
const auto ctx = exdev_context(invalid_fields_);
if(distinct_owner_)
{
TEST_CHECK(::chown((fixture.first / fixture.source).c_str(),12345,23456) == 0);
TEST_CHECK(::chown((fixture.second / fixture.destination.parent_path()).c_str(),0,34567) == 0);
TEST_CHECK(::chmod((fixture.second / fixture.destination.parent_path()).c_str(),02770) == 0);
}
struct stat source_st = {};
TEST_CHECK(::lstat((fixture.first / fixture.source).c_str(),&source_st) == 0);
check_exdev_absent(fixture.second / fixture.source);
check_exdev_absent(fixture.first / fixture.destination.parent_path());
if(occupied_)
{
std::ofstream output(fixture.second / fixture.destination);
output << "existing destination";
}
struct stat output_st = {};
fuse_timeouts_t timeouts = {};
const int rv = FUSE::link(&ctx,fixture.source.c_str(),fixture.destination.c_str(),
&output_st,&timeouts);
TEST_CHECK(rv == (occupied_ ? -EEXIST : 0));
check_exdev_payload(fixture.first / fixture.source);
check_exdev_absent(fixture.first / ".mergerfs_rename_exdev");
check_exdev_absent(fixture.first / fixture.destination);
if(occupied_)
{
check_exdev_payload(fixture.second / fixture.destination,"existing destination");
return;
}
if(rv != 0)
return;
TEST_CHECK(S_ISREG(output_st.st_mode));
TEST_CHECK(timeouts.attr == 0);
TEST_CHECK(timeouts.entry == 0);
fs::path expected;
if(std::string(mode_) == "rel-symlink")
expected = fixture.source.lexically_relative(fixture.destination.parent_path());
else if(std::string(mode_) == "abs-base-symlink")
expected = fixture.first / fixture.source;
else
expected = cfg.mountpoint / fixture.source;
check_exdev_symlink(fixture.second / fixture.destination,expected,source_st);
}
void
test_fuse_rename_exdev_relative_nested()
{
test_rename_exdev_case("rel-symlink",false,0);
}
void
test_fuse_rename_exdev_root_source()
{
for(const auto mode : {"rel-symlink","abs-symlink"})
test_rename_exdev_case(mode,true,0);
}
void
test_fuse_rename_exdev_invalid_context()
{
for(const auto mode : {"rel-symlink","abs-symlink"})
for(unsigned fields = 1; fields <= 3; ++fields)
test_rename_exdev_case(mode,false,fields);
}
void
test_fuse_link_exdev_variants()
{
for(const auto mode : {"rel-symlink","abs-base-symlink","abs-pool-symlink"})
test_link_exdev_case(mode,0);
}
void
test_fuse_link_exdev_invalid_context()
{
for(const auto mode : {"rel-symlink","abs-base-symlink","abs-pool-symlink"})
for(unsigned fields = 1; fields <= 3; ++fields)
test_link_exdev_case(mode,fields);
}
void
test_fuse_exdev_existing_destination()
{
for(const auto mode : {"rel-symlink","abs-symlink"})
test_rename_exdev_case(mode,false,3,true);
for(const auto mode : {"rel-symlink","abs-base-symlink","abs-pool-symlink"})
test_link_exdev_case(mode,3,true);
}
static
bool
exdev_distinct_ownership_available()
{
if(::geteuid() != 0)
return false;
char tmp_template[] = "/tmp/mergerfs-test-exdev-ownership-XXXXXX";
const int fd = ::mkstemp(tmp_template);
TEST_CHECK(fd >= 0);
if(fd < 0)
return false;
// Namespace root may lack the mappings or capabilities for these IDs.
// Probe outside production callbacks, in a child so credentials cannot leak.
const pid_t child = ::fork();
if(child == 0)
{
if((::fchown(fd,12345,23456) != 0) ||
(::fchown(fd,0,34567) != 0) ||
(::setregid(-1,23456) != 0) ||
(::setreuid(-1,12345) != 0) ||
(::setreuid(-1,0) != 0) ||
(::setregid(-1,0) != 0))
::_exit(77);
::_exit(0);
}
TEST_CHECK(child > 0);
int status = 0;
pid_t waited = -1;
if(child > 0)
{
do
waited = ::waitpid(child,&status,0);
while((waited < 0) && (errno == EINTR));
TEST_CHECK(waited == child);
if(waited == child)
TEST_CHECK(WIFEXITED(status));
}
TEST_CHECK(::close(fd) == 0);
TEST_CHECK(::unlink(tmp_template) == 0);
return (child > 0) && (waited == child) &&
WIFEXITED(status) && (WEXITSTATUS(status) == 0);
}
void
test_fuse_exdev_source_ownership()
{
// Run only when distinct IDs and credential switching are really available.
if(!exdev_distinct_ownership_available())
return;
for(const auto mode : {"rel-symlink","abs-symlink"})
for(const unsigned fields : {0u,3u})
test_rename_exdev_case(mode,false,fields,false,true);
for(const auto mode : {"rel-symlink","abs-base-symlink","abs-pool-symlink"})
for(const unsigned fields : {0u,3u})
test_link_exdev_case(mode,fields,false,true);
}
void
test_fuse_symlink_request_ownership()
{
if(!exdev_distinct_ownership_available())
return;
ExdevFixture fixture;
if(!fixture.ready)
return;
// Unlike internal EXDEV fallbacks, normal SYMLINK uses the valid request UID
// and lets the destination directory's setgid bit choose the native group.
TEST_CHECK(::chmod(fixture.root.c_str(),0755) == 0);
const auto parent = fixture.second / fixture.destination.parent_path();
TEST_CHECK(::chmod(fixture.second.c_str(),0755) == 0);
TEST_CHECK(::chmod((fixture.second / "destination").c_str(),0755) == 0);
TEST_CHECK(::chown(parent.c_str(),0,34567) == 0);
TEST_CHECK(::chmod(parent.c_str(),02777) == 0);
auto ctx = exdev_context(0);
ctx.uid = 12345;
ctx.gid = 23456;
struct stat output_st = {};
fuse_timeouts_t timeouts = {};
const int rv = FUSE::symlink(&ctx,"target",fixture.destination.c_str(),&output_st,&timeouts);
TEST_CHECK(rv == 0);
if(rv == 0)
{
struct stat expected = {};
expected.st_uid = ctx.uid;
expected.st_gid = 34567;
check_exdev_symlink(fixture.second / fixture.destination,"target",expected);
}
}
void void
test_fs_copyfile_basic() test_fs_copyfile_basic()
{ {
@ -4211,50 +3647,9 @@ test_rapidhash_withSeed_preserves_default_output()
} }
} }
void
test_clonepath_modes()
{
char tmp[] = "/tmp/mergerfs-clonepath-XXXXXX";
TEST_ASSERT(::mkdtemp(tmp) != NULL);
const std::filesystem::path root(tmp);
const auto src = root / "src";
const auto dst = root / "dst";
std::filesystem::create_directories(src / "d" / "child");
std::filesystem::create_directory(dst);
// Use a different group when privileged to verify actual inheritance.
const gid_t group = (::geteuid() == 0) ? 1 : ::getegid();
TEST_ASSERT(::chown((src / "d").c_str(),::geteuid(),group) == 0);
TEST_ASSERT(::chmod((src / "d").c_str(),02770) == 0);
TEST_ASSERT(::chmod((src / "d" / "child").c_str(),0770) == 0);
TEST_CHECK(fs::clonepath(src.string(),dst.string(),"d/child",true) == 0);
struct stat st;
TEST_ASSERT(::stat((dst / "d").c_str(),&st) == 0);
TEST_CHECK((st.st_mode & 07777) == 02770);
TEST_CHECK(st.st_gid == group);
TEST_ASSERT(::stat((dst / "d" / "child").c_str(),&st) == 0);
TEST_CHECK((st.st_mode & 07777) == 0770);
const auto file = dst / "d" / "file";
const int fd = ::open(file.c_str(),O_CREAT|O_EXCL|O_WRONLY,0600);
TEST_ASSERT(fd >= 0);
TEST_ASSERT(::fstat(fd,&st) == 0);
TEST_CHECK(st.st_gid == group);
::close(fd);
// Existing destination directories must remain untouched.
TEST_ASSERT(::chmod((dst / "d").c_str(),0700) == 0);
TEST_CHECK(fs::clonepath(src.string(),dst.string(),"d",true) == 0);
TEST_ASSERT(::stat((dst / "d").c_str(),&st) == 0);
TEST_CHECK((st.st_mode & 07777) == 0700);
std::filesystem::remove_all(root);
}
TEST_LIST = TEST_LIST =
{ {
{"nop",test_nop}, {"nop",test_nop},
{"boost_concurrent_flat_map_empty_lookup",test_boost_concurrent_flat_map_empty_lookup},
{"config_bool",test_config_bool}, {"config_bool",test_config_bool},
{"config_uint64",test_config_uint64}, {"config_uint64",test_config_uint64},
{"config_int",test_config_int}, {"config_int",test_config_int},
@ -4262,11 +3657,6 @@ TEST_LIST =
{"hashset_put_and_size",test_hashset_put_and_size}, {"hashset_put_and_size",test_hashset_put_and_size},
{"rapidhash_withSeed_preserves_default_output",test_rapidhash_withSeed_preserves_default_output}, {"rapidhash_withSeed_preserves_default_output",test_rapidhash_withSeed_preserves_default_output},
{"config_branches",test_config_branches}, {"config_branches",test_config_branches},
{"msppfrd_create_rejected_relative",test_msppfrd_create_rejected_relative},
{"mspmfs_create_rejected_relative",test_mspmfs_create_rejected_relative},
{"msplfs_create_rejected_relative",test_msplfs_create_rejected_relative},
{"msplus_create_rejected_relative",test_msplus_create_rejected_relative},
{"msp_create_relative_fallback",test_msp_create_relative_fallback},
{"branch_default_ctor_mode",test_branch_default_ctor_mode}, {"branch_default_ctor_mode",test_branch_default_ctor_mode},
{"branch_to_string_modes",test_branch_to_string_modes}, {"branch_to_string_modes",test_branch_to_string_modes},
{"branch_to_string_with_minfreespace",test_branch_to_string_with_minfreespace}, {"branch_to_string_with_minfreespace",test_branch_to_string_with_minfreespace},
@ -4362,14 +3752,6 @@ TEST_LIST =
{"config_is_cmd_xattr",test_config_is_cmd_xattr}, {"config_is_cmd_xattr",test_config_is_cmd_xattr},
{"config_prune_ctrl_xattr",test_config_prune_ctrl_xattr}, {"config_prune_ctrl_xattr",test_config_prune_ctrl_xattr},
{"config_prune_cmd_xattr",test_config_prune_cmd_xattr}, {"config_prune_cmd_xattr",test_config_prune_cmd_xattr},
{"fuse_rename_exdev_relative_nested",test_fuse_rename_exdev_relative_nested},
{"fuse_rename_exdev_root_source",test_fuse_rename_exdev_root_source},
{"fuse_rename_exdev_invalid_context",test_fuse_rename_exdev_invalid_context},
{"fuse_link_exdev_variants",test_fuse_link_exdev_variants},
{"fuse_link_exdev_invalid_context",test_fuse_link_exdev_invalid_context},
{"fuse_exdev_existing_destination",test_fuse_exdev_existing_destination},
{"fuse_exdev_source_ownership",test_fuse_exdev_source_ownership},
{"fuse_symlink_request_ownership",test_fuse_symlink_request_ownership},
{"fs_copyfile_basic",test_fs_copyfile_basic}, {"fs_copyfile_basic",test_fs_copyfile_basic},
{"fs_copyfile_source_changes_cleanup_tmpfiles",test_fs_copyfile_source_changes_cleanup_tmpfiles}, {"fs_copyfile_source_changes_cleanup_tmpfiles",test_fs_copyfile_source_changes_cleanup_tmpfiles},
{"str_eq_nullptr",test_str_eq_nullptr}, {"str_eq_nullptr",test_str_eq_nullptr},
@ -4446,6 +3828,5 @@ TEST_LIST =
{"tp_heavy_repeated_construct_destroy",test_tp_heavy_repeated_construct_destroy}, {"tp_heavy_repeated_construct_destroy",test_tp_heavy_repeated_construct_destroy},
{"tp_heavy_enqueue_task_mixed_outcomes",test_tp_heavy_enqueue_task_mixed_outcomes}, {"tp_heavy_enqueue_task_mixed_outcomes",test_tp_heavy_enqueue_task_mixed_outcomes},
{"tp_heavy_add_remove_churn_under_enqueue",test_tp_heavy_add_remove_churn_under_enqueue}, {"tp_heavy_add_remove_churn_under_enqueue",test_tp_heavy_add_remove_churn_under_enqueue},
{"clonepath_modes",test_clonepath_modes},
{NULL,NULL} {NULL,NULL}
}; };

View file

@ -949,14 +949,13 @@ Group* dummy_groups()
* we are not allocating any dynamic memory and yet lookup can be implemented * we are not allocating any dynamic memory and yet lookup can be implemented
* without checking for groups==nullptr. This space won't ever be used for * without checking for groups==nullptr. This space won't ever be used for
* insertion as the container's capacity is precisely zero. * insertion as the container's capacity is precisely zero.
* Keep the storage writable: atomic loads on ARMv5 can write back through
* compare-and-swap. constinit preserves static initialization without const.
*/ */
static constinit typename Group::dummy_group_type static constexpr typename Group::dummy_group_type
storage[Size]={typename Group::dummy_group_type(),}; storage[Size]={typename Group::dummy_group_type(),};
return reinterpret_cast<Group*>(storage); return reinterpret_cast<Group*>(
const_cast<typename Group::dummy_group_type*>(storage));
} }
template< template<

View file

@ -32,6 +32,9 @@ UTILS :=
INSTALLUTILS := INSTALLUTILS :=
endif endif
ifeq ($(NDEBUG),1)
OPT_FLAGS := -O2 -DNDEBUG
else
ifdef SANITIZE ifdef SANITIZE
ifeq ($(SANITIZE),1) ifeq ($(SANITIZE),1)
override SANITIZE := -fsanitize=address,undefined,leak override SANITIZE := -fsanitize=address,undefined,leak
@ -39,22 +42,15 @@ else ifeq ($(filter -fsanitize=%,$(SANITIZE)),)
override SANITIZE := -fsanitize=$(SANITIZE) override SANITIZE := -fsanitize=$(SANITIZE)
endif endif
endif endif
OPT_FLAGS := -O0 \
COMMON_OPT_FLAGS += \ -g \
-fno-omit-frame-pointer \
$(SANITIZE) \
-fstack-protector-strong \ -fstack-protector-strong \
-Wextra \ -Wextra \
-Wno-unused-parameter -Werror \
-Wno-unused-parameter \
DEBUG_OPT_FLAGS += \ -DDEBUG
-O0 \
-g3 \
-fno-omit-frame-pointer \
$(SANITIZE)
ifdef RELEASE
OPT_FLAGS := -O3 $(COMMON_OPT_FLAGS)
else
OPT_FLAGS ?= $(DEBUG_OPT_FLAGS) $(COMMON_OPT_FLAGS)
endif endif
ifeq ($(LTO),1) ifeq ($(LTO),1)
@ -114,7 +110,7 @@ CXXFLAGS ?= \
-Wall \ -Wall \
-pipe -pipe
override CXXFLAGS += \ override CXXFLAGS += \
-std=c++20 \ -std=c++17 \
-MMD \ -MMD \
-MP -MP
FUSERMOUNT_DIR := $(BINDIR) FUSERMOUNT_DIR := $(BINDIR)
@ -155,10 +151,10 @@ $(BUILDDIR)/mount.mergerfs: $(BUILDDIR)/libfuse.a util/mount.mergerfs.cpp
mount.mergerfs: $(BUILDDIR)/mount.mergerfs mount.mergerfs: $(BUILDDIR)/mount.mergerfs
$(BUILDDIR)/.objs/%.c.o: lib/%.c | $(BUILDDIR)/stamp $(BUILDDIR)/.objs/%.c.o: lib/%.c | $(BUILDDIR)/stamp
$(CC) $(CFLAGS) $(CPPFLAGS) $(FUSE_FLAGS) -c $< -o $@ $(CC) $(CFLAGS) $(FUSE_FLAGS) -c $< -o $@
$(BUILDDIR)/.objs/%.cpp.o: lib/%.cpp | $(BUILDDIR)/stamp $(BUILDDIR)/.objs/%.cpp.o: lib/%.cpp | $(BUILDDIR)/stamp
$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(FUSE_FLAGS) -c $< -o $@ $(CXX) $(CXXFLAGS) $(FUSE_FLAGS) -c $< -o $@
.PHONY: clean .PHONY: clean
clean: clean:
@ -180,10 +176,6 @@ install-utils: mergerfs-fusermount mount.mergerfs strip
install: $(INSTALLUTILS) install: $(INSTALLUTILS)
.PHONY: release
release:
$(MAKE) RELEASE=1 NDEBUG=1 CPPFLAGS="$(CPPFLAGS) -DNDEBUG" all
.PHONY: objects strip utils install install-utils .PHONY: objects strip utils install install-utils
-include $(DEPS) -include $(DEPS)

View file

@ -171,18 +171,6 @@ struct fuse_operations
int (*ftruncate)(const fuse_req_ctx_t *, int (*ftruncate)(const fuse_req_ctx_t *,
const uint64_t, const uint64_t,
off_t); off_t);
// libfuse calls the fh based ops (fgetattr, statx_fh, fchmod,
// fchown, ftruncate, futimens) with fh=0 when the node has no path,
// so the filesystem can use a file it has open for ctx->nodeid.
// With none the node was removed (unlink, rmdir, rename over it)
// while the kernel still held it: a dirfd, a cwd, an O_PATH fd, or
// a dentry resolved just before the removal. Return ENOENT, not
// EBADF, as the caller may not have used a descriptor at all: the
// kernel sends GETATTR in permission checks of path walks too.
// ENOENT is what a local filesystem gives *at() calls in a removed
// directory, and what rm -f ignores. ESTALE would make the kernel
// redo the lookup, but a call through a dirfd or cwd of a removed
// directory meets the same node again and gets ESTALE. See #1693.
int (*fgetattr)(const fuse_req_ctx_t *, int (*fgetattr)(const fuse_req_ctx_t *,
const uint64_t, const uint64_t,
struct stat *, struct stat *,

View file

@ -5,7 +5,6 @@
#include <climits> #include <climits>
#include <cstdio> #include <cstdio>
#include <memory> #include <memory>
#include <shared_mutex>
#include <string> #include <string>
#define FUSE_CFG_INVALID_ID -1 #define FUSE_CFG_INVALID_ID -1
@ -34,7 +33,6 @@ struct fuse_cfg_t
std::shared_ptr<std::string> log_filepath() const; std::shared_ptr<std::string> log_filepath() const;
void log_filepath(const std::string &); void log_filepath(const std::string &);
private: private:
mutable std::shared_mutex _log_mutex;
std::shared_ptr<FILE> _log_file = sp<FILE>(stderr,[](FILE*){}); std::shared_ptr<FILE> _log_file = sp<FILE>(stderr,[](FILE*){});
std::shared_ptr<std::string> _log_filepath = sp<std::string>(); std::shared_ptr<std::string> _log_filepath = sp<std::string>();

View file

@ -10,7 +10,6 @@ struct fuse_req_t
{ {
fuse_req_ctx_t ctx; fuse_req_ctx_t ctx;
struct fuse_session *se; struct fuse_session *se;
int fd;
fuse_conn_info_t conn; fuse_conn_info_t conn;
unsigned int ioctl_64bit : 1; unsigned int ioctl_64bit : 1;
}; };

View file

@ -1191,7 +1191,7 @@ fuse_syslog_fuse_init_in(const struct fuse_init_in *arg_)
output.pop_back(); output.pop_back();
output += ");"; output += ");";
SysLog::info("{}",output); SysLog::info(output);
} }
void void
@ -1239,7 +1239,7 @@ fuse_syslog_fuse_init_out(const struct fuse_init_out *arg_)
output.pop_back(); output.pop_back();
output += ");"; output += ");";
SysLog::info("{}",output); SysLog::info(output);
} }

View file

@ -1064,29 +1064,6 @@ free_path_wrlock(uint64_t nodeid,
free(path); free(path);
} }
static
void
update_stat(node_t *node_,
const struct stat *stnew_)
{
uint32_t crc32b;
// This function can only invalidate an existing fingerprint; it
// never arms a new one. Arming (writing a non-zero CRC into
// state_crc32b) happens exclusively in open_auto_cache(), which is
// the single point that decides a file's page cache is worth
// retaining across opens. If stat_crc32b is 0 here the cache is
// already considered invalid and we have nothing to compare
// against.
if(node_->stat_crc32b == 0)
return;
crc32b = stat_crc32b(stnew_);
if(crc32b != node_->stat_crc32b)
node_->stat_crc32b = 0;
}
static static
void void
free_path(uint64_t nodeid, free_path(uint64_t nodeid,
@ -1096,59 +1073,6 @@ free_path(uint64_t nodeid,
free_path_wrlock(nodeid,NULL,path); free_path_wrlock(nodeid,NULL,path);
} }
static
node_t*
free_path_and_inc_open(u64 free_nodeid_,
char *path_,
u64 inc_open_ino_,
bool remember_too_)
{
node_t *node;
mutex_lock(f.lock);
unlock_path(free_nodeid_,NULL,NULL);
node = get_node(inc_open_ino_);
if(node)
{
if(remember_too_ && remember_nodes())
remember_node(node);
node->open_count++;
}
if(f.lockq)
wake_up_queued();
mutex_unlock(f.lock);
free(path_);
return node;
}
static
bool
free_path_and_update_stat(u64 nodeid_,
char *path_,
const struct stat *stnew_)
{
bool ok;
node_t *node;
mutex_lock(f.lock);
unlock_path(nodeid_,NULL,NULL);
node = get_node(nodeid_);
ok = (node != NULL);
if(ok)
update_stat(node,stnew_);
if(f.lockq)
wake_up_queued();
mutex_unlock(f.lock);
free(path_);
return ok;
}
static static
void void
free_path2(uint64_t nodeid1, free_path2(uint64_t nodeid1,
@ -1284,65 +1208,52 @@ node_open(const node_t *node_)
return ((node_ != NULL) && (node_->open_count > 0)); return ((node_ != NULL) && (node_->open_count > 0));
} }
static
void
update_stat(node_t *node_,
const struct stat *stnew_)
{
uint32_t crc32b;
// This function can only invalidate an existing fingerprint; it
// never arms a new one. Arming (writing a non-zero CRC into
// state_crc32b) happens exclusively in open_auto_cache(), which is
// the single point that decides a file's page cache is worth
// retaining across opens. If stat_crc32b is 0 here the cache is
// already considered invalid and we have nothing to compare
// against.
if(node_->stat_crc32b == 0)
return;
crc32b = stat_crc32b(stnew_);
if(crc32b != node_->stat_crc32b)
node_->stat_crc32b = 0;
}
static static
int int
set_path_info(uint64_t nodeid_, set_path_info(uint64_t nodeid,
const char *name_, const char *name,
struct fuse_entry_param *e_, struct fuse_entry_param *e,
bool remember_ = true) bool remember = true)
{ {
node_t *node; node_t *node;
node = find_node(nodeid,name,remember);
if(node == NULL)
return -ENOMEM;
e->ino = node->nodeid;
e->generation = ((e->ino == FUSE_ROOT_ID) ? 0 : f.nodeid_gen.generation);
mutex_lock(f.lock); mutex_lock(f.lock);
update_stat(node,&e->attr);
if(!name_)
{
node = get_node(nodeid_);
if(node == NULL)
goto out_unlock;
}
else
{
node = lookup_node(nodeid_,name_);
}
if(node == NULL)
{
node = node_alloc();
if(node == NULL)
goto out_unlock;
node->nodeid = generate_nodeid(&f.nodeid_gen);
if(remember_ && remember_nodes())
remember_node(node);
if(hash_name(node,nodeid_,name_) == -1)
{
free_node(node);
node = NULL;
goto out_unlock;
}
hash_id(node);
}
inc_nlookup(node);
e_->ino = node->nodeid;
e_->generation = ((e_->ino == FUSE_ROOT_ID) ? 0 : f.nodeid_gen.generation);
update_stat(node,&e_->attr);
mutex_unlock(f.lock); mutex_unlock(f.lock);
set_stat(e_->ino,&e_->attr); set_stat(e->ino,&e->attr);
return 0; return 0;
out_unlock:
mutex_unlock(f.lock);
return -ENOMEM;
} }
/* /*
@ -1563,37 +1474,26 @@ fuse_lib_getattr(fuse_req_t *req_,
if(!err) if(!err)
{ {
bool node_ok = true;
if(fusepath != NULL) if(fusepath != NULL)
{
err = f.ops.getattr(&req_->ctx,&fusepath[1],&buf,&timeouts); err = f.ops.getattr(&req_->ctx,&fusepath[1],&buf,&timeouts);
if(!err)
node_ok = free_path_and_update_stat(hdr_->nodeid,fusepath,&buf);
else else
err = f.ops.fgetattr(&req_->ctx,fh,&buf,&timeouts);
free_path(hdr_->nodeid,fusepath); free_path(hdr_->nodeid,fusepath);
} }
else
{
err = f.ops.fgetattr(&req_->ctx,fh,&buf,&timeouts);
if(!err) if(!err)
{
{ {
mutex_lockguard(f.lock); mutex_lockguard(f.lock);
node = get_node(hdr_->nodeid); node = get_node(hdr_->nodeid);
node_ok = (node != NULL); if(node == NULL)
if(node_ok)
update_stat(node,&buf);
}
}
if(!err && !node_ok)
{ {
fuse_reply_err(req_,ESTALE); fuse_reply_err(req_,ESTALE);
return; return;
} }
update_stat(node,&buf);
} }
if(!err)
{
set_stat(hdr_->nodeid,&buf); set_stat(hdr_->nodeid,&buf);
fuse_reply_attr(req_,&buf,timeouts.attr); fuse_reply_attr(req_,&buf,timeouts.attr);
} }
@ -1763,32 +1663,15 @@ fuse_lib_setattr(fuse_req_t *req_,
f.ops.getattr(&req_->ctx,&fusepath[1],&stbuf,&timeouts) : f.ops.getattr(&req_->ctx,&fusepath[1],&stbuf,&timeouts) :
f.ops.fgetattr(&req_->ctx,fh,&stbuf,&timeouts)); f.ops.fgetattr(&req_->ctx,fh,&stbuf,&timeouts));
bool stat_updated = false;
if(!err && (fusepath != NULL))
{
node_t *node;
mutex_lock(f.lock);
unlock_path(hdr_->nodeid,NULL,NULL);
node = get_node(hdr_->nodeid);
if(node)
update_stat(node,&stbuf);
if(f.lockq)
wake_up_queued();
mutex_unlock(f.lock);
free(fusepath);
stat_updated = true;
}
else
{
free_path(hdr_->nodeid,fusepath); free_path(hdr_->nodeid,fusepath);
} }
if(!err) if(!err)
{ {
if(!stat_updated)
{ {
node_t *node; node_t *node;
mutex_lockguard(f.lock); mutex_lockguard(f.lock);
node = get_node(hdr_->nodeid); node = get_node(hdr_->nodeid);
if(node) if(node)
update_stat(node,&stbuf); update_stat(node,&stbuf);
@ -1801,13 +1684,8 @@ fuse_lib_setattr(fuse_req_t *req_,
{ {
fuse_reply_err(req_,err); fuse_reply_err(req_,err);
} }
return;
} }
fuse_reply_err(req_,err);
}
static static
void void
fuse_lib_access(fuse_req_t *req_, fuse_lib_access(fuse_req_t *req_,
@ -2211,8 +2089,15 @@ fuse_lib_create(fuse_req_t *req_,
if(!err) if(!err)
{ {
free_path_and_inc_open(hdr_->nodeid,fusepath,e.ino,true); mutex_lock(f.lock);
fusepath = NULL; node_t *node = get_node(e.ino);
if(node)
{
if(remember_nodes())
remember_node(node);
node->open_count++;
}
mutex_unlock(f.lock);
if(fuse_reply_create(req_,&e,&ffi) == -ENOENT) if(fuse_reply_create(req_,&e,&ffi) == -ENOENT)
{ {
@ -2311,9 +2196,11 @@ fuse_lib_open(fuse_req_t *req_,
if(!err) if(!err)
{ {
free_path_and_inc_open(hdr_->nodeid,fusepath,hdr_->nodeid,false); mutex_lock(f.lock);
fusepath = NULL; node_t *node = get_node(hdr_->nodeid);
if(node)
node->open_count++;
mutex_unlock(f.lock);
/* The open syscall was interrupted,so it must be cancelled */ /* The open syscall was interrupted,so it must be cancelled */
if(fuse_reply_open(req_,&ffi) == -ENOENT) if(fuse_reply_open(req_,&ffi) == -ENOENT)
fuse_do_release(&req_->ctx,hdr_->nodeid,&ffi); fuse_do_release(&req_->ctx,hdr_->nodeid,&ffi);
@ -2656,11 +2543,7 @@ fuse_lib_releasedir(fuse_req_t *req_,
f.ops.releasedir(&req_->ctx, f.ops.releasedir(&req_->ctx,
&ffi); &ffi);
// Acquire/release barrier: not a real critical section. A /* Done to keep race condition between last readdir reply and the unlock */
// concurrent readdir may still hold dh->lock at this point. This
// lock+unlock pair blocks until the last readdir drops the lock
// guaranteeing that the subsequent destroy/free sees no in-flight
// readdir accessing dh->d. Do NOT remove.
mutex_lock(dh->lock); mutex_lock(dh->lock);
mutex_unlock(dh->lock); mutex_unlock(dh->lock);
mutex_destroy(dh->lock); mutex_destroy(dh->lock);
@ -3014,7 +2897,7 @@ fuse_lib_tmpfile(fuse_req_t *req_,
req_->ctx.nodeid = new_nodeid; req_->ctx.nodeid = new_nodeid;
} }
err = get_path(hdr_->nodeid,&fusepath); err = get_path_name(hdr_->nodeid,name,&fusepath);
if(!err) if(!err)
{ {
err = f.ops.tmpfile(&req_->ctx, err = f.ops.tmpfile(&req_->ctx,
@ -3041,8 +2924,15 @@ fuse_lib_tmpfile(fuse_req_t *req_,
if(!err) if(!err)
{ {
free_path_and_inc_open(hdr_->nodeid,fusepath,e.ino,true); mutex_lock(f.lock);
fusepath = NULL; node_t *node = get_node(e.ino);
if(node)
{
if(remember_nodes())
remember_node(node);
node->open_count++;
}
mutex_unlock(f.lock);
if(fuse_reply_create(req_,&e,&ffi) == -ENOENT) if(fuse_reply_create(req_,&e,&ffi) == -ENOENT)
{ {

View file

@ -1,7 +1,5 @@
#include "fuse_cfg.hpp" #include "fuse_cfg.hpp"
#include <mutex>
fuse_cfg_t fuse_cfg; fuse_cfg_t fuse_cfg;
bool bool
@ -25,32 +23,24 @@ fuse_cfg_t::valid_umask() const
std::shared_ptr<FILE> std::shared_ptr<FILE>
fuse_cfg_t::log_file() const fuse_cfg_t::log_file() const
{ {
std::shared_lock<std::shared_mutex> lk(_log_mutex); return std::atomic_load(&_log_file);
return _log_file;
} }
void void
fuse_cfg_t::log_file(std::shared_ptr<FILE> f_) fuse_cfg_t::log_file(std::shared_ptr<FILE> f_)
{ {
std::unique_lock<std::shared_mutex> lk(_log_mutex); std::atomic_store(&_log_file, f_);
_log_file = std::move(f_);
} }
std::shared_ptr<std::string> std::shared_ptr<std::string>
fuse_cfg_t::log_filepath() const fuse_cfg_t::log_filepath() const
{ {
std::shared_lock<std::shared_mutex> lk(_log_mutex); return std::atomic_load(&_log_filepath);
return _log_filepath;
} }
void void
fuse_cfg_t::log_filepath(const std::string &s_) fuse_cfg_t::log_filepath(const std::string &s_)
{ {
auto filepath = std::make_shared<std::string>(s_); std::atomic_store(&_log_filepath,
std::unique_lock<std::shared_mutex> lk(_log_mutex); std::make_shared<std::string>(s_));
_log_filepath = std::move(filepath);
} }

View file

@ -15,7 +15,6 @@
#include "extern_c.h" #include "extern_c.h"
#include <atomic> #include <atomic>
#include <vector>
/* Simplified fuse_session - fields inlined from former fuse_chan /* Simplified fuse_session - fields inlined from former fuse_chan
* Since mergerfs only supports one mount, we collapse the hierarchy: * Since mergerfs only supports one mount, we collapse the hierarchy:
@ -25,11 +24,9 @@
struct fuse_session struct fuse_session
{ {
int (*receive_buf)(struct fuse_session *se, int (*receive_buf)(struct fuse_session *se,
int fd,
fuse_msgbuf_t *msgbuf); fuse_msgbuf_t *msgbuf);
void (*process_buf)(struct fuse_session *se, void (*process_buf)(struct fuse_session *se,
int fd,
const fuse_msgbuf_t *msgbuf); const fuse_msgbuf_t *msgbuf);
void (*destroy)(void *data); void (*destroy)(void *data);
@ -40,8 +37,6 @@ struct fuse_session
/* Formerly in fuse_chan - inlined for single-mount simplicity */ /* Formerly in fuse_chan - inlined for single-mount simplicity */
int fd; /* /dev/fuse file descriptor */ int fd; /* /dev/fuse file descriptor */
size_t bufsize; /* Buffer size for I/O operations */ size_t bufsize; /* Buffer size for I/O operations */
std::vector<int> clone_fds; /* cloned /dev/fuse fds for read workers */
}; };
struct fuse_notify_req struct fuse_notify_req
@ -55,12 +50,6 @@ struct fuse_notify_req
struct fuse_notify_req *prev; struct fuse_notify_req *prev;
}; };
bool fuse_session_setup_read_fds(struct fuse_session *se,
int read_thread_count);
int fuse_session_read_fd(struct fuse_session *se,
int index);
EXTERN_C_BEGIN EXTERN_C_BEGIN

View file

@ -11,6 +11,7 @@
#include "maintenance_thread.hpp" #include "maintenance_thread.hpp"
#include "fuse_i.hpp" #include "fuse_i.hpp"
#include "fuse_kernel.h"
#include "fuse_lowlevel.h" #include "fuse_lowlevel.h"
#include "fuse_cfg.hpp" #include "fuse_cfg.hpp"
@ -66,16 +67,13 @@ _nproc()
struct AsyncWorker struct AsyncWorker
{ {
fuse_session *_se; fuse_session *_se;
int _fd;
sem_t *_finished; sem_t *_finished;
std::shared_ptr<ThreadPool> _process_tp; std::shared_ptr<ThreadPool> _process_tp;
AsyncWorker(fuse_session *se_, AsyncWorker(fuse_session *se_,
int fd_,
sem_t *finished_, sem_t *finished_,
std::shared_ptr<ThreadPool> process_tp_) std::shared_ptr<ThreadPool> process_tp_)
: _se(se_), : _se(se_),
_fd(fd_),
_finished(finished_), _finished(finished_),
_process_tp(process_tp_) _process_tp(process_tp_)
{ {
@ -85,12 +83,8 @@ struct AsyncWorker
void void
operator()() const operator()() const
{ {
// Set exited before waking the main loop, which rechecks it. DEFER{ fuse_session_exit(_se); };
DEFER DEFER{ sem_post(_finished); };
{
fuse_session_exit(_se);
sem_post(_finished);
};
ThreadPool::PToken ptok(_process_tp->ptoken()); ThreadPool::PToken ptok(_process_tp->ptoken());
while(!fuse_session_exited(_se)) while(!fuse_session_exited(_se))
@ -108,7 +102,7 @@ struct AsyncWorker
while(true) while(true)
{ {
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
rv = _se->receive_buf(_se,_fd,msgbuf); rv = _se->receive_buf(_se,msgbuf);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
if(rv > 0) if(rv > 0)
@ -124,9 +118,9 @@ struct AsyncWorker
} }
_process_tp->enqueue_work(ptok, _process_tp->enqueue_work(ptok,
[se = _se,fd = _fd,msgbuf]() [=]()
{ {
se->process_buf(se,fd,msgbuf); _se->process_buf(_se,msgbuf);
msgbuf_free(msgbuf); msgbuf_free(msgbuf);
}); });
} }
@ -136,15 +130,12 @@ struct AsyncWorker
struct SyncWorker struct SyncWorker
{ {
fuse_session *_se; fuse_session *_se;
int _fd;
sem_t *_finished; sem_t *_finished;
SyncWorker(fuse_session *se_, SyncWorker(fuse_session *se_,
int fd_,
sem_t *finished_) sem_t *finished_)
: _se(se_), : _se(se_),
_fd(fd_),
_finished(finished_) _finished(finished_)
{ {
} }
@ -153,12 +144,8 @@ struct SyncWorker
void void
operator()() const operator()() const
{ {
// Set exited before waking the main loop, which rechecks it. DEFER{ fuse_session_exit(_se); };
DEFER DEFER{ sem_post(_finished); };
{
fuse_session_exit(_se);
sem_post(_finished);
};
while(!fuse_session_exited(_se)) while(!fuse_session_exited(_se))
{ {
@ -175,7 +162,7 @@ struct SyncWorker
while(true) while(true)
{ {
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
rv = _se->receive_buf(_se,_fd,msgbuf); rv = _se->receive_buf(_se,msgbuf);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
if(rv > 0) if(rv > 0)
break; break;
@ -189,7 +176,7 @@ struct SyncWorker
return ::_print_error(rv); return ::_print_error(rv);
} }
_se->process_buf(_se,_fd,msgbuf); _se->process_buf(_se,msgbuf);
msgbuf_free(msgbuf); msgbuf_free(msgbuf);
} }
@ -268,19 +255,16 @@ fuse_session_loop_mt(struct fuse_session *se_,
const std::string pin_threads_type_) const std::string pin_threads_type_)
{ {
sem_t finished; sem_t finished;
bool cloned_read_fds;
int read_thread_count; int read_thread_count;
int process_thread_count; int process_thread_count;
int process_thread_queue_depth; int process_thread_queue_depth;
std::vector<pthread_t> read_threads; std::vector<pthread_t> read_threads;
std::vector<pthread_t> process_threads; std::vector<pthread_t> process_threads;
sem_init(&finished,0,0);
DEFER{ sem_destroy(&finished); };
std::unique_ptr<ThreadPool> read_tp; std::unique_ptr<ThreadPool> read_tp;
std::shared_ptr<ThreadPool> process_tp; std::shared_ptr<ThreadPool> process_tp;
sem_init(&finished,0,0);
read_thread_count = raw_read_thread_count_; read_thread_count = raw_read_thread_count_;
process_thread_count = raw_process_thread_count_; process_thread_count = raw_process_thread_count_;
process_thread_queue_depth = raw_process_thread_queue_depth_; process_thread_queue_depth = raw_process_thread_queue_depth_;
@ -293,25 +277,18 @@ fuse_session_loop_mt(struct fuse_session *se_,
process_thread_queue_depth, process_thread_queue_depth,
"fuse.process"); "fuse.process");
cloned_read_fds = fuse_session_setup_read_fds(se_,read_thread_count);
read_tp = std::make_unique<ThreadPool>(read_thread_count, read_tp = std::make_unique<ThreadPool>(read_thread_count,
read_thread_count, read_thread_count,
"fuse.read"); "fuse.read");
if(process_tp) if(process_tp)
{ {
for(auto i = 0; i < read_thread_count; i++) for(auto i = 0; i < read_thread_count; i++)
read_tp->enqueue_work(AsyncWorker(se_, read_tp->enqueue_work(AsyncWorker(se_,&finished,process_tp));
fuse_session_read_fd(se_,i),
&finished,
process_tp));
} }
else else
{ {
for(auto i = 0; i < read_thread_count; i++) for(auto i = 0; i < read_thread_count; i++)
read_tp->enqueue_work(SyncWorker(se_, read_tp->enqueue_work(SyncWorker(se_,&finished));
fuse_session_read_fd(se_,i),
&finished));
} }
if(read_tp) if(read_tp)
@ -324,12 +301,10 @@ fuse_session_loop_mt(struct fuse_session *se_,
SysLog::info("read-thread-count={}; " SysLog::info("read-thread-count={}; "
"process-thread-count={}; " "process-thread-count={}; "
"process-thread-queue-depth={}; " "process-thread-queue-depth={}; "
"fuse-dev-ioc-clone={}; "
"pin-threads={};", "pin-threads={};",
read_thread_count, read_thread_count,
process_thread_count, process_thread_count,
process_thread_queue_depth, process_thread_queue_depth,
cloned_read_fds,
pin_threads_type_); pin_threads_type_);
while(!fuse_session_exited(se_)) while(!fuse_session_exited(se_))
@ -338,8 +313,7 @@ fuse_session_loop_mt(struct fuse_session *se_,
for(auto t : read_threads) for(auto t : read_threads)
pthread_cancel(t); pthread_cancel(t);
read_tp.reset(); sem_destroy(&finished);
process_tp.reset();
return 0; return 0;
} }

View file

@ -103,7 +103,7 @@ iov_length(const struct iovec *iov,
static static
int int
fuse_send_msg(const int fd_, fuse_send_msg(struct fuse_session *se,
struct iovec *iov, struct iovec *iov,
int count) int count)
{ {
@ -112,7 +112,7 @@ fuse_send_msg(const int fd_,
out->len = iov_length(iov, count); out->len = iov_length(iov, count);
rv = writev(fd_,iov,count); rv = writev(se->fd,iov,count);
if(rv == -1) if(rv == -1)
return -errno; return -errno;
@ -144,7 +144,7 @@ fuse_send_reply_iov_nofree(fuse_req_t *req,
iov[0].iov_base = &out; iov[0].iov_base = &out;
iov[0].iov_len = sizeof(struct fuse_out_header); iov[0].iov_len = sizeof(struct fuse_out_header);
return fuse_send_msg(req->fd, iov, count); return fuse_send_msg(req->se, iov, count);
} }
static static
@ -440,7 +440,7 @@ fuse_reply_data(fuse_req_t *req,
if(fuse_cfg.debug) if(fuse_cfg.debug)
fuse_debug_data_out(req->ctx.unique,bufsize_); fuse_debug_data_out(req->ctx.unique,bufsize_);
res = fuse_send_msg(req->fd,iov,2); res = fuse_send_msg(req->se,iov,2);
fuse_req_free(req); fuse_req_free(req);
return res; return res;
@ -1310,7 +1310,7 @@ send_notify_iov(struct fuse_session *se,
iov[0].iov_base = &out; iov[0].iov_base = &out;
iov[0].iov_len = sizeof(struct fuse_out_header); iov[0].iov_len = sizeof(struct fuse_out_header);
return fuse_send_msg(se->fd, iov, count); return fuse_send_msg(se, iov, count);
} }
int int
@ -1558,7 +1558,7 @@ fuse_ll_destroy(void *data)
static static
void void
fuse_send_errno(const int fd_, fuse_send_errno(struct fuse_session *se_,
const int errno_, const int errno_,
const uint64_t unique_id_) const uint64_t unique_id_)
{ {
@ -1574,26 +1574,25 @@ fuse_send_errno(const int fd_,
if(fuse_cfg.debug) if(fuse_cfg.debug)
fuse_debug_out_header(&out); fuse_debug_out_header(&out);
fuse_send_msg(fd_,&iov,1); fuse_send_msg(se_,&iov,1);
} }
static static
void void
fuse_send_enomem(const int fd_, fuse_send_enomem(struct fuse_session *se_,
const uint64_t unique_id_) const uint64_t unique_id_)
{ {
fuse_send_errno(fd_,ENOMEM,unique_id_); fuse_send_errno(se_,ENOMEM,unique_id_);
} }
static static
int int
fuse_ll_buf_receive_read(struct fuse_session *se_, fuse_ll_buf_receive_read(struct fuse_session *se_,
int fd_,
fuse_msgbuf_t *msgbuf_) fuse_msgbuf_t *msgbuf_)
{ {
int rv; int rv;
rv = read(fd_,msgbuf_->mem,msgbuf_->size); rv = read(se_->fd,msgbuf_->mem,msgbuf_->size);
if(rv == -1) if(rv == -1)
return -errno; return -errno;
@ -1609,7 +1608,6 @@ fuse_ll_buf_receive_read(struct fuse_session *se_,
static static
void void
fuse_ll_buf_process_read(struct fuse_session *se_, fuse_ll_buf_process_read(struct fuse_session *se_,
int fd_,
const fuse_msgbuf_t *msgbuf_) const fuse_msgbuf_t *msgbuf_)
{ {
int err; int err;
@ -1623,7 +1621,7 @@ fuse_ll_buf_process_read(struct fuse_session *se_,
req = fuse_req_alloc(); req = fuse_req_alloc();
if(req == NULL) if(req == NULL)
return fuse_send_enomem(fd_,in->unique); return fuse_send_enomem(se_,in->unique);
req->ctx.len = in->len; req->ctx.len = in->len;
req->ctx.opcode = in->opcode; req->ctx.opcode = in->opcode;
@ -1635,7 +1633,6 @@ fuse_ll_buf_process_read(struct fuse_session *se_,
req->ctx.umask = 0; req->ctx.umask = 0;
req->conn = f.conn; req->conn = f.conn;
req->se = se_; req->se = se_;
req->fd = fd_;
req->ioctl_64bit = 0; req->ioctl_64bit = 0;
err = ENOSYS; err = ENOSYS;
@ -1656,7 +1653,6 @@ fuse_ll_buf_process_read(struct fuse_session *se_,
static static
void void
fuse_ll_buf_process_read_init(struct fuse_session *se_, fuse_ll_buf_process_read_init(struct fuse_session *se_,
int fd_,
const fuse_msgbuf_t *msgbuf_) const fuse_msgbuf_t *msgbuf_)
{ {
int err; int err;
@ -1670,7 +1666,7 @@ fuse_ll_buf_process_read_init(struct fuse_session *se_,
req = fuse_req_alloc(); req = fuse_req_alloc();
if(req == NULL) if(req == NULL)
return fuse_send_enomem(fd_,in->unique); return fuse_send_enomem(se_,in->unique);
req->ctx.len = in->len; req->ctx.len = in->len;
req->ctx.opcode = in->opcode; req->ctx.opcode = in->opcode;
@ -1682,7 +1678,6 @@ fuse_ll_buf_process_read_init(struct fuse_session *se_,
req->ctx.pid = in->pid; req->ctx.pid = in->pid;
req->ctx.umask = 0; req->ctx.umask = 0;
req->se = se_; req->se = se_;
req->fd = fd_;
err = EIO; err = EIO;
if(in->opcode != FUSE_INIT) if(in->opcode != FUSE_INIT)

View file

@ -8,24 +8,16 @@
#include "fuse_i.hpp" #include "fuse_i.hpp"
#include "fuse_kernel.h" #include "fuse_kernel.h"
#include "syslog.hpp"
#include <cassert> #include <cassert>
#include <cerrno> #include <cerrno>
#include <cstdint>
#include <cstdio> #include <cstdio>
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
#include <fcntl.h>
#include <new> #include <new>
#include <sys/ioctl.h>
#include <unistd.h> #include <unistd.h>
#include <sys/uio.h> #include <sys/uio.h>
#ifndef O_CLOEXEC
#define O_CLOEXEC 0
#endif
/* /*
* Simplified session management for single-mount filesystems. * Simplified session management for single-mount filesystems.
* The fuse_chan structure has been removed and its fields inlined * The fuse_chan structure has been removed and its fields inlined
@ -33,42 +25,6 @@
* one mount point per process. * one mount point per process.
*/ */
static
int
_clone_fuse_fd(const int fd_)
{
int rv;
int clone_fd;
uint32_t source_fd;
clone_fd = ::open("/dev/fuse",O_RDWR|O_CLOEXEC);
if(clone_fd == -1)
return -errno;
source_fd = fd_;
rv = ::ioctl(clone_fd,FUSE_DEV_IOC_CLONE,&source_fd);
if(rv == -1)
{
int err = errno;
::close(clone_fd);
return -err;
}
return clone_fd;
}
static
void
_close_clone_fds(struct fuse_session *se_)
{
for(auto fd : se_->clone_fds)
{
if(fd != -1)
::close(fd);
}
se_->clone_fds.clear();
}
struct fuse_session* struct fuse_session*
fuse_session_new(void *data, fuse_session_new(void *data,
void *receive_buf, void *receive_buf,
@ -84,8 +40,8 @@ fuse_session_new(void *data,
} }
se->f = static_cast<struct fuse_ll*>(data); se->f = static_cast<struct fuse_ll*>(data);
se->receive_buf = reinterpret_cast<int(*)(struct fuse_session*, int, fuse_msgbuf_t*)>(receive_buf); se->receive_buf = reinterpret_cast<int(*)(struct fuse_session*, fuse_msgbuf_t*)>(receive_buf);
se->process_buf = reinterpret_cast<void(*)(struct fuse_session*, int, const fuse_msgbuf_t*)>(process_buf); se->process_buf = reinterpret_cast<void(*)(struct fuse_session*, const fuse_msgbuf_t*)>(process_buf);
se->destroy = reinterpret_cast<void(*)(void*)>(destroy); se->destroy = reinterpret_cast<void(*)(void*)>(destroy);
se->fd = -1; se->fd = -1;
@ -101,8 +57,6 @@ fuse_session_destroy(struct fuse_session *se)
if(se->destroy) if(se->destroy)
se->destroy(se->f); se->destroy(se->f);
::_close_clone_fds(se);
if(se->fd != -1) if(se->fd != -1)
{ {
close(se->fd); close(se->fd);
@ -139,8 +93,6 @@ fuse_session_data(struct fuse_session *se)
int int
fuse_session_clearfd(struct fuse_session *se) fuse_session_clearfd(struct fuse_session *se)
{ {
::_close_clone_fds(se);
int fd = se->fd; int fd = se->fd;
se->fd = -1; se->fd = -1;
return fd; return fd;
@ -150,55 +102,9 @@ void
fuse_session_setfd(struct fuse_session *se, fuse_session_setfd(struct fuse_session *se,
int fd) int fd)
{ {
::_close_clone_fds(se);
se->fd = fd; se->fd = fd;
} }
bool
fuse_session_setup_read_fds(struct fuse_session *se_,
const int read_thread_count_)
{
::_close_clone_fds(se_);
if(read_thread_count_ <= 1)
return false;
se_->clone_fds.reserve(read_thread_count_ - 1);
for(auto i = 1; i < read_thread_count_; i++)
{
int fd;
fd = ::_clone_fuse_fd(se_->fd);
if(fd < 0)
{
int err = -fd;
::_close_clone_fds(se_);
SysLog::warning("failed to clone /dev/fuse fd for read threads; "
"using shared fd: {} ({})",
strerror(err),
err);
return false;
}
se_->clone_fds.push_back(fd);
}
return true;
}
int
fuse_session_read_fd(struct fuse_session *se_,
const int index_)
{
if((index_ > 0) && (index_ <= (int)se_->clone_fds.size()))
return se_->clone_fds[index_ - 1];
return se_->fd;
}
void void
fuse_session_setbufsize(struct fuse_session *se, fuse_session_setbufsize(struct fuse_session *se,
size_t bufsize) size_t bufsize)