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
+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
|
||||
Reference in new issue
Block a user