#include "FileWorkers.hpp" #include #include #include #include #include #include #include #include #if defined(__unix__) || defined(__APPLE__) #include #include #include #define VOID_IO_POSIX_FILES 1 #endif namespace Void::IO { namespace { thread_local const detail::FileWorkerShared* tl_io_worker_owner = nullptr; } // namespace bool is_io_worker_thread() noexcept { return tl_io_worker_owner != nullptr; } // ── FileSyscalls (native) ──────────────────────────────────────────────────── FileSyscallResult FileSyscalls::pread(int fd, std::span buf, std::uint64_t offset) noexcept { #ifdef VOID_IO_POSIX_FILES const ssize_t n = ::pread(fd, buf.data(), buf.size(), static_cast(offset)); if (n < 0) { return FileSyscallResult{-1, errno}; } return FileSyscallResult{static_cast(n), 0}; #else (void)fd; (void)buf; (void)offset; return FileSyscallResult{-1, ENOSYS}; #endif } FileSyscallResult FileSyscalls::pwrite(int fd, std::span buf, std::uint64_t offset) noexcept { #ifdef VOID_IO_POSIX_FILES const ssize_t n = ::pwrite(fd, buf.data(), buf.size(), static_cast(offset)); if (n < 0) { return FileSyscallResult{-1, errno}; } return FileSyscallResult{static_cast(n), 0}; #else (void)fd; (void)buf; (void)offset; return FileSyscallResult{-1, ENOSYS}; #endif } FileSyscallResult FileSyscalls::sync(int fd, SyncMode mode) noexcept { #ifdef VOID_IO_POSIX_FILES int rc = 0; #if defined(__linux__) rc = (mode == SyncMode::data) ? ::fdatasync(fd) : ::fsync(fd); #else (void)mode; rc = ::fsync(fd); #endif if (rc != 0) { return FileSyscallResult{-1, errno}; } return FileSyscallResult{0, 0}; #else (void)fd; (void)mode; return FileSyscallResult{-1, ENOSYS}; #endif } FileSyscallResult FileSyscalls::close(int fd) noexcept { #ifdef VOID_IO_POSIX_FILES if (::close(fd) != 0) { return FileSyscallResult{-1, errno}; } return FileSyscallResult{0, 0}; #else (void)fd; return FileSyscallResult{-1, ENOSYS}; #endif } FileSyscalls& FileSyscalls::native() noexcept { static FileSyscalls instance; return instance; } } // namespace Void::IO namespace Void::IO::detail { namespace { [[nodiscard]] std::error_code errno_code(int err) noexcept { return std::error_code{err, std::generic_category()}; } void worker_main(std::shared_ptr shared) noexcept { tl_io_worker_owner = shared.get(); FileWorkerShared& p = *shared; std::unique_lock lk{p.mu}; for (;;) { p.work_cv.wait(lk, [&p] { return p.exit_requested || p.rollback_requested || p.has_runnable_locked(); }); if (p.exit_requested || p.rollback_requested) { break; } bool settled = false; std::shared_ptr req = p.take_next_locked(settled); if (!req) { if (settled) { lk.unlock(); p.wake(); lk.lock(); } continue; } lk.unlock(); const FileSyscallResult result = execute_file_request(*req); lk.lock(); p.finish_locked(*req, result); const bool idle = p.active.empty(); // `completions` still owns the request, so this never destroys it. req.reset(); lk.unlock(); p.work_cv.notify_all(); if (idle) { p.idle_cv.notify_all(); } p.wake(); lk.lock(); } if (p.running_workers > 0) { --p.running_workers; } p.publish_counts_locked(); lk.unlock(); p.idle_cv.notify_all(); tl_io_worker_owner = nullptr; } } // namespace const FileWorkerShared* current_io_worker_owner() noexcept { return tl_io_worker_owner; } // ── FileState ──────────────────────────────────────────────────────────────── FileState::FileState(std::shared_ptr pool_in, std::weak_ptr backend_in, FileSyscalls* syscalls_in, int fd_in, DescriptorId id_in) : pool(std::move(pool_in)) , backend(std::move(backend_in)) , syscalls(syscalls_in) , id(id_in) , fd(fd_in) { auto close_req = std::make_shared(); close_req->kind = FileRequestKind::close; close_node.push_back(std::move(close_req)); } // ── FileWorkerShared ───────────────────────────────────────────────────────── void FileWorkerShared::publish_counts_locked() noexcept { queued_count.store(queued.size(), std::memory_order_release); active_count.store(active.size(), std::memory_order_release); running_count.store(running_workers, std::memory_order_release); } bool FileWorkerShared::has_runnable_locked() const noexcept { if (!close_queued.empty()) { return true; } for (const auto& r : queued) { if (r->stop_requested || r->expired) { return true; } if (!r->serialized() || !r->file->serial_active) { return true; } } return false; } std::shared_ptr FileWorkerShared::take_next_locked(bool& settled_without_syscall) noexcept { settled_without_syscall = false; if (exit_requested || rollback_requested) { return nullptr; } if (!close_queued.empty()) { auto it = close_queued.begin(); std::shared_ptr req = *it; active.splice(active.end(), close_queued, it); req->phase = FileRequestPhase::active; req->exec_fd = req->file ? req->file->fd : -1; publish_counts_locked(); return req; } for (auto it = queued.begin(); it != queued.end();) { FileRequest& r = **it; auto next = std::next(it); if (r.stop_requested || r.expired) { // S3: decided under the mutex from flags set by the stop callback or // by the last poll turn; the clock is never read on a worker. settle_queued_locked(r, r.expired ? FileSettle::timeout : FileSettle::cancelled); settled_without_syscall = true; it = next; continue; } if (r.serialized() && r.file->serial_active) { it = next; continue; } if (r.serialized()) { r.file->serial_active = true; } std::shared_ptr req = *it; active.splice(active.end(), queued, it); r.phase = FileRequestPhase::active; r.exec_fd = r.file->fd; publish_counts_locked(); return req; } return nullptr; } void FileWorkerShared::finish_locked(FileRequest& req, FileSyscallResult result) noexcept { req.result = result; req.settle = FileSettle::syscall; req.phase = FileRequestPhase::done; if (req.file) { FileState& f = *req.file; if (req.serialized()) { f.serial_active = false; } if (req.kind == FileRequestKind::close) { // Whoever closes the fd marks the file closed. Linux closes the fd // even when close() reports EINTR, so that is not an error. f.status = FileState::Status::closed; f.fd = -1; f.close_error = (result.error == EINTR) ? 0 : result.error; } } completions.splice(completions.end(), active, req.pos); publish_counts_locked(); } void FileWorkerShared::settle_queued_locked(FileRequest& req, FileSettle settle) noexcept { FileRequestList& from = (req.kind == FileRequestKind::close) ? close_queued : queued; req.settle = settle; req.phase = FileRequestPhase::done; if (settle == FileSettle::timeout) { req.expired = true; } completions.splice(completions.end(), from, req.pos); publish_counts_locked(); } void FileWorkerShared::enqueue_close_locked(FileState& file) noexcept { if (file.close_enqueued || file.close_node.empty()) { return; } std::shared_ptr self = file.weak_from_this().lock(); if (!self) { return; } file.close_enqueued = true; file.close_pending = false; auto it = file.close_node.begin(); FileRequest& req = **it; req.file = std::move(self); req.phase = FileRequestPhase::queued; close_queued.splice(close_queued.end(), file.close_node, it); req.pos = it; publish_counts_locked(); } // ── Forwarders ─────────────────────────────────────────────────────────────── void FileCancelForwarder::operator()() const noexcept { auto req = request.lock(); if (!req || !req->file) { return; } FileWorkerShared& pool = *req->file->pool; bool removed = false; { std::lock_guard lk{pool.mu}; req->stop_requested = true; if (req->phase == FileRequestPhase::queued && req->kind != FileRequestKind::close) { pool.settle_queued_locked(*req, FileSettle::cancelled); removed = true; } } if (removed) { if (auto b = req->file->backend.lock()) { b->wake(); } } } void FileWakeForwarder::operator()() const noexcept { if (auto b = backend.lock()) { b->wake(); } } // ── Execution ──────────────────────────────────────────────────────────────── FileSyscallResult execute_file_request(const FileRequest& req) noexcept { FileSyscalls& sys = (req.file && req.file->syscalls != nullptr) ? *req.file->syscalls : FileSyscalls::native(); const int fd = req.exec_fd; for (;;) { FileSyscallResult r{}; switch (req.kind) { case FileRequestKind::read: r = sys.pread(fd, std::span{req.read_ptr, req.len}, req.offset); break; case FileRequestKind::write: r = sys.pwrite(fd, std::span{req.write_ptr, req.len}, req.offset); break; case FileRequestKind::sync: r = sys.sync(fd, req.mode); break; case FileRequestKind::close: // Never retried: the descriptor is released even on EINTR. return sys.close(fd); } if (r.error == EINTR) { continue; } return r; } } std::optional run_file_requests_inline(FileWorkerShared& shared, std::size_t max_requests) { std::unique_lock lk{shared.mu}; if (shared.running_workers > 0) { return std::nullopt; } std::size_t done = 0; while (done < max_requests) { bool settled = false; std::shared_ptr req = shared.take_next_locked(settled); if (!req) { break; } lk.unlock(); const FileSyscallResult result = execute_file_request(*req); lk.lock(); shared.finish_locked(*req, result); req.reset(); ++done; } const bool idle = shared.active.empty(); lk.unlock(); if (idle) { shared.idle_cv.notify_all(); } return done; } void file_handle_dropped(FileState& file) noexcept { FileWorkerShared& pool = *file.pool; bool enqueued = false; { std::lock_guard lk{pool.mu}; if (file.status == FileState::Status::closed) { return; } if (file.status == FileState::Status::open) { file.status = FileState::Status::closing; } if (!file.close_enqueued) { if (file.in_flight == 0) { pool.enqueue_close_locked(file); enqueued = true; } else { file.close_pending = true; } } } if (enqueued) { pool.work_cv.notify_one(); if (auto b = file.backend.lock()) { b->wake(); } } } // ── Open helpers ───────────────────────────────────────────────────────────── Void::Result::Result validate_file_open_options(const FileOpenOptions& options) { if (!options.read && !options.write) { return std::unexpected{make_io_error( IoErrorCode::invalid_argument, "FileOpenOptions needs read or write access")}; } if (options.truncate && !options.write) { return std::unexpected{make_io_error( IoErrorCode::invalid_argument, "FileOpenOptions::truncate requires write")}; } if (options.exclusive && !options.create) { return std::unexpected{make_io_error( IoErrorCode::invalid_argument, "FileOpenOptions::exclusive requires create")}; } return {}; } Void::Result::Result open_file_native(const std::filesystem::path& path, const FileOpenOptions& options) { #ifdef VOID_IO_POSIX_FILES int flags = O_CLOEXEC; if (options.read && options.write) { flags |= O_RDWR; } else if (options.write) { flags |= O_WRONLY; } else { flags |= O_RDONLY; } if (options.create) { flags |= O_CREAT; } if (options.truncate) { flags |= O_TRUNC; } if (options.exclusive) { flags |= O_EXCL; } int fd = -1; for (;;) { fd = ::open(path.c_str(), flags, static_cast(options.mode)); if (fd < 0 && errno == EINTR) { continue; } break; } if (fd < 0) { return std::unexpected{make_io_error( IoErrorCode::os_error, "open failed for " + path.string(), errno_code(errno))}; } return fd; #else (void)path; (void)options; return std::unexpected{make_io_error( IoErrorCode::unsupported, "Positional files require a POSIX platform")}; #endif } // ── FileWorkers ────────────────────────────────────────────────────────────── FileWorkers::~FileWorkers() { for (const auto& t : threads_) { if (t.joinable()) { std::fputs( "Void::IO: file worker still running at backend destruction " "(Driver teardown did not join it)\n", stderr); std::terminate(); } } } Void::Result::Result FileWorkers::start( std::size_t count, const std::function(std::size_t)>& hook) { std::lock_guard tl{threads_mu_}; if (started_) { return std::unexpected{make_io_error( IoErrorCode::invalid_argument, "start_file_workers was already called")}; } { std::lock_guard lk{shared_->mu}; if (!shared_->accepting || shared_->exit_requested) { return std::unexpected{make_io_error( IoErrorCode::closed, "IO Driver is shutting down")}; } } if (count == 0) { started_ = true; return {}; } try { threads_.reserve(count); } catch (...) { return std::unexpected{make_io_error( IoErrorCode::os_error, "Cannot allocate file worker table", std::make_error_code(std::errc::not_enough_memory))}; } for (std::size_t i = 0; i < count; ++i) { if (hook) { Void::Result::Result hr{}; try { hr = hook(i); } catch (const std::system_error& e) { hr = std::unexpected{make_io_error(IoErrorCode::os_error, e.what(), e.code())}; } catch (...) { rollback_locked(); throw; } if (!hr.has_value()) { rollback_locked(); return std::unexpected{make_io_error( IoErrorCode::os_error, "before_file_worker_start failed for worker " + std::to_string(i) + ": " + std::string{hr.error().message()}, hr.error().system_code())}; } } { std::lock_guard lk{shared_->mu}; ++shared_->running_workers; shared_->publish_counts_locked(); } try { threads_.emplace_back(&worker_main, shared_); } catch (const std::system_error& e) { { std::lock_guard lk{shared_->mu}; --shared_->running_workers; shared_->publish_counts_locked(); } rollback_locked(); return std::unexpected{make_io_error( IoErrorCode::os_error, "Cannot create file worker thread", e.code())}; } } started_ = true; return {}; } void FileWorkers::rollback_locked() noexcept { { std::lock_guard lk{shared_->mu}; shared_->rollback_requested = true; } shared_->work_cv.notify_all(); for (auto& t : threads_) { if (t.joinable()) { t.join(); } } threads_.clear(); { std::lock_guard lk{shared_->mu}; shared_->rollback_requested = false; } // Requests queued meanwhile stay queued for a retried start or run_file_work. shared_->work_cv.notify_all(); } void FileWorkers::join_for_shutdown() noexcept { std::lock_guard tl{threads_mu_}; shared_->work_cv.notify_all(); for (auto& t : threads_) { if (t.joinable()) { t.join(); } } threads_.clear(); } } // namespace Void::IO::detail // ── File ───────────────────────────────────────────────────────────────────── namespace Void::IO { File::File() noexcept = default; File::File(std::shared_ptr state) noexcept : state_(std::move(state)) { } File::File(File&& other) noexcept : state_(std::move(other.state_)) { } File& File::operator=(File&& other) noexcept { if (this != &other) { release_handle(); state_ = std::move(other.state_); } return *this; } File::~File() { release_handle(); } void File::release_handle() noexcept { std::shared_ptr st = std::move(state_); if (st) { detail::file_handle_dropped(*st); } } DescriptorId File::id() const noexcept { return state_ ? state_->id : DescriptorId{}; } Coro::Task> File::read_at(std::uint64_t offset, std::span buf, Async::OperationOptions options) { auto st = state_; if (!st) { co_return std::unexpected{make_io_error( IoErrorCode::closed, "File is closed or moved-from")}; } auto backend = st->backend.lock(); if (!backend) { co_return std::unexpected{make_io_error( IoErrorCode::closed, "IO Driver no longer alive")}; } auto submitted = backend->submit_file_read(st, offset, buf, std::move(options)); if (!submitted.has_value()) { co_return std::unexpected{std::move(submitted.error())}; } auto op = std::move(*submitted); co_return co_await op->awaitable(&backend->executor()); } Coro::Task> File::write_at(std::uint64_t offset, std::span buf, Async::OperationOptions options) { auto st = state_; if (!st) { co_return std::unexpected{make_io_error( IoErrorCode::closed, "File is closed or moved-from")}; } auto backend = st->backend.lock(); if (!backend) { co_return std::unexpected{make_io_error( IoErrorCode::closed, "IO Driver no longer alive")}; } auto submitted = backend->submit_file_write(st, offset, buf, std::move(options)); if (!submitted.has_value()) { co_return std::unexpected{std::move(submitted.error())}; } auto op = std::move(*submitted); co_return co_await op->awaitable(&backend->executor()); } Coro::Task> File::sync(SyncMode mode, Async::OperationOptions options) { auto st = state_; if (!st) { co_return std::unexpected{make_io_error( IoErrorCode::closed, "File is closed or moved-from")}; } auto backend = st->backend.lock(); if (!backend) { co_return std::unexpected{make_io_error( IoErrorCode::closed, "IO Driver no longer alive")}; } auto submitted = backend->submit_file_sync(st, mode, std::move(options)); if (!submitted.has_value()) { co_return std::unexpected{std::move(submitted.error())}; } auto op = std::move(*submitted); co_return co_await op->awaitable(&backend->executor()); } Coro::Task> File::close_and_join(Async::OperationOptions options) { auto st = state_; if (!st) { co_return Void::Result::Result{}; } Void::Result::Result res{}; if (auto backend = st->backend.lock()) { auto submitted = backend->submit_file_close(st, std::move(options)); if (!submitted.has_value()) { co_return std::unexpected{std::move(submitted.error())}; } auto op = std::move(*submitted); res = co_await op->awaitable(&backend->executor()); } // Without a backend the Driver was torn down, which closed the fd. if (res.has_value() && state_ == st) { release_handle(); } co_return res; } } // namespace Void::IO