feat(io): add positional File workers, sync, bounded shutdown core, and epoll D1 fixes (S-IO-03)
This commit is contained in:
1 parent
b2c84114fe
commit
1e752da590
8 files changed
+5000
-325
No files matched your search
@@ -3,15 +3,19 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/IO/File.hpp>
|
||||
#include <Void/IO/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::IO
|
||||
@@ -23,6 +27,7 @@ namespace detail
|
||||
{
|
||||
|
||||
class StreamState;
|
||||
class FileState;
|
||||
|
||||
enum class Direction {
|
||||
read,
|
||||
@@ -73,6 +78,52 @@ public:
|
||||
[[nodiscard]] virtual Void::Result::Result<void> shutdown_and_join() = 0;
|
||||
[[nodiscard]] virtual DriverTelemetry telemetry() const noexcept = 0;
|
||||
|
||||
// ── Positional files (bounded worker pool shared by every backend) ──────
|
||||
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<FileState>>
|
||||
open_file(const std::filesystem::path& path, const FileOpenOptions& options) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<FileState>>
|
||||
adopt_file_fd(int fd) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> start_file_workers() = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<std::size_t>
|
||||
run_file_work(std::size_t max_requests) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<Transfer>>>
|
||||
submit_file_read(const std::shared_ptr<FileState>& file,
|
||||
std::uint64_t offset,
|
||||
std::span<std::byte> buf,
|
||||
Async::OperationOptions options) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<Transfer>>>
|
||||
submit_file_write(const std::shared_ptr<FileState>& file,
|
||||
std::uint64_t offset,
|
||||
std::span<const std::byte> buf,
|
||||
Async::OperationOptions options) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<void>>>
|
||||
submit_file_sync(const std::shared_ptr<FileState>& file,
|
||||
SyncMode mode,
|
||||
Async::OperationOptions options) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<void>>>
|
||||
submit_file_close(const std::shared_ptr<FileState>& file,
|
||||
Async::OperationOptions options) = 0;
|
||||
|
||||
// ── Bounded shutdown core ────────────────────────────────────────────────
|
||||
// Idempotent: closes admission, cancels queued requests and records stop
|
||||
// intent for active ones, then wakes the poller. Never completes,
|
||||
// dispatches or frees anything itself.
|
||||
virtual void begin_shutdown() noexcept = 0;
|
||||
// Drives shutdown until complete, the injected-clock deadline passes or
|
||||
// `stop` fires; the latter two return the current report with
|
||||
// complete == false (not an error). Returns
|
||||
// Async::make_async_error(AdmissionError::self_join) on one of this
|
||||
// backend's file workers or inside one of its poll turns.
|
||||
[[nodiscard]] virtual Void::Result::Result<DriverShutdownReport> advance_shutdown(
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline,
|
||||
std::stop_token stop) = 0;
|
||||
[[nodiscard]] virtual bool shutdown_complete() const noexcept = 0;
|
||||
// No owned operations, file requests or in-flight syscalls remain.
|
||||
[[nodiscard]] virtual bool quiescent() const noexcept = 0;
|
||||
// Driver::~Driver only: begin + advance to completion (blocking).
|
||||
virtual void teardown_blocking() noexcept = 0;
|
||||
|
||||
// Mock inspection / test-only control hooks (returns nullptr on non-mock backends).
|
||||
[[nodiscard]] virtual class MockBackend* as_mock() noexcept { return nullptr; }
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/IO/Detail/Backend.hpp>
|
||||
#include <Void/IO/File.hpp>
|
||||
#include <Void/IO/Stream.hpp>
|
||||
#include <Void/IO/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
@@ -9,10 +10,12 @@
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <memory_resource>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
@@ -56,6 +59,22 @@ private:
|
||||
detail::MockBackend* backend_{nullptr};
|
||||
};
|
||||
|
||||
// True on any Driver's file-worker thread (never on poll or executor threads).
|
||||
[[nodiscard]] bool is_io_worker_thread() noexcept;
|
||||
|
||||
// The Driver owns no thread except its optional file workers. One thread at a
|
||||
// time runs a poll_once turn (the poll owner); a concurrent or reentrant
|
||||
// poll_once returns IoErrorCode::busy without touching any descriptor.
|
||||
//
|
||||
// Lifetime rules:
|
||||
// - The executor must outlive the Driver. Resume tickets produced by
|
||||
// shutdown/teardown are dispatched to it after poll ownership is released,
|
||||
// so an owned executor must not be joined before Driver teardown.
|
||||
// - ~Driver is the only blocking teardown: it begins shutdown, waits for
|
||||
// in-flight syscalls and file requests, joins file workers, closes file and
|
||||
// operation descriptors and delivers every pending result exactly once.
|
||||
// Destroying a Driver on one of its file workers or inside one of its poll
|
||||
// turns is a programmer error: it prints a diagnostic and terminates.
|
||||
class Driver
|
||||
{
|
||||
public:
|
||||
@@ -92,9 +111,43 @@ public:
|
||||
std::optional<std::chrono::nanoseconds> max_wait = std::chrono::nanoseconds{0});
|
||||
|
||||
void wake() noexcept;
|
||||
// Equivalent to begin_shutdown().
|
||||
void request_stop() noexcept;
|
||||
// Blocks until shutdown is complete (shutdown with no deadline or stop).
|
||||
// Returns self_join on a file worker or inside a poll turn of this Driver.
|
||||
[[nodiscard]] Void::Result::Result<void> shutdown_and_join();
|
||||
|
||||
// ── Positional files ─────────────────────────────────────────────────────
|
||||
[[nodiscard]] Void::Result::Result<File> open_file(
|
||||
const std::filesystem::path& path, FileOpenOptions options = {});
|
||||
// Takes ownership of `fd` only on success.
|
||||
[[nodiscard]] Void::Result::Result<File> adopt_file_fd(int fd);
|
||||
// Starts IoLimits::file_workers threads once (0 = none, manual stepping).
|
||||
// A second call is invalid_argument; after shutdown begins it is closed; a
|
||||
// failed start joins the workers already started and may be retried.
|
||||
[[nodiscard]] Void::Result::Result<void> start_file_workers();
|
||||
// Runs up to `max_requests` queued file syscalls on the calling thread and
|
||||
// queues their results for the next poll turn; busy while workers run.
|
||||
[[nodiscard]] Void::Result::Result<std::size_t> run_file_work(std::size_t max_requests = 1);
|
||||
|
||||
// ── Bounded shutdown ─────────────────────────────────────────────────────
|
||||
// Idempotent; closes admission, cancels queued requests, records stop
|
||||
// intent for active ones and wakes the poller. Never blocks or frees.
|
||||
void begin_shutdown() noexcept { backend_->begin_shutdown(); }
|
||||
// Advances shutdown until complete, or until options.deadline (judged by
|
||||
// clock()) or options.stop, which return complete == false with every
|
||||
// listed resource retained. Repeatable.
|
||||
[[nodiscard]] Void::Result::Result<DriverShutdownReport> shutdown(
|
||||
Async::OperationOptions options)
|
||||
{
|
||||
return backend_->advance_shutdown(options.deadline, std::move(options.stop));
|
||||
}
|
||||
[[nodiscard]] bool quiescent() const noexcept { return backend_->quiescent(); }
|
||||
[[nodiscard]] bool shutdown_complete() const noexcept
|
||||
{
|
||||
return backend_->shutdown_complete();
|
||||
}
|
||||
|
||||
private:
|
||||
Driver(std::shared_ptr<detail::DriverBackend> backend,
|
||||
std::shared_ptr<detail::OwnedBufferTracker> buffer_tracker) noexcept;
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/IO/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::IO
|
||||
{
|
||||
|
||||
// Flags for Driver::open_file. read+write maps to O_RDWR, write-only to
|
||||
// O_WRONLY and read-only to O_RDONLY; neither read nor write, truncate without
|
||||
// write, or exclusive without create is invalid_argument. O_CLOEXEC is always
|
||||
// set and open(2) runs on the calling thread with ordinary path semantics.
|
||||
struct FileOpenOptions {
|
||||
bool read{true};
|
||||
bool write{false};
|
||||
bool create{false};
|
||||
bool truncate{false};
|
||||
bool exclusive{false};
|
||||
std::uint32_t mode{0600};
|
||||
};
|
||||
|
||||
enum class SyncMode : std::uint8_t {
|
||||
data, // fdatasync
|
||||
full // fsync
|
||||
};
|
||||
|
||||
// Result of one positional-file syscall: on success `error == 0` and `value`
|
||||
// holds the byte count (0 for sync/close); on failure `error` is the errno.
|
||||
struct FileSyscallResult {
|
||||
std::int64_t value{0};
|
||||
int error{0};
|
||||
};
|
||||
|
||||
// Injectable syscall shim used by the Driver's file workers. The base class
|
||||
// is the native implementation (one syscall per call, no EINTR retry; the
|
||||
// Driver retries EINTR). An override runs on file workers or inside
|
||||
// Driver::run_file_work(); it must not call Driver, Executor or File APIs, and
|
||||
// it must outlive Driver teardown (teardown closes remaining fds through it).
|
||||
class FileSyscalls
|
||||
{
|
||||
public:
|
||||
virtual ~FileSyscalls() = default;
|
||||
|
||||
[[nodiscard]] virtual FileSyscallResult pread(
|
||||
int fd, std::span<std::byte> buf, std::uint64_t offset) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult pwrite(
|
||||
int fd, std::span<const std::byte> buf, std::uint64_t offset) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult sync(int fd, SyncMode mode) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult close(int fd) noexcept;
|
||||
|
||||
[[nodiscard]] static FileSyscalls& native() noexcept;
|
||||
};
|
||||
|
||||
namespace detail
|
||||
{
|
||||
class FileState;
|
||||
} // namespace detail
|
||||
|
||||
// Move-only handle to a positional file owned by a Driver. Requests run on
|
||||
// the Driver's bounded file workers (or Driver::run_file_work) and are
|
||||
// delivered only by a poll turn.
|
||||
//
|
||||
// - Writes and syncs on one File run in admission order, one at a time; reads
|
||||
// may run concurrently and are unordered relative to writes.
|
||||
// - A queued request that is stopped or expires completes cancelled/timeout
|
||||
// without a syscall. An active request keeps its buffer and reports the
|
||||
// syscall's actual outcome even after stop or expiry.
|
||||
// - Dropping a File with requests in flight defers the close until they have
|
||||
// been delivered; the close never blocks the dropping thread.
|
||||
// - Unlike ByteStream::close_and_join (which consumes the stream at once),
|
||||
// File::close_and_join waits for the file's queued and active requests,
|
||||
// never cancels them, and invalidates the File only on success. On deadline
|
||||
// or stop it returns incomplete_shutdown and the File stays valid but
|
||||
// closing (new requests fail with closed; a repeated call waits again).
|
||||
// - After Driver teardown every request fails with closed without a syscall
|
||||
// and close_and_join succeeds immediately.
|
||||
class File
|
||||
{
|
||||
public:
|
||||
File() noexcept;
|
||||
File(File&& other) noexcept;
|
||||
File& operator=(File&& other) noexcept;
|
||||
~File();
|
||||
|
||||
File(const File&) = delete;
|
||||
File& operator=(const File&) = delete;
|
||||
|
||||
[[nodiscard]] bool valid() const noexcept { return state_ != nullptr; }
|
||||
[[nodiscard]] DescriptorId id() const noexcept;
|
||||
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at(
|
||||
std::uint64_t offset, std::span<std::byte> buf, Async::OperationOptions options = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at(
|
||||
std::uint64_t offset, std::span<const std::byte> buf, Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at_owned(
|
||||
std::uint64_t offset, BufferLease& lease, Async::OperationOptions options = {})
|
||||
{
|
||||
auto res = co_await read_at(offset, lease.writable(), std::move(options));
|
||||
if (res.has_value()) {
|
||||
lease.set_valid_bytes(res->bytes);
|
||||
}
|
||||
co_return res;
|
||||
}
|
||||
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at_owned(
|
||||
std::uint64_t offset, const BufferLease& lease, Async::OperationOptions options = {})
|
||||
{
|
||||
co_return co_await write_at(offset, lease.readable(), std::move(options));
|
||||
}
|
||||
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sync(
|
||||
SyncMode mode = SyncMode::full, Async::OperationOptions options = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> close_and_join(
|
||||
Async::OperationOptions options = {});
|
||||
|
||||
private:
|
||||
friend class Driver; // the only producer of open Files
|
||||
|
||||
explicit File(std::shared_ptr<detail::FileState> state) noexcept;
|
||||
|
||||
void release_handle() noexcept;
|
||||
|
||||
std::shared_ptr<detail::FileState> state_{};
|
||||
};
|
||||
|
||||
// Composed positional transfers mirroring read_exact/write_all: the offset
|
||||
// advances with each chunk and one deadline/stop applies to the whole call.
|
||||
[[nodiscard]] inline Coro::Task<std::expected<std::size_t, ComposedTransferError>>
|
||||
read_exact_at(File& file,
|
||||
std::uint64_t offset,
|
||||
std::span<std::byte> buf,
|
||||
Async::OperationOptions options = {})
|
||||
{
|
||||
std::size_t total = 0;
|
||||
while (total < buf.size()) {
|
||||
if (options.stop.stop_requested()) {
|
||||
co_return std::unexpected{ComposedTransferError{
|
||||
total,
|
||||
false,
|
||||
make_io_error(IoErrorCode::cancelled, "read_exact_at stopped before completion")}};
|
||||
}
|
||||
const auto chunk = co_await file.read_at(offset + total, buf.subspan(total), options);
|
||||
if (!chunk.has_value()) {
|
||||
co_return std::unexpected{ComposedTransferError{total, false, chunk.error()}};
|
||||
}
|
||||
total += chunk->bytes;
|
||||
if (total < buf.size() && chunk->eof) {
|
||||
co_return std::unexpected{ComposedTransferError{
|
||||
total,
|
||||
true,
|
||||
make_io_error(IoErrorCode::eof, "Unexpected EOF before read_exact_at finished")}};
|
||||
}
|
||||
}
|
||||
co_return total;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline Coro::Task<std::expected<std::size_t, ComposedTransferError>>
|
||||
write_all_at(File& file,
|
||||
std::uint64_t offset,
|
||||
std::span<const std::byte> buf,
|
||||
Async::OperationOptions options = {})
|
||||
{
|
||||
std::size_t total = 0;
|
||||
while (total < buf.size()) {
|
||||
if (options.stop.stop_requested()) {
|
||||
co_return std::unexpected{ComposedTransferError{
|
||||
total,
|
||||
false,
|
||||
make_io_error(IoErrorCode::cancelled, "write_all_at stopped before completion")}};
|
||||
}
|
||||
const auto chunk = co_await file.write_at(offset + total, buf.subspan(total), options);
|
||||
if (!chunk.has_value()) {
|
||||
co_return std::unexpected{ComposedTransferError{total, false, chunk.error()}};
|
||||
}
|
||||
if (chunk->bytes == 0) {
|
||||
// A zero-byte pwrite with bytes remaining makes no progress; report
|
||||
// it instead of looping.
|
||||
co_return std::unexpected{ComposedTransferError{
|
||||
total,
|
||||
false,
|
||||
make_io_error(IoErrorCode::os_error, "pwrite made no progress in write_all_at")}};
|
||||
}
|
||||
total += chunk->bytes;
|
||||
}
|
||||
co_return total;
|
||||
}
|
||||
|
||||
} // namespace Void::IO
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <memory_resource>
|
||||
#include <new>
|
||||
@@ -120,6 +121,11 @@ struct IoLimits {
|
||||
IoErrorCode::invalid_argument,
|
||||
"IoLimits descriptor, operation, control, and turn bounds must be non-zero")};
|
||||
}
|
||||
if (limits.max_file_queue == 0) {
|
||||
return std::unexpected{make_io_error(
|
||||
IoErrorCode::invalid_argument,
|
||||
"IoLimits max_file_queue must be non-zero")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -129,9 +135,18 @@ enum class BackendPreference {
|
||||
mock
|
||||
};
|
||||
|
||||
class FileSyscalls;
|
||||
|
||||
struct BackendOptions {
|
||||
IoLimits limits{};
|
||||
BackendPreference preference{BackendPreference::auto_native};
|
||||
// Borrowed positional-file syscall shim (nullptr = FileSyscalls::native()).
|
||||
// It runs on file workers or in run_file_work(), must not call Driver,
|
||||
// Executor or File APIs, and must outlive Driver teardown.
|
||||
FileSyscalls* file_syscalls{nullptr};
|
||||
// Called before each file worker thread is created with its index; an
|
||||
// error aborts start_file_workers() exactly like a thread-creation failure.
|
||||
std::function<Void::Result::Result<void>(std::size_t)> before_file_worker_start{};
|
||||
};
|
||||
|
||||
struct DescriptorId {
|
||||
@@ -150,6 +165,21 @@ struct DriverTelemetry {
|
||||
std::uint64_t turns{0};
|
||||
std::uint64_t wakeups{0};
|
||||
std::uint64_t stale_events_ignored{0};
|
||||
std::size_t queued_file_requests{0};
|
||||
std::size_t active_file_requests{0};
|
||||
std::size_t file_workers_running{0};
|
||||
// Cancel/expiry/shutdown paths that met an already-retired op and skipped it.
|
||||
std::uint64_t duplicate_completions_ignored{0};
|
||||
};
|
||||
|
||||
// Snapshot returned by Driver::shutdown(). `complete == false` means the
|
||||
// bounded call expired (deadline or stop) and everything listed is retained.
|
||||
struct DriverShutdownReport {
|
||||
bool complete{false};
|
||||
std::size_t pending_operations{0};
|
||||
std::size_t active_file_requests{0};
|
||||
std::size_t open_descriptors{0};
|
||||
std::size_t retained_buffer_bytes{0};
|
||||
};
|
||||
|
||||
namespace detail
|
||||
|
||||
+1534
-325
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,743 @@
|
||||
#include "FileWorkers.hpp"
|
||||
|
||||
#include <Void/IO/Driver.hpp>
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <exception>
|
||||
#include <iterator>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
#if defined(__unix__) || defined(__APPLE__)
|
||||
#include <fcntl.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#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<std::byte> buf, std::uint64_t offset) noexcept
|
||||
{
|
||||
#ifdef VOID_IO_POSIX_FILES
|
||||
const ssize_t n = ::pread(fd, buf.data(), buf.size(), static_cast<off_t>(offset));
|
||||
if (n < 0) {
|
||||
return FileSyscallResult{-1, errno};
|
||||
}
|
||||
return FileSyscallResult{static_cast<std::int64_t>(n), 0};
|
||||
#else
|
||||
(void)fd;
|
||||
(void)buf;
|
||||
(void)offset;
|
||||
return FileSyscallResult{-1, ENOSYS};
|
||||
#endif
|
||||
}
|
||||
|
||||
FileSyscallResult FileSyscalls::pwrite(int fd,
|
||||
std::span<const std::byte> buf,
|
||||
std::uint64_t offset) noexcept
|
||||
{
|
||||
#ifdef VOID_IO_POSIX_FILES
|
||||
const ssize_t n = ::pwrite(fd, buf.data(), buf.size(), static_cast<off_t>(offset));
|
||||
if (n < 0) {
|
||||
return FileSyscallResult{-1, errno};
|
||||
}
|
||||
return FileSyscallResult{static_cast<std::int64_t>(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<FileWorkerShared> 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<FileRequest> 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<FileWorkerShared> pool_in,
|
||||
std::weak_ptr<DriverBackend> 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<FileRequest>();
|
||||
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<FileRequest> 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<FileRequest> 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<FileRequest> 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<FileState> 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<std::byte>{req.read_ptr, req.len}, req.offset);
|
||||
break;
|
||||
case FileRequestKind::write:
|
||||
r = sys.pwrite(fd, std::span<const std::byte>{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<std::size_t> 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<FileRequest> 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<void> 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<int> 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<mode_t>(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<void> FileWorkers::start(
|
||||
std::size_t count,
|
||||
const std::function<Void::Result::Result<void>(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<void> 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<detail::FileState> 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<detail::FileState> st = std::move(state_);
|
||||
if (st) {
|
||||
detail::file_handle_dropped(*st);
|
||||
}
|
||||
}
|
||||
|
||||
DescriptorId File::id() const noexcept
|
||||
{
|
||||
return state_ ? state_->id : DescriptorId{};
|
||||
}
|
||||
|
||||
Coro::Task<Void::Result::Result<Transfer>> File::read_at(std::uint64_t offset,
|
||||
std::span<std::byte> 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<Void::Result::Result<Transfer>> File::write_at(std::uint64_t offset,
|
||||
std::span<const std::byte> 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<Void::Result::Result<void>> 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<Void::Result::Result<void>> File::close_and_join(Async::OperationOptions options)
|
||||
{
|
||||
auto st = state_;
|
||||
if (!st) {
|
||||
co_return Void::Result::Result<void>{};
|
||||
}
|
||||
Void::Result::Result<void> 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
|
||||
@@ -0,0 +1,267 @@
|
||||
#pragma once
|
||||
|
||||
// Private to the IO module: the bounded positional-file worker pool shared by
|
||||
// every backend. Nothing here is installed.
|
||||
//
|
||||
// Ownership (S6/F1):
|
||||
// - FileWorkerShared holds the queues, the mutex/condvars, the completion
|
||||
// queue and a raw waker (function pointer + backend context). Workers hold
|
||||
// only shared_ptr<FileWorkerShared>; the raw waker is called only by workers
|
||||
// and run_file_work, which are finished or joined before the backend dies.
|
||||
// - FileState holds shared_ptr<FileWorkerShared> and weak_ptr<DriverBackend>.
|
||||
// - A FileRequest lives in exactly one FileWorkerShared list (queued,
|
||||
// close_queued, active, completions) from admission until a poll turn
|
||||
// retires it; nodes move between lists with splice, so workers never
|
||||
// allocate.
|
||||
//
|
||||
// Lock order: backend poll_mu_ -> backend mu_ -> FileWorkerShared::mu, and
|
||||
// poll_mu_ -> FileWorkers::threads_mu_ -> FileWorkerShared::mu. Workers take
|
||||
// only FileWorkerShared::mu. No stop_callback is constructed or destroyed and
|
||||
// no clock is read while FileWorkerShared::mu is held.
|
||||
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/IO/Detail/Backend.hpp>
|
||||
#include <Void/IO/File.hpp>
|
||||
#include <Void/IO/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <stop_token>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::IO::detail
|
||||
{
|
||||
|
||||
struct FileRequest;
|
||||
struct FileWorkerShared;
|
||||
using FileRequestList = std::list<std::shared_ptr<FileRequest>>;
|
||||
|
||||
enum class FileRequestKind : std::uint8_t {
|
||||
read,
|
||||
write,
|
||||
sync,
|
||||
close
|
||||
};
|
||||
|
||||
enum class FileRequestPhase : std::uint8_t {
|
||||
queued, // in queued / close_queued
|
||||
active, // in active, syscall running
|
||||
done, // in completions, awaiting poll-turn retirement
|
||||
retired // delivered by a poll turn
|
||||
};
|
||||
|
||||
enum class FileSettle : std::uint8_t {
|
||||
syscall, // result holds the syscall outcome
|
||||
cancelled, // stopped while queued (no syscall)
|
||||
timeout // expired while queued (no syscall)
|
||||
};
|
||||
|
||||
struct FileCancelForwarder {
|
||||
std::weak_ptr<FileRequest> request;
|
||||
|
||||
void operator()() const noexcept;
|
||||
};
|
||||
|
||||
struct FileWakeForwarder {
|
||||
std::weak_ptr<DriverBackend> backend;
|
||||
|
||||
void operator()() const noexcept;
|
||||
};
|
||||
|
||||
class FileState;
|
||||
|
||||
struct FileRequest {
|
||||
FileRequestKind kind{FileRequestKind::read};
|
||||
// Guarded by FileWorkerShared::mu.
|
||||
FileRequestPhase phase{FileRequestPhase::queued};
|
||||
FileSettle settle{FileSettle::syscall};
|
||||
bool stop_requested{false};
|
||||
bool expired{false};
|
||||
int exec_fd{-1};
|
||||
FileSyscallResult result{};
|
||||
FileRequestList::iterator pos{};
|
||||
// Immutable after admission (a close request's `file` is set under mu
|
||||
// when it is enqueued).
|
||||
std::shared_ptr<FileState> file{};
|
||||
std::byte* read_ptr{nullptr};
|
||||
const std::byte* write_ptr{nullptr};
|
||||
std::size_t len{0};
|
||||
std::uint64_t offset{0};
|
||||
SyncMode mode{SyncMode::full};
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
|
||||
std::shared_ptr<Async::OperationState<Transfer>> transfer_op{};
|
||||
std::shared_ptr<Async::OperationState<void>> void_op{};
|
||||
// MUST stay LAST: synchronized teardown with external stop callbacks.
|
||||
std::optional<std::stop_callback<FileCancelForwarder>> cancel_cb{};
|
||||
|
||||
[[nodiscard]] bool serialized() const noexcept
|
||||
{
|
||||
return kind == FileRequestKind::write || kind == FileRequestKind::sync;
|
||||
}
|
||||
};
|
||||
|
||||
class FileState : public std::enable_shared_from_this<FileState>
|
||||
{
|
||||
public:
|
||||
enum class Status : std::uint8_t {
|
||||
open,
|
||||
closing,
|
||||
closed
|
||||
};
|
||||
|
||||
// Allocates the preallocated close request node (so ~File never allocates).
|
||||
FileState(std::shared_ptr<FileWorkerShared> pool_in,
|
||||
std::weak_ptr<DriverBackend> backend_in,
|
||||
FileSyscalls* syscalls_in,
|
||||
int fd_in,
|
||||
DescriptorId id_in);
|
||||
|
||||
FileState(const FileState&) = delete;
|
||||
FileState& operator=(const FileState&) = delete;
|
||||
|
||||
const std::shared_ptr<FileWorkerShared> pool;
|
||||
const std::weak_ptr<DriverBackend> backend;
|
||||
FileSyscalls* const syscalls;
|
||||
const DescriptorId id;
|
||||
|
||||
// Guarded by pool->mu.
|
||||
int fd{-1};
|
||||
Status status{Status::open};
|
||||
bool close_pending{false};
|
||||
bool close_enqueued{false};
|
||||
bool serial_active{false};
|
||||
std::size_t in_flight{0};
|
||||
int close_error{0};
|
||||
FileRequestList close_node{};
|
||||
};
|
||||
|
||||
struct FileCloseWaiter {
|
||||
std::shared_ptr<FileState> file{};
|
||||
std::shared_ptr<Async::OperationState<void>> op{};
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
|
||||
// MUST stay LAST.
|
||||
std::optional<std::stop_callback<FileWakeForwarder>> stop_cb{};
|
||||
};
|
||||
|
||||
struct FileWorkerShared {
|
||||
FileWorkerShared(std::size_t max_queue_in, FileSyscalls* syscalls_in) noexcept
|
||||
: max_queue(max_queue_in)
|
||||
, syscalls(syscalls_in)
|
||||
{
|
||||
}
|
||||
|
||||
FileWorkerShared(const FileWorkerShared&) = delete;
|
||||
FileWorkerShared& operator=(const FileWorkerShared&) = delete;
|
||||
|
||||
std::mutex mu{};
|
||||
std::condition_variable work_cv{};
|
||||
std::condition_variable idle_cv{};
|
||||
|
||||
// Guarded by mu.
|
||||
FileRequestList queued{}; // admitted read/write/sync, admission order
|
||||
FileRequestList close_queued{}; // internal close requests (reserved capacity)
|
||||
FileRequestList active{}; // syscall running
|
||||
FileRequestList completions{}; // finished, awaiting poll-turn retirement
|
||||
std::vector<std::shared_ptr<FileCloseWaiter>> close_waiters{};
|
||||
bool accepting{true};
|
||||
bool exit_requested{false};
|
||||
bool rollback_requested{false};
|
||||
std::size_t running_workers{0};
|
||||
|
||||
const std::size_t max_queue;
|
||||
FileSyscalls* const syscalls;
|
||||
void (*waker)(void*) noexcept {nullptr};
|
||||
void* waker_ctx{nullptr};
|
||||
|
||||
// Lock-free telemetry mirrors (written under mu).
|
||||
std::atomic<std::size_t> queued_count{0};
|
||||
std::atomic<std::size_t> active_count{0};
|
||||
std::atomic<std::size_t> running_count{0};
|
||||
|
||||
void wake() const noexcept
|
||||
{
|
||||
if (waker != nullptr) {
|
||||
waker(waker_ctx);
|
||||
}
|
||||
}
|
||||
|
||||
// All *_locked members require `mu`.
|
||||
void publish_counts_locked() noexcept;
|
||||
[[nodiscard]] bool has_runnable_locked() const noexcept;
|
||||
// Moves the next eligible request to `active` (close requests first; a
|
||||
// write/sync only when its file has no serialized request active). A
|
||||
// queued request already stopped/expired is settled without a syscall and
|
||||
// `settled_without_syscall` is set.
|
||||
[[nodiscard]] std::shared_ptr<FileRequest> take_next_locked(
|
||||
bool& settled_without_syscall) noexcept;
|
||||
void finish_locked(FileRequest& req, FileSyscallResult result) noexcept;
|
||||
// queued -> completions with `settle` (cancelled/timeout).
|
||||
void settle_queued_locked(FileRequest& req, FileSettle settle) noexcept;
|
||||
void enqueue_close_locked(FileState& file) noexcept;
|
||||
};
|
||||
|
||||
// Runs one request's syscall through the shim (EINTR retried except close).
|
||||
[[nodiscard]] FileSyscallResult execute_file_request(const FileRequest& req) noexcept;
|
||||
|
||||
// Executes up to `max_requests` requests on the calling thread. Returns
|
||||
// nullopt (busy) while workers are running.
|
||||
[[nodiscard]] std::optional<std::size_t> run_file_requests_inline(
|
||||
FileWorkerShared& shared, std::size_t max_requests);
|
||||
|
||||
// Handle-drop transition for ~File and File move-assignment (noexcept, never
|
||||
// allocates; wakes only through the worker condvar or a weak->strong lock).
|
||||
void file_handle_dropped(FileState& file) noexcept;
|
||||
|
||||
[[nodiscard]] const FileWorkerShared* current_io_worker_owner() noexcept;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> validate_file_open_options(
|
||||
const FileOpenOptions& options);
|
||||
[[nodiscard]] Void::Result::Result<int> open_file_native(
|
||||
const std::filesystem::path& path, const FileOpenOptions& options);
|
||||
|
||||
// Owns the worker threads. Never blocks in its destructor: a joinable thread
|
||||
// left at destruction is a programmer error (diagnostic + std::terminate).
|
||||
class FileWorkers
|
||||
{
|
||||
public:
|
||||
explicit FileWorkers(std::shared_ptr<FileWorkerShared> shared) noexcept
|
||||
: shared_(std::move(shared))
|
||||
{
|
||||
}
|
||||
|
||||
~FileWorkers();
|
||||
|
||||
FileWorkers(const FileWorkers&) = delete;
|
||||
FileWorkers& operator=(const FileWorkers&) = delete;
|
||||
|
||||
// invalid_argument when already started, closed once shutdown began,
|
||||
// os_error (with the system code when present) on a hook or thread
|
||||
// creation failure after joining the workers already started.
|
||||
[[nodiscard]] Void::Result::Result<void> start(
|
||||
std::size_t count,
|
||||
const std::function<Void::Result::Result<void>(std::size_t)>& hook);
|
||||
|
||||
// FileWorkerShared::exit_requested must already be set.
|
||||
void join_for_shutdown() noexcept;
|
||||
|
||||
private:
|
||||
void rollback_locked() noexcept;
|
||||
|
||||
std::shared_ptr<FileWorkerShared> shared_{};
|
||||
std::mutex threads_mu_{};
|
||||
std::vector<std::thread> threads_{};
|
||||
bool started_{false};
|
||||
};
|
||||
|
||||
} // namespace Void::IO::detail
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user