fix: keep readdir listings stable under fill errors

- func.readdir=cor appended entries in whichever order branch workers
  finished. Directory offsets are positions in that list, so a reader
  reopening an unchanged directory and seeking to a previously issued
  cookie (NFS does this) could see a duplicate and miss a later entry.
  Read branches concurrently into their own buffers, then merge and
  deduplicate them in configured branch order. The merge mutex is gone.
- Growing a dirents buffer overwrote the only pointer with realloc's
  result while recording the new capacity, so an allocation failure
  leaked the buffer and the next fill wrote through NULL. Grow both
  vectors without changing pointer, length or capacity until the
  allocation succeeds, and return ENOMEM.
- seq and cosr ignored that failure and served a listing with entries
  missing. Every policy now returns the error, and libfuse resets the
  handle's buffer whenever a fill fails, so a later request at a
  nonzero offset re-enumerates instead of serving a partial or stale
  listing as success. cosr closes the directories its workers opened
  when it gives up early.
- Document the fill-error contract, which doesn't promise that every
  branch was read: seq and cosr can treat a branch read error as the
  end of the directory. Document cor's memory use, and refer to
  func.getattr, not fuse.getattr.
- TEST_readdir_cor_cookie_replay compares cor listings, offsets and
  inodes with seq and replays cookies on fresh handles.
  TEST_dirents_allocation injects allocation failures into the dirents
  code. TEST_readdir_cor_enomem fails one allocation in a mounted
  daemon for cor and seq and checks the same handle then serves the
  exact suffix.

Performance: cor copies each entry twice and merges serially after the
parallel reads. Listing 100,000 entries over 4 tmpfs branches took
the same time before and after (81-83 ms per listing for cor:4 and
seq). Peak daemon memory for cor:4 dropped from 27.4 MB to 18.7 MB.
This commit is contained in:
Antonio SJ Musumeci 2026-05-13 10:58:01 -05:00
parent b367b593ba
commit eea1c1bc09
15 changed files with 1026 additions and 79 deletions

View file

