Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions docs/directstorage.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,19 @@ The first boot with the executable settles most of this: the dry-run report show
`DSTORAGE_QUEUE_OPTIONS::AutoSubmitDisabled`). An enqueue into a full queue waits for space, as the reference
says; with auto-submit disabled only a `Submit` from another thread frees it. One worker thread per queue runs
the submitted entries in order, so every notification follows all the entries before it.
- **Reads into physical pages wait for `Submit`**: an automatic submit stops at the first request whose
destination is a physical page list; that request and every entry behind it wait for the title's own `Submit`.
A title may fill the page-number table such a list points into only in its submit path, so an early read finds
page 0 (the entry fails) or the number the slot held before (the data lands in a page that now belongs to
something else, with no error). A full queue submits the held entries too, since the title cannot call `Submit`
while it waits in an enqueue, and so does `Close`. The idea is from VIctory (`Marvisak/VIctory` `eddde73`, also
in `fxceless/victory-fork` `79cfdd9`); the queue here keeps its order, so entries behind a held read wait with
it. `LEONIDA_DSTORAGE_HOLD_PAGES=0` restores the automatic submit of everything. A hold ends after
`LEONIDA_DSTORAGE_HOLD_MS` milliseconds without a `Submit` (2000 unless set): the held entries are submitted with
their page lists as they are, as a timed release, so a path that never calls `Submit` cannot stall for good. `0`
is no time limit (a hold of five seconds is then logged once). The `[rt] ds-hold` line counts automatic submits,
reads held, full-queue and timed releases, and destination lists that named page 0 when written (`event=`, at
each power of two of the counter that moved).
- **Requests**: copied at enqueue. A file request reads `SourceSize` bytes at `FileOffset` into `Destination`; a
memory request copies `Source` to `Destination` (`memmove`, so an overlapping pair is safe); a zlib request
inflates those `SourceSize` bytes into `Destination` (below). Checked in this order when the worker reaches the
Expand Down Expand Up @@ -213,8 +226,9 @@ The first boot with the executable settles most of this: the dry-run report show

`runtime/test/dstorage_test.cpp` (ctest `dstorage`) runs on synthetic files in `%TEMP%` through the registry entries
under all three module names: `GAME:` reads with an overlay copy winning, offsets, zero size, a range past the end,
cancellation, auto-submit, a full queue, status arrays, fences (a CPU fence object that checks the data is in place
when it is signalled), events, error records, file and queue close with requests in flight, a destination the
cancellation, auto-submit, reads into physical pages held for `Submit` (a page list changed or filled before it,
a full queue, the time limit, the switch), a full queue, status arrays, fences (a CPU fence object that checks the
data is in place when it is signalled), events, error records, file and queue close with requests in flight, a destination the
process cannot write, four threads enqueueing at once, the interface-id policy (unknown and system ids refused by
`QueryInterface`, learned by creating calls), a `GetHandle` handle with its own file position, an event closed (and
its handle value reused) before it is set, and cancelled requests that also had an enqueue error. zlib requests use
Expand Down
172 changes: 162 additions & 10 deletions runtime/shims/dstorage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
// it has. Completion is therefore in queue order, as the API guarantees.
// - Compressed requests stage RFC 1950 inflate, BCPack BC block reconstruction and DirectStorage
// macro-unshuffle before publishing the destination. Physical page numbers resolve in xmem at execution.
// - A queue half full submits itself, but a read into physical pages and everything enqueued behind it wait for
// the title's own Submit: the title may fill the page list only then (hold_pages below).
// Nothing here goes online or touches the GPU.
#include <windows.h>
#include <d3d12.h>
Expand Down Expand Up @@ -38,6 +40,7 @@
#include "../src/shader_directory.h"
#include "../src/dstorage_swizzle.h"
#include "../src/dstorage_trace.h"
#include "../src/dstorage_hold.h"
#include "dstorage_xs_abi.h"
#include "dstorage_staging.h"
#include "startup_trace.h"
Expand Down Expand Up @@ -542,6 +545,47 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3
return S_OK;
}

