diff --git a/mkdocs/docs/config/moveonenospc.md b/mkdocs/docs/config/moveonenospc.md index a1b54d75..10a8e55d 100644 --- a/mkdocs/docs/config/moveonenospc.md +++ b/mkdocs/docs/config/moveonenospc.md @@ -34,9 +34,16 @@ will: completed append is not duplicated. 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. If part of the write +already reached the file the bytes written are returned instead, as a +short write, as with a local filesystem. The exception is data the +kernel is flushing from its page cache (`cache.writeback` or dirty +`mmap` pages), including writeback on a direct-I/O handle. The kernel +cannot act on a short write for those pages, so the error is returned +and reaches `fsync`, `msync` or `close`. -If `moveonenospc` is disabled the underlying error will be returned. +If `moveonenospc` is disabled the underlying error will be returned, +or the bytes written if part of the write succeeded. NOTE: This feature has NO effect on policies. It ONLY applies to the literal write function. If the create function returns `ENOSPC` or the diff --git a/src/fuse_write.cpp b/src/fuse_write.cpp index d881d1e7..3304315b 100644 --- a/src/fuse_write.cpp +++ b/src/fuse_write.cpp @@ -45,6 +45,23 @@ _out_of_space(const ssize_t err_) (err_ == -EDQUOT)); } +// Bytes already written stay written. Report them as a short write, +// as a local filesystem does, rather than the error: a caller that +// retries the whole buffer would write them twice. +// +// Not for writes the kernel issues to flush its page cache (writeback +// cache, dirty mmap pages). It ignores the size in the reply and +// drops the pages, so a short count would lose the rest and hide the +// error. Only the error reaches fsync, msync and close. +static +ssize_t +_written_or_err(const ssize_t written_, + const ssize_t err_, + const bool short_ok_) +{ + return (((written_ > 0) && short_ok_) ? written_ : err_); +} + static int _move_and_pwrite(const char *buf_, @@ -82,13 +99,14 @@ _move_and_pwriten(char const *buf_, off_t const offset_, FileInfo *fi_, ssize_t const err_, - ssize_t const written_) + ssize_t const written_, + bool const short_ok_) { int err; ssize_t rv; if(cfg.moveonenospc.enabled == false) - return err_; + return ::_written_or_err(written_,err_,short_ok_); rv = fs::movefile_and_open_as_root(cfg.moveonenospc.policy, cfg.branches, @@ -96,12 +114,12 @@ _move_and_pwriten(char const *buf_, fi_->fusepath, fi_->fd); if(rv < 0) - return err_; + return ::_written_or_err(written_,err_,short_ok_); err = fs::dup2(rv,fi_->fd); fs::close(rv); if(err < 0) - return err_; + return ::_written_or_err(written_,err_,short_ok_); rv = fs::pwriten(fi_->fd, buf_ + written_, @@ -109,7 +127,7 @@ _move_and_pwriten(char const *buf_, offset_ + written_, &err); if(err < 0) - return err; + return ::_written_or_err(written_ + rv,err,short_ok_); return (written_ + rv); } @@ -146,8 +164,13 @@ _write(const fuse_req_ctx_t *ctx_, // `direct_io=true` ssize_t rv; + const bool short_ok = not ffi_->writepage; - if(fi->direct_io) + // Writeback must complete or fail regardless of the handle's cache + // mode. A direct handle therefore takes the full-write path whenever + // this request is a kernel page-cache flush rather than an application + // write, for which a positive short count remains valid. + if(fi->direct_io && !ffi_->writepage) { { std::shared_lock slk(fi->mutex); @@ -178,8 +201,8 @@ _write(const fuse_req_ctx_t *ctx_, if(err == 0) return written; - if(err && not ::_out_of_space(err)) - return err; + if(not ::_out_of_space(err)) + return ::_written_or_err(written,err,short_ok); std::unique_lock ulk(fi->mutex); // Re-check the remaining suffix under exclusive lock as another move @@ -192,10 +215,10 @@ _write(const fuse_req_ctx_t *ctx_, &err); if(err == 0) return written; - if(err && not ::_out_of_space(err)) - return err; + if(not ::_out_of_space(err)) + return ::_written_or_err(written,err,short_ok); - return ::_move_and_pwriten(buf_,count_,offset_,fi,err,written); + return ::_move_and_pwriten(buf_,count_,offset_,fi,err,written,short_ok); } } @@ -207,8 +230,17 @@ FUSE::write(const fuse_req_ctx_t *ctx_, off_t offset_) { ioprio::SetFrom iop(ctx_->pid); + int rv; - return ::_write(ctx_,ffi_,buf_,count_,offset_); + rv = ::_write(ctx_,ffi_,buf_,count_,offset_); + + // Linux writeback completion ignores a short reply's byte count. The + // full-write path above should make this unreachable except for a + // no-progress write without an error; never acknowledge a partial page. + if(ffi_->writepage && (rv >= 0) && ((size_t)rv < count_)) + return -EIO; + + return rv; } int diff --git a/tests/TEST_movefile_enospc b/tests/TEST_movefile_enospc index 3677de7f..061915b5 100755 --- a/tests/TEST_movefile_enospc +++ b/tests/TEST_movefile_enospc @@ -2,6 +2,7 @@ import contextlib import errno +import mmap import os import shutil import subprocess @@ -11,6 +12,7 @@ import tempfile from posix_parity import fail from posix_parity import find_fusermount from posix_parity import find_mergerfs +from posix_parity import mergerfs_get_option from posix_parity import mount_mergerfs from posix_parity import unmount_mergerfs @@ -23,6 +25,10 @@ class Skip(Exception): pass +class SubcaseSkip(Exception): + """An environmental skip which must not hide the other test cases.""" + + @contextlib.contextmanager def enospc_pool(options, extra_tmpfs=()): """Mount mergerfs over `source`, the `extra_tmpfs` (name, size) @@ -93,6 +99,11 @@ def check_relocated(branches, pool, expected): return 0 +def read_file(path): + with open(path, "rb") as stream: + return stream.read() + + def test_partial_append(): with enospc_pool("minfreespace=0,cache.files=full,cache.writeback=false,moveonenospc=mfs") as ( branches, pool, initial, @@ -111,6 +122,92 @@ def test_partial_append(): return check_relocated(branches, pool, initial + payload) +def test_partial_without_move(): + with enospc_pool("minfreespace=0,cache.files=full,cache.writeback=false,moveonenospc=false") as ( + branches, pool, initial, + ): + # Only one block fits. The bytes written before ENOSPC stay on + # disk, so the write must report them as a short write, not + # fail: a caller that retries the whole buffer would append + # them twice. + block_size = len(initial) + payload = bytes(range(256)) * (block_size // 64) + fd = os.open(os.path.join(pool, "target"), os.O_WRONLY | os.O_APPEND) + try: + try: + written = os.write(fd, payload) + except OSError as e: + return fail(f"append failed with {e.strerror} after writing a prefix") + finally: + os.close(fd) + if not 0 < written < len(payload): + return fail(f"append returned {written}, expected a short write") + with open(os.path.join(branches["source"], "target"), "rb") as stream: + actual = stream.read() + if actual != initial + payload[:written]: + return fail(f"source holds {len(actual)} bytes, expected {len(initial) + written}") + if holders(branches) != ["source"]: + return fail(f"target on {holders(branches)}, expected only source") + return 0 + + +def flush_errors(calls): + """Run each (name, function) and return the names that raised ENOSPC.""" + failed = [] + for name, call in calls: + try: + call() + except OSError as e: + if e.errno != errno.ENOSPC: + raise + failed.append(name) + return failed + + +def test_writeback_flush_reports_error(): + with enospc_pool("minfreespace=0,cache.files=full,cache.writeback=true,moveonenospc=false") as ( + branches, pool, initial, + ): + # The kernel flushes its page cache with writes whose reply size + # it ignores. The tail that doesn't fit is dropped, so the + # error has to reach fsync or close: a short count would hide it. + payload = bytes(range(1, 256)) * (len(initial) // 32) + failed = [] + fd = os.open(os.path.join(pool, "target"), os.O_WRONLY) + try: + failed += flush_errors([ + ("write", lambda: os.pwrite(fd, payload, len(initial))), + ("fsync", lambda: os.fsync(fd)), + ]) + finally: + failed += flush_errors([("close", lambda: os.close(fd))]) + if not failed: + return fail("write, fsync and close all succeeded but the data did not fit") + return 0 + + +def test_mmap_flush_reports_error(): + with enospc_pool("minfreespace=0,cache.files=full,cache.writeback=false,moveonenospc=false") as ( + branches, pool, initial, + ): + # Dirty shared mmap pages are flushed the same way even without + # writeback cache, so msync must report the error. + payload = bytes(range(1, 256)) * (len(initial) // 32) + total = len(initial) + len(payload) + failed = [] + fd = os.open(os.path.join(pool, "target"), os.O_RDWR) + try: + os.ftruncate(fd, total) + with mmap.mmap(fd, total) as mapping: + mapping[len(initial):] = payload + failed += flush_errors([("msync", mapping.flush), ("fsync", lambda: os.fsync(fd))]) + finally: + failed += flush_errors([("close", lambda: os.close(fd))]) + if not failed: + return fail("msync, fsync and close all succeeded but the data did not fit") + return 0 + + def test_second_relocation(): # lfs over branches with at least minfreespace free picks `middle` # first; once it fills too only `destination` is left. The same open @@ -186,22 +283,86 @@ def test_occupied_destination(): return 0 +def test_direct_mmap_flush_reports_error(): + # Exercise actual shared-mmap writeback through a direct-I/O handle on + # kernels which negotiated FUSE_DIRECT_IO_ALLOW_MMAP. Older kernels skip + # only this subcase; the callback contract is tested separately. + options = ("minfreespace=0,cache.files=off,cache.writeback=false," + "moveonenospc=false,direct-io-allow-mmap=true") + with enospc_pool(options) as (branches, pool, initial): + negotiated = mergerfs_get_option(pool, "direct-io-allow-mmap").strip().lower() + if negotiated != "true": + raise SubcaseSkip("kernel did not negotiate direct-I/O shared mmap") + block = len(initial) + payload = (bytes(range(1, 256)) * ((2 * block + 254) // 255))[:2 * block] + total = len(initial) + len(payload) + failed = [] + fd = os.open(os.path.join(pool, "target"), os.O_RDWR) + try: + os.ftruncate(fd, total) + with mmap.mmap(fd, total, flags=mmap.MAP_SHARED, + prot=mmap.PROT_READ | mmap.PROT_WRITE) as mapping: + mapping[len(initial):] = payload + failed += flush_errors([("msync", mapping.flush), + ("fsync", lambda: os.fsync(fd))]) + finally: + failed += flush_errors([("close", lambda: os.close(fd))]) + if not failed: + return fail("direct shared mmap writeback acknowledged data which did not fit") + + # Only one payload block fits, but writeback order is a kernel choice. + # Check every byte without assuming that the first payload block won: + # each position is either still sparse zero or its expected byte, and + # no more than one of the two payload blocks may contain written data. + actual = read_file(os.path.join(branches["source"], "target")) + if len(actual) != total or actual[:block] != initial: + return fail("direct shared mmap writeback changed the original bytes or file size") + changed_blocks = 0 + suffix = actual[block:] + for offset in range(0, len(payload), block): + actual_chunk = suffix[offset:offset + block] + expected_chunk = payload[offset:offset + block] + if any(value not in (0, expected) + for value, expected in zip(actual_chunk, expected_chunk)): + return fail("direct shared mmap writeback persisted unexpected bytes") + if any(actual_chunk): + changed_blocks += 1 + if changed_blocks > 1: + return fail("direct shared mmap writeback used more than the one free block") + if read_file(os.path.join(pool, "target")) != actual: + return fail("direct shared mmap writeback differs after close/reopen") + if holders(branches) != ["source"]: + return fail(f"target on {holders(branches)}, expected only source") + return 0 + + TESTS = (test_partial_append, + test_partial_without_move, + test_writeback_flush_reports_error, + test_mmap_flush_reports_error, test_second_relocation, - test_occupied_destination) + test_occupied_destination, + test_direct_mmap_flush_reports_error) def main(): if len(sys.argv) == 2 and sys.argv[1] == "--isolated": + subcase_skips = 0 for test in TESTS: try: rv = test() + except SubcaseSkip as e: + subcase_skips += 1 + print(f"SKIP {test.__name__}: {e}") + continue except Skip as e: print(e, end="") return SKIP if rv: print(f" ({test.__name__})", end="") return rv + if subcase_skips: + print(f"{subcase_skips} environmental subcase(s) skipped; all others ran") return 0 if find_mergerfs() is None or find_fusermount() is None: diff --git a/tests/tests.cpp b/tests/tests.cpp index ea922dac..28f3b475 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -1,6 +1,7 @@ #include "acutest/acutest.h" #include "config.hpp" +#include "fileinfo.hpp" #include "fs_clonepath.hpp" #include "fs_copyfile.hpp" #include "fs_inode.hpp" @@ -11,17 +12,21 @@ #include "fuse_readdir_factory.hpp" #include "fuse_rename.hpp" #include "fuse_symlink.hpp" +#include "fuse_write.hpp" #include "hashset.hpp" #include "num.hpp" #include "policies.hpp" #include "rapidhash/rapidhash.h" #include "rnd.hpp" +#include "scope_guard/scope_guard.hpp" #include "str.hpp" #include "thread_pool.hpp" #include #include #include +#include +#include #include #include #include @@ -35,10 +40,53 @@ #include #include +#include #include #include #include +void +test_direct_handle_writepage_error() +{ + // Exercise the real callback even on kernels without direct-I/O shared mmap. + // The file-size limit makes pwrite accept a prefix, then reject the suffix. + FILE *file = std::tmpfile(); + TEST_ASSERT(file != nullptr); + DEFER { std::fclose(file); }; + const int fd = ::fileno(file); + TEST_ASSERT(fd >= 0); + + struct rlimit saved; + TEST_ASSERT(::getrlimit(RLIMIT_FSIZE,&saved) == 0); + constexpr size_t prefix = 4096; + TEST_ASSERT(saved.rlim_max >= prefix); + struct sigaction ignore = {}, prev; + ignore.sa_handler = SIG_IGN; + ::sigemptyset(&ignore.sa_mask); + TEST_ASSERT(::sigaction(SIGXFSZ,&ignore,&prev) == 0); + DEFER { ::sigaction(SIGXFSZ,&prev,nullptr); }; + struct rlimit limit = saved; + limit.rlim_cur = prefix; + TEST_ASSERT(::setrlimit(RLIMIT_FSIZE,&limit) == 0); + DEFER { ::setrlimit(RLIMIT_FSIZE,&saved); }; + + Branch branch; + FileInfo fi(fd,branch,"file",true); + fuse_req_ctx_t ctx = {}; + fuse_file_info_t ffi = {}; + ffi.fh = fi.to_fh(); + char data[2 * prefix]; + std::memset(data,'a',sizeof(data)); + TEST_CHECK(FUSE::write(&ctx,&ffi,data,sizeof(data),0) == (int)prefix); + TEST_ASSERT(::ftruncate(fd,0) == 0); + + ffi.writepage = 1; + TEST_CHECK(FUSE::write(&ctx,&ffi,data,sizeof(data),0) == -EFBIG); + char actual[sizeof(data)]; + TEST_ASSERT(::pread(fd,actual,sizeof(actual),0) == (ssize_t)prefix); + TEST_CHECK(std::memcmp(data,actual,prefix) == 0); +} + template bool wait_until(Predicate pred_, @@ -5034,6 +5082,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}, + {"direct_handle_writepage_error",test_direct_handle_writepage_error}, {"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},