Return ENOENT, not EBADF, for removed nodes with no open file

Once a file or directory is removed (unlink, rmdir, rename over it)
libfuse has no path for its node and falls back to the fh based
getattr/setattr/statx with fh=0. If mergerfs had no open file for the
node (a directory, an O_PATH fd, a cwd, or a dentry resolved just
before the removal) it returned EBADF. The kernel sends GETATTR for
such nodes in the permission checks of a path walk, so lstat() of a
directory, or of a path below it, could fail with EBADF while rm -rf
removed it. Two rm -rf at once, one on a directory and one on the
directory above it, met it when one removed a directory the other
still had open: the other's unlinkat() through its dirfd failed, rm
reported "Bad file descriptor" and left entries behind.

mergerfs now returns ENOENT. That is what a local filesystem gives
*at() calls in a removed directory, and what rm -f ignores. ESTALE
would make the kernel redo a path based lookup, which helps a stat
racing a rename over the path. But a call through a dirfd or cwd of a
removed directory meets the same node again and fails anyway, and the
concurrent rm -rf still did. Calls on the removed object itself, which
succeed on a local filesystem, get ENOENT instead of EBADF.

TEST_rm_rf_concurrent runs the two cases reported. The rm -rf one is
a narrow race; TEST_use_dirfd_after_rmdir covers its cause without
one, with cache.attr=0 so the kernel sends GETATTR every time.

See #1693.
This commit is contained in:
Antonio S. Musumeci 2026-11-08 22:00:13 -05:00 • committed by trapexit
parent cb930ee7a0
commit 9d12bcf235
10 changed files with 285 additions and 6 deletions

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

95
tests/TEST_rm_rf_concurrent Executable file
View file

@ -0,0 +1,95 @@
#!/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())

151
tests/TEST_use_dirfd_after_rmdir Executable file
View file

@ -0,0 +1,151 @@
#!/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,6 +188,10 @@ def fail(msg):
return 1
def errno_name(err):
return errno.errorcode.get(err, str(err))
def join(root, rel):
return os.path.join(root, rel)

View file

@ -171,6 +171,18 @@ struct fuse_operations
int (*ftruncate)(const fuse_req_ctx_t *,
const uint64_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 *,
const uint64_t,
struct stat *,