// ---- Reads into physical pages wait for the title's Submit -------------------------------------------------------
//
// A request into physical pages names them through a pointer into the title's own page-number table, and a title may
// fill that table for a batch only in its submit path, right before Submit. A queue that submits itself at half its
// capacity then starts such a read early: it finds page 0 and fails, or finds the number the slot held before and
// writes the data into a page that now belongs to something else, with no error at all. So a self-submit stops at
// the first read into physical pages: that read and every entry behind it (the queue completes in order) wait for
// the title's Submit. A full queue still submits everything, since the title cannot call Submit while it waits in an
// enqueue, and Close does as before. The idea is from VIctory (Marvisak/VIctory eddde73, carried in
// fxceless/victory-fork 79cfdd9); the code here is written anew for this queue.
//
// LEONIDA_DSTORAGE_HOLD_PAGES=0 restores the old self-submit of everything. A hold has a time limit, so that a
// title path that never calls Submit and counted on the self-submit cannot stall for good: held entries that have
// waited LEONIDA_DSTORAGE_HOLD_MS milliseconds (2000 unless set) are submitted, page lists as they are, and counted
// as a timed release. 0 is no limit: they wait for Submit, however long. Both are read when a queue is created.
constexpr uint32_t kDefaultHoldMs = 2000;

uint32_t environment_number(const wchar_t* name, uint32_t fallback) {
wchar_t value[16]{};
const DWORD n = GetEnvironmentVariableW(name, value, 16);
if (n == 0 || n >= 16) return fallback;
wchar_t* end = nullptr;
const unsigned long parsed = std::wcstoul(value, &end, 10);
return end && *end == 0 ? static_cast<uint32_t>(parsed) : fallback;
}

// One line with every counter, at each power of two of the counter that moved: countable in a truncated log
// without a line per event.
void log_hold(const char* event, uint64_t n, unsigned capacity, size_t held_now) {
if (n & (n - 1)) return;
const auto& h = leonida::dstorage::hold_stats();
std::lock_guard lock(log_mutex());
std::fprintf(stderr, "[rt] ds-hold event=%s self_submits=%llu held_reads=%llu full_releases=%llu "
"timed_releases=%llu page0_entries=%llu capacity=%u held_now=%zu\n", event,
static_cast<unsigned long long>(h.self_submits.load()),
static_cast<unsigned long long>(h.held_reads.load()),
static_cast<unsigned long long>(h.full_releases.load()),
static_cast<unsigned long long>(h.timed_releases.load()),
static_cast<unsigned long long>(h.page0_entries.load()), capacity, held_now);
}

// ---- Queues -------------------------------------------------------------------------------------------------------

