From d679fdd265f2b4c379404fcbdde99be2e2b896a9 Mon Sep 17 00:00:00 2001 From: Antonio SJ Musumeci Date: Sat, 21 Nov 2026 14:33:27 -0500 Subject: [PATCH] fix: validate and cap thread and queue counts - std::stoi threw std::out_of_range for a func.readdir concurrency or queue depth above INT_MAX, e.g. cor:99999999999. Given at mount, mergerfs aborted. Set at runtime through .mergerfs, the daemon shut down and the mount went away, or with process-thread-count>0 the request never got a reply. Parse with str::from, which reports the overflow, and reject the value like any other malformed one. - Reject a readdir queue depth whose product with the concurrency overflows an int, e.g. cor:2147483647:2147483647, instead of wrapping it. - Limit read-thread-count, process-thread-count and the cor/cosr pool size to 64 threads per pool, after resolving automatic and CPU-divided counts, and log a warning when clamping. Resolve negative FUSE counts without overflowing on INT_MIN, and drop the unreachable negative readdir concurrency branch. - process-thread-queue-depth is multiplied by the process thread count. Saturate the product at INT_MAX instead of overflowing. - Correct the docs: cor/cosr counts accept digits only and 0 means the core count, at most 8; a queue depth of 0 means 2 per thread; read-thread-count=0 with process-thread-count=0 is 2 read threads and max(2, cores - 2) process threads, at most 8; the queue limit is depth times process threads, each read thread holding one in-flight buffer of its own. Point at threads.md for how the settings combine. - Document the per-read-thread /dev/fuse clones and their fallback. - tests.cpp covers the overflow cases. Performance: default thread counts are unchanged (8 on hosts with 8 or more cores). Only explicit or CPU-divided counts above 64, which 2.42.0 honored, are reduced. --- mkdocs/docs/config/func_readdir.md | 19 +++++++--- mkdocs/docs/config/options.md | 37 +++++++++++-------- mkdocs/docs/config/threads.md | 29 +++++++++++---- src/fuse_readdir_factory.cpp | 45 +++++++++++++++++------- tests/tests.cpp | 14 ++++++++ vendored/libfuse/include/thread_pool.hpp | 12 +++++++ vendored/libfuse/lib/fuse_loop.cpp | 31 ++++++++++++---- 7 files changed, 143 insertions(+), 44 deletions(-) diff --git a/mkdocs/docs/config/func_readdir.md b/mkdocs/docs/config/func_readdir.md index 1a928daf..0f65b50e 100644 --- a/mkdocs/docs/config/func_readdir.md +++ b/mkdocs/docs/config/func_readdir.md @@ -9,12 +9,23 @@ | Policy | Description | | ------ | ----------- | | seq | "sequential" : Iterate sequentially over branches in the order defined in `branches`. This is the default and traditional behavior found prior to the readdir policy introduction. This will be increasingly slower as more branches are added to the pool. Especially if needing to wait for drives to spin up or network filesystems to respond. | -| 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. If negative it will be the core count divided by `abs(N)`. `M` is the queue depth. If either value is `0` it will be decided based on system configuration. | +| 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. If negative it will be the core count divided by `abs(N)`. `M` is the queue depth. If either value is `0` it will be decided based on system configuration. | -| cor:N | cosr:N:M with M = 0 | -| cor | 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 | cor:N:M with M = 0 | +| cor | cor:N:M with N = 0 and M = 0 | + +For `cor` and `cosr`, write `N` and `M` as decimal digits only (no sign), +from 0 through `INT_MAX` (2147483647). Out-of-range values are rejected, +not clamped. A valid thread count above 64 is clamped to 64 with a syslog +warning (`LOG_WARNING`); the cap does not apply to the per-thread queue +depth. After defaults and the thread cap are applied, `N * M` must fit in +`INT_MAX` or the entire setting is rejected; the queue depth is not saturated. + +For example, `cor:65:2` uses 64 threads and 128 queue slots. `cor:4294967296` +is rejected because the count is out of range; `cor:64:34000000` is rejected +because its total queue depth exceeds `INT_MAX`. 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 diff --git a/mkdocs/docs/config/options.md b/mkdocs/docs/config/options.md index e26535b9..702d325a 100644 --- a/mkdocs/docs/config/options.md +++ b/mkdocs/docs/config/options.md @@ -136,25 +136,28 @@ config file. use. When used alone (`process-thread-count=-1`) it sets the number of threads reading and processing FUSE messages. When used together it sets the number of threads reading from FUSE. When set to zero it - will attempt to discover and use the number of logical cores. If the - thread count is set negative it will look up the number of cores - then divide by the absolute value. ie. threads=-2 on an 8 core - machine will result in 8 / 2 = 4 threads. There will always be at - least 1 thread. If set to -1 in combination with - `process-thread-count` then it will try to pick reasonable values - based on CPU thread count. NOTE: higher number of threads increases + uses the number of logical cores, up to 8, or 2 read threads when + `process-thread-count` is enabled as well. If the thread count is set + negative it will look up the number of cores then divide by the + absolute value. ie. threads=-2 on an 8 core machine will result in + 8 / 2 = 4 threads. There will always be at least 1 thread and at + most 64, including counts resolved from automatic or negative + settings. Counts above 64 are clamped with a syslog warning + (`LOG_WARNING`). See [threads](threads.md) for how it combines with + `process-thread-count`. NOTE: higher number of threads increases parallelism but usually decreases throughput. (default: 0) * **[process-thread-count](threads.md)=INT**: Enables separate thread pool to asynchronously process FUSE requests. In this mode `read-thread-count` refers to the number of threads reading FUSE messages which are dispatched to process threads. -1 means disabled - otherwise acts like `read-thread-count`. (default: -1) + otherwise acts like `read-thread-count`, including the 64-thread cap + and warning when clamped. (default: -1) * **[process-thread-queue-depth](threads.md)=UINT**: Sets the number of requests any single process thread can have queued up at one - time. Meaning the total memory usage of the queues is queue depth - multiplied by the number of process threads plus read thread - count. 0 sets the depth to the same as the process thread - count. (default: 2) + time. Meaning the queue capacity is the queue depth multiplied by + the number of process threads, and each read thread additionally + holds one in-flight message buffer. 0 sets the depth to 2. Queue + depths are not capped to 64. (default: 2) * **[pin-threads](pin-threads.md)=STR**: Selects a strategy to pin threads to CPUs (default: unset) * **[flush-on-close](flush-on-close.md)=never|always|opened-for-write**: @@ -171,9 +174,13 @@ config file. * **[func.FUNC](functions_categories_policies.md)=POLICY**: Sets the specific FUSE function's policy. See below for the list of value types. Example: **func.getattr=newest** -* **[func.readdir](func_readdir.md)=seq|cosr|cor|cosr:INT|cor:INT**: - Sets `readdir` policy. INT value sets the number of threads to use - for concurrency. (default: seq) +* **[func.readdir](func_readdir.md)**: `seq` (default), `cosr[:N[:M]]`, + or `cor[:N[:M]]`. `N` (threads) and `M` (queue slots per thread) accept + decimal digits only. Values above `INT_MAX` (2147483647) are rejected. + Omitted or zero values use the core count (at most 8) for `N` and 2 for `M`. Valid + thread counts above 64 are clamped to 64 with a syslog warning; `M` is + not capped at 64. If the effective `N * M` exceeds `INT_MAX`, the entire + setting is rejected. * **[category.action](functions_categories_policies.md)=POLICY**: Sets policy of all FUSE functions in the action category. (default: epall) diff --git a/mkdocs/docs/config/threads.md b/mkdocs/docs/config/threads.md index 29f2985a..7ae204f3 100644 --- a/mkdocs/docs/config/threads.md +++ b/mkdocs/docs/config/threads.md @@ -3,6 +3,13 @@ There are multiple thread pools used in mergerfs to provide parallel behaviors. +Each thread pool is limited to 64 threads. This applies to +`read-thread-count`, `process-thread-count` and the pool size in +[func.readdir](func_readdir.md). Counts resolved from automatic or +negative settings are also capped. When an applied setting exceeds +the limit, mergerfs reduces the count to 64 and logs a syslog warning +(`LOG_WARNING`). Queue depths are not capped to 64. + ## read-thread-count @@ -23,10 +30,16 @@ throughput. Create a read+process thread pool of `CPUCount / -N` threads. Minimum of `1`. * `read-thread-count=0` and `process-thread-count=0`: Create `2` read - threads and a process thread per logical CPU core upto `8`. + threads and a process thread pool of `CPUCount - 2` threads. + Minimum of `2`, maximum of `8`. * `read-thread-count=0` and `process-thread-count!=-1`: Creates `2` read threads and number of process threads as defined below. +When there is more than one read thread, each thread reads from its +own clone of the `/dev/fuse` descriptor when the kernel supports the +`FUSE_DEV_IOC_CLONE` ioctl. If cloning fails mergerfs logs a warning +and the read threads share one descriptor. + ## process-thread-count @@ -35,8 +48,12 @@ Defaults to `-1` When enabled this sets the number of threads in the message processing pool. * `process-thread-count=-1`: Process thread pool is disabled. -* `process-thread-count=0`: Create `1` thread process thread per - logical CPU core upto `8`. +* `process-thread-count=0`: With the default `read-thread-count=0` + this follows the combined rule under `read-thread-count` above: + `2` read threads and a process thread pool of `CPUCount - 2` + threads, minimum `2`, maximum `8`. With a nonzero + `read-thread-count` it creates a process thread pool of + `CPUCount` threads capped at `8` (minimum `1`). * `process-thread-count=N` where `N>0`: Create a thread pool of `N` threads. * `process-thread-count=N` where `N<-1`: Create a thread pool of `CPUCount / -N` threads. Minimum of 1. @@ -54,8 +71,8 @@ in the pool. * `process-thread-queue-depth=N` where `N>0`: Sets the number of outstanding requests that the process thread pool can have to `N * - process-thread-count`. If requests come in faster than can be - processed and the max queue depth hit then queuing the request will - block in order to limit memory growth. + process-thread-count`, at most 2147483647. If requests come in + faster than can be processed and the max queue depth hit then + queuing the request will block in order to limit memory growth. * `process-thread-queue-depth<=0`: Sets the queue depth to 2. May be used in the future to set dynamically. diff --git a/src/fuse_readdir_factory.cpp b/src/fuse_readdir_factory.cpp index 5039e4ce..055bb13b 100644 --- a/src/fuse_readdir_factory.cpp +++ b/src/fuse_readdir_factory.cpp @@ -22,11 +22,16 @@ #include "fuse_readdir_cosr.hpp" #include "fuse_readdir_seq.hpp" +#include "from_string.hpp" +#include "syslog.hpp" +#include "thread_pool.hpp" + +#include #include #include -#include #include #include +#include #include // Regex: @@ -39,7 +44,8 @@ void _read_cfg(const std::string_view str_, std::string &type_, int &concurrency_, - int &max_queue_depth_) + int &max_queue_depth_, + const bool warn_) { std::string type; int concurrency; @@ -56,11 +62,18 @@ _read_cfg(const std::string_view str_, re); if(matched) { - type = match[1]; + int rv = 0; + + // A count too large for an int leaves type empty, so the value + // is rejected as invalid instead of throwing. if(match[2].matched) - concurrency = std::stoi(match[2]); - if(match[3].matched) - max_queue_depth = std::stoi(match[3]); + rv = str::from(std::string_view(match[2].first,match[2].length()), + &concurrency); + if((rv == 0) && match[3].matched) + rv = str::from(std::string_view(match[3].first,match[3].length()), + &max_queue_depth); + if(rv == 0) + type = match[1]; } if(concurrency == 0) @@ -69,18 +82,24 @@ _read_cfg(const std::string_view str_, if(concurrency > 8) concurrency = 8; } - else if(concurrency < 0) - { - concurrency = (std::thread::hardware_concurrency() / std::abs(concurrency)); - } if(concurrency <= 0) concurrency = 1; + const bool clamped = (concurrency > ThreadPool::max_thread_count()); + concurrency = std::min(concurrency,ThreadPool::max_thread_count()); if(max_queue_depth <= 0) max_queue_depth = 2; - max_queue_depth *= concurrency; + // Reject a queue depth whose product overflows instead of wrapping. + if(max_queue_depth > (std::numeric_limits::max() / concurrency)) + type.clear(); + else + max_queue_depth *= concurrency; + + if(warn_ && clamped && ((type == "cor") || (type == "cosr"))) + SysLog::warning("func.readdir={} exceeds the thread limit; clamping to {} threads", + str_,ThreadPool::max_thread_count()); type_ = type; concurrency_ = concurrency; @@ -94,7 +113,7 @@ FUSE::ReadDirFactory::valid(const std::string_view str_) int max_queue_depth; std::string type; - ::_read_cfg(str_,type,concurrency,max_queue_depth); + ::_read_cfg(str_,type,concurrency,max_queue_depth,false); return ((type == "seq") || (type == "cosr") || @@ -108,7 +127,7 @@ FUSE::ReadDirFactory::make(const std::string_view str_) int max_queue_depth; std::string type; - ::_read_cfg(str_,type,concurrency,max_queue_depth); + ::_read_cfg(str_,type,concurrency,max_queue_depth,true); if(type == "seq") return std::make_shared(); diff --git a/tests/tests.cpp b/tests/tests.cpp index a4cbb84e..d1ccf796 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -7,6 +7,7 @@ #include "fs_movefile_and_open.hpp" #include "from_string.hpp" #include "fuse_link.hpp" +#include "fuse_readdir_factory.hpp" #include "fuse_rename.hpp" #include "fuse_symlink.hpp" #include "hashset.hpp" @@ -3862,6 +3863,18 @@ test_fs_movefile_and_open_existing_path_policies() std::filesystem::remove_all(tmp_dir); } +// Counts that don't fit an int, or whose queue depth product +// overflows, must be rejected rather than throw or wrap. +void +test_readdir_factory_rejects_oversized_counts() +{ + TEST_CHECK(FUSE::ReadDirFactory::valid("cor:4:2")); + TEST_CHECK(!FUSE::ReadDirFactory::valid("cor:99999999999")); + TEST_CHECK(!FUSE::ReadDirFactory::valid("cosr:2:99999999999")); + TEST_CHECK(!FUSE::ReadDirFactory::valid("cor:2147483647:2147483647")); + TEST_CHECK(FUSE::ReadDirFactory::make("cor:99999999999") == nullptr); +} + void test_hashset_put_and_size() { @@ -4608,6 +4621,7 @@ TEST_LIST = {"fs_copyfile_source_changes_cleanup_tmpfiles",test_fs_copyfile_source_changes_cleanup_tmpfiles}, {"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}, {"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}, diff --git a/vendored/libfuse/include/thread_pool.hpp b/vendored/libfuse/include/thread_pool.hpp index d32061d5..1f57c7ad 100644 --- a/vendored/libfuse/include/thread_pool.hpp +++ b/vendored/libfuse/include/thread_pool.hpp @@ -110,6 +110,9 @@ public: std::future> enqueue_task(FuncType&& func_); +public: + static constexpr int max_thread_count(); + public: std::vector threads() const; ThreadPool::PToken ptoken(); @@ -125,6 +128,15 @@ private: +// Cap configured pools to bound their memory and thread creation costs. +inline +constexpr int +ThreadPool::max_thread_count() +{ + return 64; +} + + inline ThreadPool::ThreadPool(const unsigned thread_count_, const unsigned max_queue_depth_, diff --git a/vendored/libfuse/lib/fuse_loop.cpp b/vendored/libfuse/lib/fuse_loop.cpp index ed57c2d8..6f84980e 100644 --- a/vendored/libfuse/lib/fuse_loop.cpp +++ b/vendored/libfuse/lib/fuse_loop.cpp @@ -17,6 +17,7 @@ #include "fuse_msgbuf.hpp" #include +#include #include #include @@ -198,7 +199,8 @@ struct SyncWorker static int -_calculate_thread_count(const int raw_thread_count_) +_calculate_thread_count(const int raw_thread_count_, + const char *option_) { int thread_count = 1; @@ -209,7 +211,7 @@ _calculate_thread_count(const int raw_thread_count_) } else if(raw_thread_count_ < 0) { - thread_count = (::_nproc() / -raw_thread_count_); + thread_count = (::_nproc() / -(long long)raw_thread_count_); thread_count = std::max(1,thread_count); } else if(raw_thread_count_ > 0) @@ -217,6 +219,14 @@ _calculate_thread_count(const int raw_thread_count_) thread_count = raw_thread_count_; } + if(thread_count > ThreadPool::max_thread_count()) + { + SysLog::warning("{}={} requests {} threads; limiting pool to {}", + option_,raw_thread_count_,thread_count, + ThreadPool::max_thread_count()); + thread_count = ThreadPool::max_thread_count(); + } + return thread_count; } @@ -245,19 +255,28 @@ _calculate_thread_counts(int *read_thread_count_, else if((*read_thread_count_ == 0) && (*process_thread_count_ != -1)) { *read_thread_count_ = 2; - *process_thread_count_ = ::_calculate_thread_count(*process_thread_count_); + *process_thread_count_ = ::_calculate_thread_count(*process_thread_count_, + "process-thread-count"); } else { - *read_thread_count_ = ::_calculate_thread_count(*read_thread_count_); + *read_thread_count_ = ::_calculate_thread_count(*read_thread_count_, + "read-thread-count"); if(*process_thread_count_ != -1) - *process_thread_count_ = ::_calculate_thread_count(*process_thread_count_); + *process_thread_count_ = ::_calculate_thread_count(*process_thread_count_, + "process-thread-count"); } if(*process_thread_queue_depth_ <= 0) *process_thread_queue_depth_ = 2; - *process_thread_queue_depth_ *= std::abs(*process_thread_count_); + // Saturate rather than overflow. A total this large is unbounded in + // practice anyway since the queue only counts free slots. + if(*process_thread_queue_depth_ > + (std::numeric_limits::max() / std::abs(*process_thread_count_))) + *process_thread_queue_depth_ = std::numeric_limits::max(); + else + *process_thread_queue_depth_ *= std::abs(*process_thread_count_); } int