fix: make the statfs cache correct and its timeout configurable

- A failed statvfs was cached as a success: for the next cache.statfs
  seconds every caller got the entry's old or zeroed stats and create
  policies chose branches from them. Keep a failure as an error for the
  timeout, like a success, so a slow failing branch isn't retried under
  the lock by every caller in turn. Document that the branch then stays
  excluded from space-based create policies until the timeout expires.
- A new entry was told apart from a fresh one only by a time of 0, so a
  timeout of at least the current time in seconds returned the zeroed
  struct as success. Give entries a valid flag set by the first
  statvfs, and measure age with a steady clock from when statvfs
  returned.
- cache.statfs given at mount was stored but never applied. Bind the
  option directly to the atomic the cache reads, so mount options,
  config files and control-file updates follow one path and concurrent
  readback no longer races with updates.
- tests.cpp checks that a cached failure is never served as success,
  that failures are kept until the timeout, huge timeouts, an invalid
  update keeping a cached ENOENT, and a timeout of 0 exposing a newly
  created directory immediately.
This commit is contained in:
Antonio SJ Musumeci 2026-11-21 14:34:26 -05:00
parent 844e1acffd
commit b367b593ba
8 changed files with 152 additions and 48 deletions

View file

@ -118,7 +118,14 @@ A number of policies require looking up the available space of the
branches being considered. This is accomplished by calling
[statfs](https://man7.org/linux/man-pages/man2/statfs.2.html). This
call however is a bit expensive so this cache reduces the overhead by
limiting how often the calls are actually made.
limiting how often the calls are actually made. Successful and failed
lookups are cached for the same timeout. A cached failure therefore
keeps the branch excluded from space-based create policies until the
timeout expires, even if the branch recovers sooner. The timeout
starts when the lookup finishes and is unaffected by changes to the
system clock.
Changing `cache.statfs` at runtime applies directly to subsequent policy
lookups; setting it to `0` bypasses cached results.
This will mean that if the available space of branches changed
somewhat rapidly there is a risk of `create` or `mkdir` calls made

View file

@ -20,6 +20,7 @@
#include "errno.hpp"
#include "fmt/core.h"
#include "fs_path.hpp"
#include "fs_statvfs_cache.hpp"
#include "nonstd/string.hpp"
#include "str.hpp"
#include "version.hpp"
@ -82,7 +83,7 @@ Config::Config()
cache_files_process_names(CACHE_FILES_PROCESS_NAMES_DEFAULT),
cache_negative_entry(0),
cache_readdir(false),
cache_statfs(0),
cache_statfs(fs::statvfs_cache_timeout),
cache_symlinks(false),
cache_writeback(false),
category(func),

View file

@ -118,7 +118,7 @@ public:
ConfigSet cache_files_process_names;
ConfigU64 cache_negative_entry;
ConfigBOOL cache_readdir;
ConfigU64 cache_statfs;
TFSRef<std::atomic<u64>> cache_statfs;
ConfigBOOL cache_symlinks;
ConfigBOOL cache_writeback;
Categories category;

View file

@ -21,27 +21,36 @@
#include "fs_statvfs.hpp"
#include "statvfs_util.hpp"
#include <atomic>
#include <chrono>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <unordered_map>
#include <sys/statvfs.h>
#include <time.h>
// The result of the last statvfs: the data, or the negative errno it
// failed with. `valid` is false until the first statvfs has run, so a
// freshly inserted entry is never taken for a fresh result whatever the
// timeout.
struct Element
{
u64 time;
struct statvfs st;
u64 time = 0;
bool valid = false;
int rv = 0;
struct statvfs st = {};
};
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.
// The timeout is changed at runtime (cache.statfs) while requests
// read it.
static std::shared_mutex g_cache_mutex;
static u64 g_timeout = 0;
std::atomic<u64> fs::statvfs_cache_timeout{0};
static statvfs_cache g_cache;
@ -49,60 +58,66 @@ static
u64
_get_time(void)
{
u64 rv;
rv = ::time(NULL);
return rv;
using namespace std::chrono;
return duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
}
u64
fs::statvfs_cache_timeout(void)
static
bool
_fresh(const Element &e_,
const u64 now_,
const u64 timeout_)
{
return g_timeout;
return (e_.valid && ((now_ - e_.time) <= timeout_));
}
void
fs::statvfs_cache_timeout(cu64 timeout_)
static
int
_result(const Element &e_,
struct statvfs *st_)
{
g_timeout = timeout_;
if(e_.rv < 0)
return e_.rv;
*st_ = e_.st;
return 0;
}
int
fs::statvfs_cache(const std::string &path_,
struct statvfs *st_)
{
u64 now;
u64 timeout;
if(g_timeout == 0)
timeout = statvfs_cache_timeout.load(std::memory_order_relaxed);
if(timeout == 0)
return fs::statvfs(path_,st_);
now = ::_get_time();
{
std::shared_lock<std::shared_mutex> lk(g_cache_mutex);
auto it = g_cache.find(path_);
if((it != g_cache.end()) && ((now - it->second.time) <= g_timeout))
{
*st_ = it->second.st;
return 0;
}
if((it != g_cache.end()) && ::_fresh(it->second,::_get_time(),timeout))
return ::_result(it->second,st_);
}
int rv = 0;
std::unique_lock<std::shared_mutex> lk(g_cache_mutex);
// Another caller may have refreshed the entry while we waited.
Element &e = g_cache[path_];
if((now - e.time) > g_timeout)
if(not ::_fresh(e,::_get_time(),timeout))
{
e.time = now;
rv = fs::statvfs(path_,&e.st);
// A failure is kept for the timeout like a success. Retrying it on
// every call would hold this lock for a slow failing branch,
// such as an unreachable network mount, one caller at a time.
// It is never stored as zeroed space.
e.rv = fs::statvfs(path_,&e.st);
e.time = ::_get_time();
e.valid = true;
}
*st_ = e.st;
return rv;
return ::_result(e,st_);
}
int

View file

@ -20,6 +20,8 @@
#include "base_types.h"
#include <atomic>
#include <sys/statvfs.h>
#include <string>
@ -27,10 +29,7 @@
namespace fs
{
u64
statvfs_cache_timeout(void);
void
statvfs_cache_timeout(cu64 timeout);
extern std::atomic<u64> statvfs_cache_timeout;
int
statvfs_cache(const std::string &path,

View file

@ -23,7 +23,6 @@
#include "fs_glob.hpp"
#include "fs_lsetxattr.hpp"
#include "fs_path.hpp"
#include "fs_statvfs_cache.hpp"
#include "num.hpp"
#include "policy_rv.hpp"
#include "str.hpp"
@ -73,7 +72,6 @@ _setxattr_ctrl_file(const char *attrname_,
size_t attrvalsize_,
const int flags_)
{
int rv;
std::string key;
if(!Config::is_mergerfs_xattr(attrname_))
@ -91,13 +89,7 @@ _setxattr_ctrl_file(const char *attrname_,
if((flags_ & XATTR_CREATE) == XATTR_CREATE)
return -EEXIST;
rv = cfg.set(key,std::string{attrval_,attrvalsize_});
if(rv < 0)
return rv;
fs::statvfs_cache_timeout(cfg.cache_statfs);
return rv;
return cfg.set(key,std::string{attrval_,attrvalsize_});
}
static

View file

@ -22,7 +22,6 @@
#include "fmt/core.h"
#include "fs_glob.hpp"
#include "fs_path.hpp"
#include "fs_statvfs_cache.hpp"
#include "hw_cpu.hpp"
#include "num.hpp"
#include "policy.hpp"

View file

@ -5,6 +5,7 @@
#include "fs_copyfile.hpp"
#include "fs_inode.hpp"
#include "fs_movefile_and_open.hpp"
#include "fs_statvfs_cache.hpp"
#include "from_string.hpp"
#include "fuse_link.hpp"
#include "fuse_readdir_factory.hpp"
@ -3875,6 +3876,93 @@ test_readdir_factory_rejects_oversized_counts()
TEST_CHECK(FUSE::ReadDirFactory::make("cor:99999999999") == nullptr);
}
// A failed statvfs is cached for the timeout like a success, but the
// cache must never serve a cached failure as a success.
void
test_statvfs_cache_failure_not_served_as_success()
{
int rv;
struct statvfs st;
const std::string path = "/nonexistent/mergerfs-statvfs-cache-test";
TEST_CHECK(cfg.set("cache.statfs","60") == 0);
rv = fs::statvfs_cache(path,&st);
TEST_CHECK(rv == -ENOENT);
TEST_MSG("first rv: %d",rv);
rv = fs::statvfs_cache(path,&st);
TEST_CHECK(rv == -ENOENT);
TEST_MSG("second rv: %d",rv);
TEST_CHECK(cfg.set("cache.statfs","0") == 0);
}
// A failure is kept for the timeout like a success, so a branch that
// fails slowly isn't asked again on every call. Create the directory
// after the first failure: a cached failure still shows ENOENT, an
// uncached call would succeed.
void
test_statvfs_cache_keeps_failure_for_timeout()
{
int rv;
struct statvfs st;
char tmp_template[] = "/tmp/mergerfs-test-statvfs-cache-XXXXXX";
if(::mkdtemp(tmp_template) == nullptr)
{
TEST_CHECK(false);
return;
}
const std::string path = std::string(tmp_template) + "/later";
TEST_CHECK(cfg.set("cache.statfs","60") == 0);
rv = fs::statvfs_cache(path,&st);
TEST_CHECK(rv == -ENOENT);
TEST_MSG("first rv: %d",rv);
TEST_CHECK(::mkdir(path.c_str(),0700) == 0);
// An invalid update must leave the cached result in force.
TEST_CHECK(cfg.set("cache.statfs","invalid") == -EINVAL);
rv = fs::statvfs_cache(path,&st);
TEST_CHECK(rv == -ENOENT);
TEST_MSG("cached rv: %d",rv);
TEST_CHECK(cfg.set("cache.statfs","0") == 0);
rv = fs::statvfs_cache(path,&st);
TEST_CHECK(rv == 0);
TEST_MSG("uncached rv: %d",rv);
::rmdir(path.c_str());
::rmdir(tmp_template);
}
// A timeout of at least the current time in seconds made a new entry
// look fresh before any statvfs had run, so every branch reported no
// free space and a failure was reported as success.
void
test_statvfs_cache_huge_timeout()
{
int rv;
struct statvfs st;
for(const u64 timeout : {(u64)4294967295ULL,(u64)~0ULL})
{
TEST_CHECK(cfg.set("cache.statfs",std::to_string(timeout)) == 0);
memset(&st,0,sizeof(st));
rv = fs::statvfs_cache("/",&st);
TEST_CHECK(rv == 0);
TEST_CHECK(st.f_blocks > 0);
TEST_MSG("timeout: %llu; rv: %d; blocks: %lu",
(unsigned long long)timeout,rv,(unsigned long)st.f_blocks);
rv = fs::statvfs_cache("/nonexistent/mergerfs-statvfs-huge-timeout",&st);
TEST_CHECK(rv == -ENOENT);
TEST_MSG("timeout: %llu; missing rv: %d",(unsigned long long)timeout,rv);
}
TEST_CHECK(cfg.set("cache.statfs","0") == 0);
}
void
test_hashset_put_and_size()
{
@ -4622,6 +4710,9 @@ TEST_LIST =
{"fs_movefile_and_open_same_branch",test_fs_movefile_and_open_same_branch},
{"fs_movefile_and_open_existing_path_policies",test_fs_movefile_and_open_existing_path_policies},
{"readdir_factory_rejects_oversized_counts",test_readdir_factory_rejects_oversized_counts},
{"statvfs_cache_failure_not_served_as_success",test_statvfs_cache_failure_not_served_as_success},
{"statvfs_cache_keeps_failure_for_timeout",test_statvfs_cache_keeps_failure_for_timeout},
{"statvfs_cache_huge_timeout",test_statvfs_cache_huge_timeout},
{"str_eq_nullptr",test_str_eq_nullptr},
{"str_startswith_char_nullptr",test_str_startswith_char_nullptr},
{"str_from_u64_suffixes",test_str_from_u64_suffixes},