@ -12,7 +12,7 @@
| cosr:N:M | "concurrent open, sequential read" : Concurrently open branch directories using a thread pool and process them in the order defined in `branches`. This keeps memory and CPU usage low while also reducing the time spent waiting on branches to respond. `N` is the number of threads, at most 64. If `0` it is the core count, at most 8. `M` is the queue depth per thread. If `0` it is 2. |
| cosr:N | cosr:N:M with M = 0 |
| cosr | cosr:N:M with N = 0 and M = 0 |
| cor:N:M | "concurrent open and read" : Concurrently open branch directories and immediately start reading their contents using a thread pool. This will result in slightly higher memory and CPU usage but reduced latency. Particularly when using higher latency / slower speed network filesystem branches. Unlike `seq` and `cosr` the order of files could change due the async nature of the thread pool. This should not be a problem since the order of files returned in not guaranteed. `N` is the number of threads, at most 64. If `0` it is the core count, at most 8. `M` is the queue depth per thread. If `0` it is 2. |
| cor:N:M | "concurrent open and read" : Concurrently open branch directories and immediately start reading their contents using a thread pool. This will result in higher memory and CPU usage but reduced latency: peak memory is roughly all outstanding per-branch listings plus the merged output. Particularly when using higher latency / slower speed network filesystem branches. Each branch is read into its own buffer and the buffers are merged in the order defined in `branches` so, as with `seq` and `cosr`, the order of files is stable across reads. A stable order is required for correct readdir offset handling given the kernel may drop and re-open a directory mid-stream, such as when exported via NFS. `N` is the number of threads, at most 64. If `0` it is the core count, at most 8. `M` is the queue depth per thread. If `0` it is 2. |
| cor:N | cor:N:M with M = 0 |
| cor | cor:N:M with N = 0 and M = 0 |
@ -31,7 +31,7 @@ Keep in mind that `readdir` mostly just provides a list of file names
in a directory and possibly some basic metadata about said files. To
know details about the files, as one would see from commands like
`find` or `ls`, it is required to call `stat` on the file which is
controlled by `fuse.getattr`.
controlled by `func.getattr`.
Until Linux v6.16, despite being able to change the size of FUSE
messages, `readdir` requests were limited to 1 page (4KiB) in size per
@ -56,3 +56,12 @@ situations.
or change [fuse-msg-size](fuse-msg-size.md).
* [readdir](https://man7.org/linux/man-pages/man2/readdir.2.html) is
used on FreeBSD.
* Each open directory handle caches its listing. If a policy reports a
fill error (for example, `ENOMEM` while growing the entry buffer),
mergerfs returns that error and discards the incomplete buffer. The
next request rebuilds the listing, even when resuming at a nonzero
offset. With unchanged branches and directory contents, merging entries
in branch order preserves their positions across those retries.
* This is not a guarantee that every branch was read successfully. For
example, `seq` and `cosr` can treat a branch read error as end of
directory and return the entries collected so far.

View file

@ -100,9 +100,7 @@ _handle_ENOENT(const fuse_file_info_t *ffi_,
strncpy(de.d_name,msg,(sizeof(msg) - 1));
de.d_reclen = sizeof(de);
fuse_dirents_add(buf_,&de,(sizeof(msg) - 1));
return 0;
return fuse_dirents_add(buf_,&de,(sizeof(msg) - 1));
}
int

View file

@ -23,6 +23,11 @@
#include "config.hpp"
#include "dirinfo.hpp"
#include "error.hpp"
#include "fuse_dirents.hpp"
#include "hashset.hpp"
#include <cstddef>
#include <new>
FUSE::ReadDirCOR::ReadDirCOR(unsigned concurrency_,
@ -43,12 +48,56 @@ FUSE::ReadDirCOR::~ReadDirCOR()
#include "fuse_readdir_cor_readdir.icpp"
#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.
// Each branch is read concurrently into its own dirents buffer by a
// thread pool worker. The buffers are then merged into the shared
// list in branch order, making the enumeration order reproducible
// across re-reads. Reproducibility is required by FUSE readdir
// offsets, which are positional indices into the enumeration: NFS
// can drop and re-open a directory mid-stream and replay its cookie
// against a fresh handle, and a non-reproducible order splices that
// stale index into a differently-ordered list (duplicating and
// dropping entries). See GitHub issues #781 and #1589.
static
inline
uint64_t
_dirent_size(const uint64_t namelen_)
{
uint64_t rv;
rv = offsetof(fuse_dirent_t,name);
rv += namelen_;
rv = ((rv + 7) & ~7ULL);
return rv;
}
static
inline
int
_merge_branch_dirents(fuse_dirents_t *dst_,
HashSet &names_,
const fuse_dirents_t *src_)
{
size_t pos = 0;
while(pos < kv_size(src_->data))
{
int rv;
const fuse_dirent_t *d;
d = reinterpret_cast<const fuse_dirent_t*>(&kv_A(src_->data,pos));
if(names_.put(d->name,d->namelen) != 0)
{
rv = fuse_dirents_add(dst_,d,d->namelen);
if(rv != 0)
return rv;
}
pos += _dirent_size(d->namelen);
}
return 0;
}
static
inline
int
@ -57,35 +106,125 @@ _concurrent_readdir(ThreadPool &tp_,
const fs::path &rel_dirpath_,
fuse_dirents_t *dirents_)
{
int rv;
int worker_error;
Err err;
HashSet names;
Mutex mutex;
bool fill_ok;
std::vector<fuse_dirents_t> branch_dirents;
std::vector<std::future<int>> futures;
worker_error = 0;
fill_ok = false;
fuse_dirents_reset(dirents_);
futures.reserve(branches_->size());
for(const auto &branch : *branches_)
DEFER{
for(auto &bd : branch_dirents)
fuse_dirents_free(&bd);
};
// A failed fill must not leave a partial or stale listing cached:
// the next request would continue reading it at an offset belonging
// to a different enumeration, duplicating and dropping entries.
// Reset the destination on every unsuccessful exit so the next
// readdir re-enumerates from scratch. The reset above covers entry
// into a regeneration after a previous failure, including a request
// resuming at a nonzero offset against an emptied cache.
DEFER{
if(not fill_ok)
fuse_dirents_reset(dirents_);
};
auto wait_for_tasks = [&futures]()
{
auto func =
[&,dirents_]()
// No queued task may still reference locals during cleanup.
for(auto &future : futures)
{
return ::_readdir(branch.path,
rel_dirpath_,
names,
dirents_,
mutex);
};
if(not future.valid())
continue;
try
{
future.wait();
}
catch(...)
{
}
}
};
auto rv = tp_.enqueue_task(std::move(func));
try
{
branch_dirents.reserve(branches_->size());
for(size_t i = 0; i < branches_->size(); ++i)
{
fuse_dirents_t bd;
futures.emplace_back(std::move(rv));
// Per-branch scratch buffer: empty with just the zero
// offset sentinel and nothing pre-allocated. Checked so an
// allocation failure cannot leave a half-built buffer for
// a worker to fill.
rv = fuse_dirents_init_noreserve(&bd);
if(rv != 0)
return rv;
branch_dirents.emplace_back(bd);
}
futures.reserve(branches_->size());
size_t i = 0;
for(const auto &branch : *branches_)
{
const fs::path *branch_path = &branch.path;
auto func = [branch_path,i,&rel_dirpath_,&branch_dirents]()
{
return ::_readdir(*branch_path,
rel_dirpath_,
&branch_dirents[i]);
};
futures.emplace_back(tp_.enqueue_task(std::move(func)));
i++;
}
for(auto &future : futures)
{
rv = future.get();
if(rv == -ENOMEM)
worker_error = rv;
err = rv;
}
// Do not merge a buffer whose allocation failed partway through.
if(worker_error != 0)
return worker_error;
rv = 0;
for(auto &bd : branch_dirents)
{
rv = _merge_branch_dirents(dirents_,names,&bd);
if(rv != 0)
break;
}
}
catch(const std::bad_alloc&)
{
wait_for_tasks();
return -ENOMEM;
}
catch(...)
{
wait_for_tasks();
return -EIO;
}
Err err;
for(auto &future : futures)
err = future.get();
// A nonzero status means the caller gets an error reply, never the
// listing; keep the cache only for a fully successful fill. The
// DEFER above discards it in every other case.
rv = (rv != 0 ? rv : err);
if(rv == 0)
fill_ok = true;
return err;
return rv;
}
int

View file

@ -23,9 +23,6 @@
#include "fs_inode.hpp"
#include "fs_open.hpp"
#include "fs_path.hpp"
#include "hashset.hpp"
#include "mutex.hpp"
#include "scope_guard/scope_guard.hpp"
#include "fuse_msgbuf.hpp"
@ -37,9 +34,7 @@ inline
int
_readdir(const fs::path &branch_path_,
const fs::path &rel_dirpath_,
HashSet &names_,
fuse_dirents_t *dirents_,
mutex_t &mutex_)
fuse_dirents_t *dirents_)
{
int fd;
fuse_msgbuf_t *buf;
@ -67,7 +62,6 @@ _readdir(const fs::path &branch_path_,
if(nread <= 0)
return nread;
LockGuard lk(mutex_);
for(ssize_t pos = 0; pos < nread;)
{
int rv;
@ -78,16 +72,14 @@ _readdir(const fs::path &branch_path_,
namelen = d->namelen();
rv = names_.put(d->name,namelen);
if(rv == 0)
continue;
d->ino = inodecalc.calc(d->name,
namelen,
DTTOIF(d->type),
d->ino);
d->ino = inodecalc.calc(d->name,
namelen,
DTTOIF(d->type),
d->ino);
fuse_dirents_add(dirents_,d,namelen);
rv = fuse_dirents_add(dirents_,d,namelen);
if(rv != 0)
return rv;
}
}

View file

@ -22,7 +22,6 @@
#include "fs_opendir.hpp"
#include "fs_closedir.hpp"
#include "hashset.hpp"
#include "scope_guard/scope_guard.hpp"
#include "fs_readdir.hpp"
#include "fs_inode.hpp"
@ -52,9 +51,7 @@ inline
int
_readdir(const fs::path &branch_path_,
const fs::path &rel_dirpath_,
HashSet &names_,
fuse_dirents_t *dirents_,
mutex_t &mutex_)
fuse_dirents_t *dirents_)
{
DIR *dir;
fs::path abs_dirpath;
@ -70,7 +67,6 @@ _readdir(const fs::path &branch_path_,
fs::inode::ReaddirCalc inodecalc(branch_path_,rel_dirpath_);
while(true)
{
LockGuard lk(mutex_);
for(int i = 0; i < MAX_ENTRIES_PER_LOOP; i++)
{
int rv;
@ -84,16 +80,14 @@ _readdir(const fs::path &branch_path_,
namelen = ::_dirent_exact_namelen(de);
rv = names_.put(de->d_name,namelen);
if(rv == 0)
continue;
de->d_ino = inodecalc.calc(de->d_name,
namelen,
DTTOIF(de->d_type),
de->d_ino);
de->d_ino = inodecalc.calc(de->d_name,
namelen,
DTTOIF(de->d_type),
de->d_ino);
fuse_dirents_add(dirents_,de,namelen);
rv = fuse_dirents_add(dirents_,de,namelen);
if(rv != 0)
return rv;
}
}

View file

@ -75,6 +75,34 @@ _opendir(ThreadPool &tp_,
return futures;
}
// A failed fill returns before every branch future has been consumed;
// drain the rest so their opened directory fds are closed instead of
// leaking. Futures consumed by the main loop are invalid and skipped.
// A worker exception is swallowed: cleanup must not throw.
static
inline
void
_drain_futures(std::vector<std::future<DirRV>> &dh_futures_)
{
DirRV dirrv;
for(auto &dh_future : dh_futures_)
{
if(not dh_future.valid())
continue;
try
{
dirrv = dh_future.get();
}
catch(...)
{
continue;
}
if(dirrv.fd >= 0)
fs::close(dirrv.fd);
}
}
static
inline
int
@ -88,7 +116,10 @@ _readdir(std::vector<std::future<DirRV>> &dh_futures_,
buf = msgbuf_alloc();
if(not buf)
return -ENOMEM;
{
::_drain_futures(dh_futures_);
return -ENOMEM;
}
DEFER { msgbuf_free(buf); };
for(auto &dh_future : dh_futures_)
@ -130,7 +161,12 @@ _readdir(std::vector<std::future<DirRV>> &dh_futures_,
DTTOIF(d->type),
d->ino);
fuse_dirents_add(dirents_,d,namelen);
rv = fuse_dirents_add(dirents_,d,namelen);
if(rv != 0)
{
::_drain_futures(dh_futures_);
return rv;
}
}
}
}

View file

@ -85,6 +85,34 @@ _opendir(ThreadPool &tp_,
return futures;
}
// A failed fill returns before every branch future has been consumed;
// drain the rest so their opened directory handles are closed instead
// of leaking. Futures consumed by the main loop are invalid and
// skipped. A worker exception is swallowed: cleanup must not throw.
static
inline
void
_drain_futures(std::vector<std::future<DirRV>> &dh_futures_)
{
DirRV dirrv;
for(auto &dh_future : dh_futures_)
{
if(not dh_future.valid())
continue;
try
{
dirrv = dh_future.get();
}
catch(...)
{
continue;
}
if(dirrv.dir != NULL)
fs::closedir(dirrv.dir);
}
}
static
inline
int
@ -125,7 +153,12 @@ _readdir(std::vector<std::future<DirRV>> &dh_futures_,
DTTOIF(de->d_type),
de->d_ino);
fuse_dirents_add(dirents_,de,namelen);
rv = fuse_dirents_add(dirents_,de,namelen);
if(rv != 0)
{
::_drain_futures(dh_futures_);
return rv;
}
}
}