// Only sampled when request tracing is enabled. Times include work done by the file/decode worker.
Expand Down Expand Up @@ -576,7 +620,10 @@ struct Entry {

class Queue final : public IDStorageQueueX2 {
public:
explicit Queue(const DSTORAGE_QUEUE_DESC1& desc) : desc_(desc) {
explicit Queue(const DSTORAGE_QUEUE_DESC1& desc)
: desc_(desc),
hold_pages_(environment_number(L"LEONIDA_DSTORAGE_HOLD_PAGES", 1) != 0),
hold_release_ms_(environment_number(L"LEONIDA_DSTORAGE_HOLD_MS", kDefaultHoldMs)) {
error_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
clear_record_locked();
std::lock_guard lock(stats().mutex);
Expand Down Expand Up @@ -781,15 +828,64 @@ class Queue final : public IDStorageQueueX2 {
bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; }
size_t used_locked() const { return entries_.size() + in_flight_; }

// A read into physical pages: its page list may not be filled before the title's Submit (hold_pages above).
static bool into_pages(const Entry& e) {
return e.type == Entry::Type::Request && (e.request.Options.AsUINT64 & options::kDestinationPages) != 0;
}

// The queue has reached half its capacity and holds nothing yet. Submits up to the first read into physical
// pages, which waits with everything behind it for the title's Submit.
void self_submit_locked() {
auto& h = leonida::dstorage::hold_stats();
if (!hold_pages_) {
log_hold("self-submit", ++h.self_submits, desc_.Capacity, 0);
submit_locked();
return;
}
size_t end = submitted_;
while (end < entries_.size() && !into_pages(entries_[end])) ++end;
if (end < entries_.size()) {
uint64_t reads = 0;
for (size_t i = end; i < entries_.size(); ++i) reads += into_pages(entries_[i]);
h.held_reads += reads;
holding_ = true;
hold_warned_ = false;
held_since_ = std::chrono::steady_clock::now();
}
const size_t held_now = entries_.size() - end;
const bool hold = holding_; // submit_locked ends a hold when it submits everything
submit_locked(end);
holding_ = hold;
if (holding_) work_.notify_one(); // the worker starts timing the hold
log_hold("self-submit", ++h.self_submits, desc_.Capacity, held_now);
}

void enqueue(Entry&& e) {
{
std::unique_lock lock(mutex_);
// A full queue waits for the worker to free a slot. With auto-submit on, half the queue is always
// submitted by then; with it off, only a Submit from another thread frees one (as the reference warns).
space_.wait(lock, [&] { return closing_ || used_locked() < usable(); });
// A full queue waits for the worker to free a slot. With auto-submit on, half the queue was submitted
// by then, except what is held for the title's Submit: the title cannot make that call while it waits
// here, so a full queue submits the held entries too, page lists as they are. With auto-submit off,
// only a Submit from another thread frees a slot (as the reference warns).
space_.wait(lock, [&] {
if (closing_ || used_locked() < usable()) return true;
if (holding_) {
const size_t held_now = entries_.size() - submitted_;
submit_locked();
log_hold("full-queue", ++leonida::dstorage::hold_stats().full_releases, desc_.Capacity, held_now);
log_once("full-hold", "a full queue submitted reads into physical pages before the title's "
"Submit (their page lists may not be filled yet)");
}
return false;
});
if (!closing_) {
entries_.push_back(std::move(e));
if (auto_submit() && entries_.size() - submitted_ >= half()) submit_locked();
if (holding_) {
// Behind a held read: it waits with it, whatever it is. No second self-submit until the hold ends.
if (into_pages(entries_.back())) ++leonida::dstorage::hold_stats().held_reads;
} else if (auto_submit() && entries_.size() - submitted_ >= half()) {
self_submit_locked();
}
return;
}
}
Expand All @@ -801,10 +897,16 @@ class Queue final : public IDStorageQueueX2 {
release_references(e);
}

void submit_locked() {
// Submits the entries before "end". Without one it submits all of them and ends a hold: the title's Submit, a
// full queue, Close, a hold that ran out of time.
void submit_locked(size_t end = SIZE_MAX) {
if (end >= entries_.size()) {
end = entries_.size();
holding_ = false;
}
uint32_t requests = 0;
uint64_t source_bytes = 0, destination_bytes = 0;
for (size_t i = submitted_; i < entries_.size(); ++i) {
for (size_t i = submitted_; i < end; ++i) {
Entry& e = entries_[i];
if (e.file) e.file_counted = e.file->add_pending();
if (e.counted) {
Expand All @@ -820,12 +922,49 @@ class Queue final : public IDStorageQueueX2 {
p.TotalRequestSourceByteCount += source_bytes;
p.TotalRequestDestinationByteCount += destination_bytes;
}
if (entries_.size() > submitted_) {
submitted_ = entries_.size();
if (end > submitted_) {
submitted_ = end;
work_.notify_one();
}
}

// How long the worker sleeps before it looks at a hold again: until the time limit runs out, a quarter of a
// second at most (and exactly that without a limit, for the five-second line).
std::chrono::milliseconds hold_wait_locked() const {
long long ms = 250;
if (hold_release_ms_) {
const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - held_since_).count();
ms = std::clamp<long long>(static_cast<long long>(hold_release_ms_) - waited, 1, 250);
}
return std::chrono::milliseconds(ms);
}

// On the worker while entries are held: a hold with a time limit ends when it runs out (a timed release), and
// one without says once that it has lasted five seconds (a title that never calls Submit would show up as this
// line and nothing after it).
void hold_tick_locked() {
if (!holding_) return;
const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - held_since_).count();
const size_t held_now = entries_.size() - submitted_;
if (hold_release_ms_ && waited >= static_cast<long long>(hold_release_ms_)) {
submit_locked();
log_hold("timed", ++leonida::dstorage::hold_stats().timed_releases, desc_.Capacity, held_now);
log_once("timed-hold", "timed release: reads into physical pages held for the title's Submit were "
"submitted after LEONIDA_DSTORAGE_HOLD_MS without one (their page lists may "
"not be filled; the ds-hold line counts these)");
} else if (waited >= 5000 && !hold_warned_) {
hold_warned_ = true;
std::lock_guard lock(log_mutex());
std::fprintf(stderr, "[rt] dstorage: %zu entries behind a read into physical pages have waited %lld ms "
"for the title's Submit (queue %p, capacity %u; LEONIDA_DSTORAGE_HOLD_MS=<n> "
"submits them after n ms, LEONIDA_DSTORAGE_HOLD_PAGES=0 never holds)\n",
held_now, static_cast<long long>(waited), static_cast<void*>(this),
unsigned(desc_.Capacity));
}
}

struct Prepared {
Entry& entry;
HRESULT result = S_OK;
Expand Down Expand Up @@ -859,7 +998,11 @@ class Queue final : public IDStorageQueueX2 {
bool paired = false;
{
std::unique_lock lock(mutex_);
work_.wait(lock, [&] { return submitted_ > 0 || closed_; });
while (!(submitted_ > 0 || closed_)) {
if (!holding_) work_.wait(lock);
else if (work_.wait_for(lock, hold_wait_locked()) == std::cv_status::timeout)
hold_tick_locked();
}
if (submitted_ == 0) return;
head = std::move(entries_.front());
entries_.pop_front();
Expand Down Expand Up @@ -1088,6 +1231,10 @@ class Queue final : public IDStorageQueueX2 {
std::vector<uint64_t> numbers(1 + (buffer.size() - 1 + offset) / 65536);
if (!guarded_move(numbers.data(), pages, numbers.size() * sizeof(numbers[0])))
return E_DSTORAGE_ACCESS_VIOLATION;
// Page 0 is never a title page: a destination list that names it was not filled when its request ran, and
// the request fails below. Counted, since each one is data the title asked for and did not get.
if (write && std::find(numbers.begin(), numbers.end(), uint64_t{0}) != numbers.end())
log_hold("page0", ++leonida::dstorage::hold_stats().page0_entries, 0, 0);
if (rt::xmem::transfer_physical(numbers, offset, buffer, write)) return S_OK;
return HRESULT_FROM_WIN32(GetLastError());
}
Expand Down Expand Up @@ -1305,6 +1452,11 @@ class Queue final : public IDStorageQueueX2 {
std::condition_variable work_, space_, idle_;
std::deque<Entry> entries_;
size_t submitted_ = 0; // the first submitted_ entries are submitted
const bool hold_pages_; // LEONIDA_DSTORAGE_HOLD_PAGES
const uint32_t hold_release_ms_; // LEONIDA_DSTORAGE_HOLD_MS (kDefaultHoldMs unless set); 0: no time limit
bool holding_ = false; // under mutex_: a self-submit left entries for the title's Submit
bool hold_warned_ = false; // under mutex_: this hold's five-second line was written
std::chrono::steady_clock::time_point held_since_{}; // under mutex_
size_t in_flight_ = 0;
bool closing_ = false;
bool closed_ = false;
Expand Down
23 changes: 23 additions & 0 deletions runtime/src/dstorage_hold.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Counters of the DirectStorage queues' rule "reads into physical pages wait for the title's Submit"
// (shims/dstorage.cpp, docs/directstorage.md). Process-wide, so the log line and the test read the same numbers.
#pragma once

#include <atomic>
#include <cstdint>

namespace leonida::dstorage {

struct HoldStats {
std::atomic<uint64_t> self_submits{0}; // a queue half full submitted itself
std::atomic<uint64_t> held_reads{0}; // reads into physical pages such a submit left for the title's Submit
std::atomic<uint64_t> full_releases{0}; // a full queue submitted its held entries (the title waits in an enqueue)
std::atomic<uint64_t> timed_releases{0}; // LEONIDA_DSTORAGE_HOLD_MS ran out before the title's Submit
std::atomic<uint64_t> page0_entries{0}; // destination page lists that named page 0 when their data was written
};

inline HoldStats& hold_stats() {
static HoldStats stats;
return stats;
}

} // namespace leonida::dstorage
Loading
Loading