View file

@ -89,7 +89,9 @@ _readdir(const Branches::Ptr &branches_,
DTTOIF(d->type),
d->ino);
fuse_dirents_add(dirents_,d,namelen);
rv = fuse_dirents_add(dirents_,d,namelen);
if(rv != 0)
return rv;
}
}
}

View file

@ -88,7 +88,9 @@ _readdir(const Branches::Ptr &branches_,
DTTOIF(de->d_type),
de->d_ino);
fuse_dirents_add(dirents_,de,namelen);
rv = fuse_dirents_add(dirents_,de,namelen);
if(rv != 0)
return rv;
}
}

230
tests/TEST_dirents_allocation Executable file
View file

@ -0,0 +1,230 @@
#!/usr/bin/env python3
"""Deterministic allocation-failure regression for the fuse_dirents layer.
Compiles the real vendored/libfuse/lib/fuse_dirents.cpp with a small C++
harness and -Wl,--wrap=realloc/--wrap=free, failing one exact call: the
initial reservation (NULL old pointer), the next data-buffer growth
(>= 32KiB quantum), or the next offset-table growth (< 32KiB). No mount,
no branches; disposable work dir under tests/.test_tmp. A failed call
must return -ENOMEM once and leave the added entries intact, verified by
name, inode and cookie (d->off == index + 1), never by pointers,
capacities or padding bytes; a disarmed retry must complete to exactly
the never-failed sequence, and a failed init must leave nothing behind.
Exit codes: 0 pass, 1 fail, 77 skip (non-Linux or no C++ compiler).
"""
import os
import shutil
import subprocess
import sys
import tempfile
SKIP = 77
HARNESS = r"""
#include "fuse_dirents.hpp"
#include <dirent.h>
#include <errno.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* Data grows in 32KiB quanta; offset-table reallocs stay far below it,
so the allocation size discriminates the two vectors. Mode: 1 fails
a NULL old pointer (init), 2 the next data growth, 3 the next table
growth; each fires once at the Nth matching call. */
#define DATA_QUANTUM (1024 * 32)
#define NENTRIES 1500
extern "C" {
void *__real_realloc(void *, size_t);
void __real_free(void *);
}
static int fail_mode, fail_nth, fail_count;
static long live_blocks;
static char msg[256];
static void arm(int mode, int nth) {
fail_mode = mode;
fail_nth = nth;
fail_count = 0;
}
static bool ok(bool cond, const char *what) {
if(!cond && !msg[0])
snprintf(msg, sizeof(msg), "%s", what);
return cond;
}
static int should_fail(void *p, size_t n) {
int match;
if(fail_mode == 1)
match = (p == NULL);
else if(fail_mode == 2)
match = (p && n >= DATA_QUANTUM);
else if(fail_mode == 3)
match = (p && n < DATA_QUANTUM);
else
return 0;
if(!match || --fail_nth)
return 0;
fail_count++;
return 1;
}
/* A failed realloc leaves the old block alive (no count change); a
successful NULL-pointer realloc births one; nonnull moves are net
zero. libc internals do not route through these wrappers. */
extern "C" void *__wrap_realloc(void *p, size_t n) {
void *q;
if(should_fail(p, n))
return NULL;
q = __real_realloc(p, n);
if(q && !p)
live_blocks++;
return q;
}
extern "C" void __wrap_free(void *p) {
if(p)
live_blocks--;
__real_free(p);
}
static bool check_entries(fuse_dirents_t *d, int count, const char *what) {
int i;
char want[16];
if(!ok((int)kv_size(d->offs) == count + 1 && kv_A(d->offs, 0) == 0, what))
return false;
for(i = 0; i < count; i++) {
const fuse_dirent_t *de =
(const fuse_dirent_t *)&kv_A(d->data, kv_A(d->offs, i));
snprintf(want, sizeof(want), "e%07d", i);
if(!ok(de->ino == (uint64_t)i + 1 && de->off == (uint64_t)i + 1 &&
de->namelen == 8 && !memcmp(de->name, want, 8), what))
return false;
}
return true;
}
static int add_entry(fuse_dirents_t *d, int idx) {
char name[16];
alignas(fs::dirent64) char storage[64];
fs::dirent64 *de = (fs::dirent64 *)storage;
snprintf(name, sizeof(name), "e%07d", idx);
memset(storage, 0, sizeof(storage));
de->ino = (uint64_t)idx + 1;
de->reclen = (uint16_t)(offsetof(fs::dirent64, name) + 9);
de->type = DT_REG;
memcpy(de->name, name, 9);
return fuse_dirents_add(d, de, 8);
}
/* Arm the injector, add until one add fails, verify the survived prefix
and that a disarmed retry reaches exactly the never-failed sequence. */
static bool growth_scenario(int mode, const char *what) {
fuse_dirents_t d;
int i, failed_at = -1;
if(fuse_dirents_init(&d))
return ok(false, "clean init failed");
arm(mode, 1);
for(i = 0; i < NENTRIES; i++)
if(add_entry(&d, i)) { failed_at = i; break; }
fail_mode = 0;
if(!ok(fail_count == 1, "injected growth failure did not fire exactly once") ||
!ok(failed_at > 0, what) ||
!check_entries(&d, failed_at, what))
return false;
for(; i < NENTRIES; i++)
if(add_entry(&d, i))
return ok(false, "retry add after the failed growth failed");
if(!check_entries(&d, NENTRIES, what))
return false;
fuse_dirents_free(&d);
return ok(live_blocks == 0, "dirents allocation leaked");
}
static bool init_failure(void) {
fuse_dirents_t d;
arm(1, 1);
if(!ok(fuse_dirents_init(&d) == -ENOMEM,
"init did not return -ENOMEM on its failed initial allocation") ||
!ok(fail_count == 1, "init injector did not fire exactly once"))
return false;
fail_mode = 0;
fuse_dirents_free(&d);
if(!ok(live_blocks == 0, "failed init left an allocation behind"))
return false;
if(fuse_dirents_init(&d))
return ok(false, "init after a failed init failed");
fuse_dirents_free(&d);
return ok(live_blocks == 0, "dirents allocation leaked");
}
int main(void) {
static char stdout_buf[4096];
setvbuf(stdout, stdout_buf, _IOFBF, sizeof(stdout_buf));
if(!growth_scenario(2, "no add failed under the armed data-growth injector") ||
!growth_scenario(3, "no add failed under the armed offset-growth injector") ||
!init_failure()) {
printf("FAIL: %s\n", msg);
return 1;
}
printf("PASS\n");
return 0;
}
"""
def main():
if not sys.platform.startswith("linux"):
print("Linux-only allocation regression; skipping on " + sys.platform)
return SKIP
compiler = next((shutil.which(c) for c in ("g++", "c++", "clang++")
if shutil.which(c)), None)
if compiler is None:
print("no C++ compiler found; skipping")
return SKIP
tests_dir = os.path.dirname(os.path.realpath(__file__))
repo = os.path.dirname(tests_dir)
fuse_dirents_cpp = os.path.join(repo, "vendored", "libfuse", "lib",
"fuse_dirents.cpp")
if not os.path.isfile(fuse_dirents_cpp):
print("missing " + fuse_dirents_cpp)
return 1
tmp_parent = os.path.join(tests_dir, ".test_tmp")
os.makedirs(tmp_parent, exist_ok=True)
workdir = tempfile.mkdtemp(prefix="dirents_allocation_",
dir=tmp_parent)
try:
harness_cpp = os.path.join(workdir, "harness.cpp")
binary = os.path.join(workdir, "test_dirents_allocation")
with open(harness_cpp, "w", encoding="ascii") as stream:
stream.write(HARNESS)
compiled = subprocess.run(
[compiler, "-std=c++20", "-O2", "-fno-builtin",
"-D_FILE_OFFSET_BITS=64",
"-I" + os.path.join(repo, "vendored", "libfuse", "include"),
"-I" + os.path.join(repo, "src"),
"-I" + os.path.join(repo, "vendored"),
"-Wl,--wrap=realloc", "-Wl,--wrap=free",
harness_cpp, fuse_dirents_cpp, "-o", binary],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
if compiled.returncode != 0:
print("compilation failed:\n" + compiled.stdout)
return 1
run = subprocess.run(
[binary], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True)
sys.stdout.write(run.stdout)
return run.returncode
finally:
shutil.rmtree(workdir, ignore_errors=True)
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -0,0 +1,200 @@
#!/usr/bin/env python3
import ctypes
import os
import sys
from posix_parity import fail
from posix_parity import mergerfs_mount
from posix_parity import mount_mergerfs
from posix_parity import unmount_mergerfs
if not sys.platform.startswith("linux"):
print("This Linux dirent ABI test is unsupported on " + sys.platform)
raise SystemExit(77)
class Dirent(ctypes.Structure):
_fields_ = [
("d_ino", ctypes.c_ulong),
("d_off", ctypes.c_long),
("d_reclen", ctypes.c_ushort),
("d_type", ctypes.c_ubyte),
("d_name", ctypes.c_char * 256),
]
libc = ctypes.CDLL(None, use_errno=True)
libc.opendir.argtypes = [ctypes.c_char_p]
libc.opendir.restype = ctypes.c_void_p
libc.readdir.argtypes = [ctypes.c_void_p]
libc.readdir.restype = ctypes.POINTER(Dirent)
libc.seekdir.argtypes = [ctypes.c_void_p, ctypes.c_long]
libc.seekdir.restype = None
libc.closedir.argtypes = [ctypes.c_void_p]
libc.closedir.restype = ctypes.c_int
def opendir_or_raise(path):
ctypes.set_errno(0)
dp = libc.opendir(os.fsencode(path))
if not dp:
err = ctypes.get_errno()
raise OSError(err, os.strerror(err), path)
return dp
def snapshot(ent):
name = bytes(ent.d_name).split(b"\0", 1)[0]
return (
os.fsdecode(name),
int(ent.d_type),
int(ent.d_ino),
int(ent.d_off),
)
def read_one(dp):
ctypes.set_errno(0)
entp = libc.readdir(dp)
if entp:
return snapshot(entp.contents)
err = ctypes.get_errno()
if err:
raise OSError(err, os.strerror(err))
return None
def read_all(dp):
entries = []
while True:
entry = read_one(dp)
if entry is None:
return entries
entries.append(entry)
def close_dir(dp):
if libc.closedir(dp) != 0:
err = ctypes.get_errno()
raise OSError(err, os.strerror(err))
def read_listing(path):
dp = opendir_or_raise(path)
try:
return read_all(dp)
finally:
close_dir(dp)
def replay_cookie(path, prefix_length):
dp = opendir_or_raise(path)
try:
prefix = [read_one(dp) for _ in range(prefix_length)]
if any(entry is None for entry in prefix):
raise RuntimeError("directory ended before the requested replay prefix")
cookie = prefix[-1][3]
finally:
close_dir(dp)
dp = opendir_or_raise(path)
try:
ctypes.set_errno(0)
libc.seekdir(dp, cookie)
err = ctypes.get_errno()
if err:
raise OSError(err, os.strerror(err))
suffix = read_all(dp)
finally:
close_dir(dp)
return prefix, cookie, suffix
def first_difference(actual, expected):
for index, (got, want) in enumerate(zip(actual, expected)):
if got != want:
return f"entry {index}: got {got!r}, expected {want!r}"
if len(actual) != len(expected):
return f"entry count {len(actual)}, expected {len(expected)}"
return "unknown difference"
def make_name(prefix, index):
return f"{prefix}_{index:05d}_" + "x" * 64
def populate(branches):
shared = [make_name("shared", index) for index in range(16)]
counts = [4000, 7, 5, 3]
for branch_index, (branch, count) in enumerate(zip(branches, counts)):
dirpath = os.path.join(branch, "dir")
os.mkdir(dirpath)
names = shared + [make_name(f"branch{branch_index}", index) for index in range(count)]
for name in names:
with open(os.path.join(dirpath, name), "wb") as stream:
stream.write(f"branch{branch_index}\n".encode("ascii"))
return shared
def main():
options = "defaults,use_ino,category.create=mfs,cache.readdir=false"
try:
with mergerfs_mount(
num_branches=4,
options=options + ",func.readdir=seq",
) as (mount, branches):
shared = populate(branches)
dirpath = os.path.join(mount, "dir")
expected = read_listing(dirpath)
expected_unique = 2 + 16 + 4000 + 7 + 5 + 3
if len(expected) != expected_unique:
return fail(
f"seq fixture has {len(expected)} entries, expected {expected_unique}"
)
if len({entry[0] for entry in expected}) != len(expected):
return fail("seq fixture contains duplicate names")
with open(os.path.join(dirpath, shared[0]), "rb") as stream:
if stream.read() != b"branch0\n":
return fail("duplicate name does not resolve to the first branch")
unmount_mergerfs(mount)
mount_mergerfs(branches, mount, options + ",func.readdir=cor:4")
for attempt in range(4):
actual = read_listing(dirpath)
if actual != expected:
return fail(
f"cor listing {attempt} differs from seq: "
+ first_difference(actual, expected)
)
split_points = [1, 2, 3, 17, 64, 255, 511, 1024, 1536, 2048, 3072]
split_points += [len(expected) - 1, len(expected)]
for prefix_length in split_points:
prefix, cookie, suffix = replay_cookie(dirpath, prefix_length)
resumed = prefix + suffix
if resumed != expected:
return fail(
f"fresh-handle replay at cookie {cookie} after "
f"{prefix_length} entries differs: "
+ first_difference(resumed, expected)
)
return 0
except RuntimeError as exc:
if "binary not found" in str(exc) or "fusermount" in str(exc):
print(str(exc), end="")
return 77
return fail(str(exc))
except OSError as exc:
return fail(f"readdir COR cookie replay failed: {exc}")
if __name__ == "__main__":
raise SystemExit(main())

183
tests/TEST_readdir_cor_enomem Executable file
View file

@ -0,0 +1,183 @@
#!/usr/bin/env python3
"""Mounted ENOMEM regression for func.readdir=cor and func.readdir=seq.
The dirents-level failures are covered by TEST_dirents_allocation; this
test drives the real daemon, once per policy. A fill that fails partway
must be reported as ENOMEM and leave no partial or stale listing cached,
so the next read on the SAME handle re-enumerates and serves the exact
reference suffix from the requested cookie. Helpers come from the
tracked cookie-replay regression via runpy. Only the daemon gets an
LD_PRELOAD failing one realloc: old pointer nonnull (not an initial
reservation), new size 64KiB (the second 32KiB data quantum of the
handle's dirents buffer), on the 'fuse.read' thread, and only while a
marker file exists, armed after a clean reference listing and consumed
on fire so the recovery fill succeeds. seq is targeted by the same
injector because read-thread-count=1 with process-thread-count=-1 runs
every request synchronously on 'fuse.read', where seq performs its
whole fill and grows the handle buffer in the same 32KiB quanta (its
branch scratch buffer is posix_memalign'ed, so it cannot steal the
realloc); cor merges into the same buffer there, while its branch
scratch buffers grow on 'readdir.cor' workers. Fails (not skips) if the
injector never fires or the errno is not ENOMEM.
Exit codes: 0 pass, 1 fail, 77 skip.
"""
import errno
import os
import runpy
import shutil
import subprocess
import sys
import tempfile
SKIP = 77
HERE = os.path.dirname(os.path.realpath(__file__))
_cookie = runpy.run_path(os.path.join(HERE, "TEST_readdir_cor_cookie_replay"))
(close_dir, fail, first_difference, libc, mergerfs_mount,
opendir_or_raise, populate, read_all, read_one, read_listing) = (
_cookie[name] for name in ("close_dir", "fail", "first_difference",
"libc", "mergerfs_mount", "opendir_or_raise",
"populate", "read_all", "read_one",
"read_listing"))
# Synchronous read thread: both policies grow the handle's shared
# dirents buffer there. seq fills it directly on the request thread;
# cor merges into it there, not on the readdir.cor branch workers.
OPTIONS_TEMPLATE = ("defaults,use_ino,category.create=mfs,cache.readdir=false,"
"read-thread-count=1,process-thread-count=-1,"
"func.readdir={policy}")
PRELOAD_C = r"""
#define _GNU_SOURCE
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
extern void *__libc_realloc(void *,size_t);
/* The open directory handle's dirents buffer grows in 32KiB quanta on
the synchronous read thread; its 64KiB growth carries a non-NULL old
pointer, unlike the opendir-time init reservation. Both policies
grow it there: seq fills it directly, cor merges into it. */
#define MERGED_GROWTH ((size_t)(64 * 1024))
void *
realloc(void *ptr_,size_t size_)
{
if((ptr_ != NULL) && (size_ == MERGED_GROWTH))
{
const char *marker = getenv("MERGERFS_TEST_COR_ENOMEM_MARKER");
char name[16];
if((marker != NULL) &&
(pthread_getname_np(pthread_self(),name,sizeof(name)) == 0) &&
(strcmp(name,"fuse.read") == 0) &&
(access(marker,F_OK) == 0))
{
unlink(marker);
return NULL;
}
}
return __libc_realloc(ptr_,size_);
}
"""
def main():
if not sys.platform.startswith("linux"):
print("Linux-only cor ENOMEM regression; skipping on " + sys.platform)
return SKIP
if not hasattr(libc, "__libc_realloc"):
print("glibc is required for the daemon allocator hook")
return SKIP
compiler = shutil.which("cc") or shutil.which("gcc")
if compiler is None:
print("no C compiler for the preload; skipping")
return SKIP
tmp_parent = os.path.join(HERE, ".test_tmp")
os.makedirs(tmp_parent, exist_ok=True)
tmpdir = tempfile.mkdtemp(prefix="mergerfs_cor_enomem_", dir=tmp_parent)
preload = os.path.join(tmpdir, "cor_enomem_preload.so")
marker = os.path.join(tmpdir, "cor_enomem_armed")
preload_env = os.environ.get("LD_PRELOAD")
try:
src = os.path.join(tmpdir, "cor_enomem_preload.c")
with open(src, "w", encoding="ascii") as stream:
stream.write(PRELOAD_C)
built = subprocess.run(
[compiler, "-O2", "-fPIC", "-shared", src, "-o", preload],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
if built.returncode != 0:
return fail("preload compilation failed:\n" + built.stdout)
os.environ["LD_PRELOAD"] = preload
os.environ["MERGERFS_TEST_COR_ENOMEM_MARKER"] = marker
try:
for policy in ("cor:4", "seq"):
rv = injected_run(marker, policy)
if rv != 0:
return rv
return 0
except RuntimeError as exc:
if ("binary not found" in str(exc)) or ("fusermount" in str(exc)):
print(str(exc), end="")
return SKIP
return fail(str(exc))
except OSError as exc:
return fail("cor ENOMEM regression failed: %s" % exc)
finally:
if preload_env is None:
os.environ.pop("LD_PRELOAD", None)
else:
os.environ["LD_PRELOAD"] = preload_env
os.environ.pop("MERGERFS_TEST_COR_ENOMEM_MARKER", None)
shutil.rmtree(tmpdir, ignore_errors=True)
def injected_run(marker, policy):
options = OPTIONS_TEMPLATE.format(policy=policy)
with mergerfs_mount(num_branches=4, options=options) as (mount, branches):
dirpath = os.path.join(mount, "dir")
populate(branches)
truth = read_listing(dirpath)
if len(truth) < 4:
return fail("reference listing has only %d entries" % len(truth))
if len({entry[0] for entry in truth}) != len(truth):
return fail("reference listing contains duplicate names")
mid = len(truth) // 2
cookie = truth[mid][3]
expected_suffix = truth[(mid + 1):]
with open(marker, "w", encoding="ascii"):
pass
dp = opendir_or_raise(dirpath)
try:
libc.seekdir(dp, cookie)
try:
first = read_one(dp)
except OSError as exc:
if exc.errno != errno.ENOMEM:
return fail("injected failure reported errno %s, "
"expected ENOMEM" % exc.errno)
else:
return fail("injector never fired: the seeked readdir "
"returned %r" % (first,))
suffix = read_all(dp)
finally:
close_dir(dp)
if suffix != expected_suffix:
return fail("after ENOMEM the same handle served a wrong "
"suffix: " + first_difference(suffix, expected_suffix))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -36,13 +36,20 @@ struct fuse_dirents_t
kvec_t(uint32_t) offs;
};
/* A failed add preserves entries and cookies (capacity may grow). offs[0]
is the zero sentinel; offs[k] starts entry k and its cookie is k+1. */
int fuse_dirents_init(fuse_dirents_t *d);
int fuse_dirents_init_noreserve(fuse_dirents_t *d);
void fuse_dirents_free(fuse_dirents_t *d);
void fuse_dirents_reset(fuse_dirents_t *d);
int fuse_dirents_add(fuse_dirents_t *d,
const dirent *de,
const uint64_t namelen);
int fuse_dirents_add(fuse_dirents_t *d_,
const dirent *de_,
const uint64_t namelen_);
int fuse_dirents_add(fuse_dirents_t *d,
const fs::dirent64 *de,
const uint64_t namelen);
int fuse_dirents_add(fuse_dirents_t *d,
const fuse_dirent_t *de,
const uint64_t namelen);

View file

@ -2561,6 +2561,11 @@ fuse_lib_readdir(fuse_req_t *req_,
if(rv)
{
// A failed fill must not leave a partial or stale listing
// cached: a later nonzero-offset request would otherwise be
// served from a truncated enumeration of a different fill.
// Reset so the next request re-enumerates from scratch.
fuse_dirents_reset(d);
fuse_reply_err(req_,rv);
return;
}
@ -2611,6 +2616,11 @@ fuse_lib_readdir_plus(fuse_req_t *req_,
if(rv)
{
// A failed fill must not leave a partial or stale listing
// cached: a later nonzero-offset request would otherwise be
// served from a truncated enumeration of a different fill.
// Reset so the next request re-enumerates from scratch.
fuse_dirents_reset(d);
fuse_reply_err(req_,rv);
return;
}

View file

@ -23,6 +23,9 @@
/* Initial pre-allocated capacity for directory-entry offset vector */
#define DENTS_OFFS_INITIAL_CAPACITY 64
// Grow through checked reallocations; kvec's unchecked growth loses the
// original pointer on failure. Offsets in the returned listing are uint32_t.
static
uint64_t
_round_up(const uint64_t number_,
@ -51,25 +54,73 @@ _dirent_size(const uint64_t namelen_)
return rv;
}
// Grow the data buffer so one more entry of size_ bytes fits. The
// reallocation is checked: on failure the buffer's pointer, length
// and capacity are left exactly as they were, so a failed add neither
// loses written entries nor leaks the old buffer.
static
int
_dirents_buf_resize(fuse_dirents_t *d_,
const uint64_t size_)
{
if((kv_size(d_->data) + size_) >= kv_max(d_->data))
if(size_ > (UINT32_MAX - kv_size(d_->data)))
return -ENOMEM;
if((kv_size(d_->data) + size_) > kv_max(d_->data))
{
uint64_t new_size;
char *new_data;
new_size = _round_up((kv_size(d_->data) + size_),DENTS_BUF_EXPAND_SIZE);
if(new_size > SIZE_MAX)
new_size = SIZE_MAX;
kv_resize(char,d_->data,new_size);
if(d_->data.a == NULL)
new_data = (char*)realloc(d_->data.a,new_size);
if(new_data == NULL)
return -ENOMEM;
d_->data.a = new_data;
kv_max(d_->data) = new_size;
}
return 0;
}
// Grow the offset vector so entries_ more entries fit. Checked like
// _dirents_buf_resize; growth mirrors kv_push's doubling.
static
int
_dirents_offs_resize(fuse_dirents_t *d_,
const uint64_t entries_)
{
uint64_t new_capacity;
uint32_t *new_offs;
if((kv_size(d_->offs) + entries_) <= kv_max(d_->offs))
return 0;
new_capacity = kv_max(d_->offs);
while((kv_size(d_->offs) + entries_) > new_capacity)
new_capacity = (new_capacity ? (new_capacity << 1) : 2);
if(new_capacity > SIZE_MAX / sizeof(uint32_t))
return -ENOMEM;
new_offs = (uint32_t*)realloc(d_->offs.a,(new_capacity * sizeof(uint32_t)));
if(new_offs == NULL)
return -ENOMEM;
d_->offs.a = new_offs;
kv_max(d_->offs) = new_capacity;
return 0;
}
// Reserve both vectors before committing either length. A failed append
// can grow capacity, but never changes the listing or its cookies.
// offs stays one longer than the entry count: offs[0] is the zero
// sentinel and offs[k] is the data offset of entry k, so an entry's
// cookie is its index + 1, the offset the next readdir resumes from.
static
fuse_dirent_t*
_dirents_dirent_alloc(fuse_dirents_t *d_,
@ -79,8 +130,14 @@ _dirents_dirent_alloc(fuse_dirents_t *d_,
uint64_t size;
fuse_dirent_t *d;
if(namelen_ > UINT32_MAX)
return NULL;
size = _dirent_size(namelen_);
rv = _dirents_offs_resize(d_,1);
if(rv)
return NULL;
rv = _dirents_buf_resize(d_,size);
if(rv)
return NULL;
@ -88,6 +145,10 @@ _dirents_dirent_alloc(fuse_dirents_t *d_,
d = (fuse_dirent_t*)&kv_end(d_->data);
kv_size(d_->data) += size;
d->off = kv_size(d_->offs);
d_->offs.a[d_->offs.n] = kv_size(d_->data);
kv_size(d_->offs)++;
return d;
}
@ -102,8 +163,6 @@ fuse_dirents_add(fuse_dirents_t *d_,
if(d == NULL)
return -ENOMEM;
d->off = kv_size(d_->offs);
kv_push(uint32_t,d_->offs,kv_size(d_->data));
d->ino = de_->d_ino;
d->namelen = namelen_;
d->type = de_->d_type;
@ -123,8 +182,6 @@ fuse_dirents_add(fuse_dirents_t *d_,
if(d == NULL)
return -ENOMEM;
d->off = kv_size(d_->offs);
kv_push(uint32_t,d_->offs,kv_size(d_->data));
d->ino = de_->ino;
d->namelen = namelen_;
d->type = de_->type;
@ -133,6 +190,30 @@ fuse_dirents_add(fuse_dirents_t *d_,
return 0;
}
int
fuse_dirents_add(fuse_dirents_t *d_,
const fuse_dirent_t *de_,
const uint64_t namelen_)
{
fuse_dirent_t *d;
d = _dirents_dirent_alloc(d_,namelen_);
if(d == NULL)
return -ENOMEM;
d->ino = de_->ino;
d->namelen = namelen_;
d->type = de_->type;
memcpy(d->name,de_->name,namelen_);
return 0;
}
// Restore the just-initialized state: empty data and a single offset
// sentinel. offs[0] is never overwritten by adds, so only lengths
// change and no reallocation happens. A fill that fails partway must
// be reset before the dirents are reused: a partial listing would
// otherwise be served at offsets belonging to a complete enumeration.
void
fuse_dirents_reset(fuse_dirents_t *d_)
{
@ -143,14 +224,45 @@ fuse_dirents_reset(fuse_dirents_t *d_)
int
fuse_dirents_init(fuse_dirents_t *d_)
{
kv_init(d_->data);
kv_resize(char,d_->data,DENTS_BUF_EXPAND_SIZE);
if(d_->data.a == NULL)
return -ENOMEM;
int rv;
kv_init(d_->data);
kv_init(d_->offs);
kv_resize(uint32_t,d_->offs,DENTS_OFFS_INITIAL_CAPACITY);
kv_push(uint32_t,d_->offs,0);
rv = _dirents_buf_resize(d_,DENTS_BUF_EXPAND_SIZE);
if(rv)
return rv;
rv = _dirents_offs_resize(d_,DENTS_OFFS_INITIAL_CAPACITY);
if(rv)
{
kv_destroy(d_->data);
kv_init(d_->data);
return rv;
}
d_->offs.a[d_->offs.n++] = 0;
return 0;
}
// Like fuse_dirents_init but reserves nothing beyond the single zero
// offset sentinel. For scratch buffers filled immediately by the
// caller. Returns -ENOMEM on allocation failure with nothing left
// allocated.
int
fuse_dirents_init_noreserve(fuse_dirents_t *d_)
{
int rv;
kv_init(d_->data);
kv_init(d_->offs);
rv = _dirents_offs_resize(d_,1);
if(rv)
return rv;
d_->offs.a[d_->offs.n++] = 0;
return 0;
}