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
12 changes: 12 additions & 0 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -1680,6 +1680,18 @@ The copies:
cannot fit between the title's address reservations can use a separate mapped buffer. The buffer's device address
must fit as a positive 47-bit offset from the arena base. The same window cap and dirty-page refresh apply.
`LEONIDA_STREAM_BUFFER_WINDOWS=0` requires the window to fit in the arena.
- **What the GPU wrote goes back.** The same return copy serves slot-133 shadows (a buffer the driver would not
import, a compute result the title reads again): the ranges are recorded through the alias of the buffer's pages and
the tracker there carries them back. `d3d12_placed_write_back` covers it. A copy is a read-side mirror, so a UAV or a raw write into a window would land in
the copy and the title would never see it ([#1537](https://github.com/ubiquitarianism/leonida/issues/1537), the
`WRITE_INVALID` stop at the world start). Every title range a submission's bindings reach is kept, and the next
refresh copies those ranges from the copy to the title's pages *before* it copies the pages forward, so a page the
title itself wrote in between keeps the title's newer bytes and its GPU result is dropped. Up to 8,192 ranges and
64 MiB a submission (a V# has no read/write bit, so a read-only view costs a copy too; past the caps the ranges are
left behind, logged once). `LEONIDA_TITLE_WRITEBACK=0` turns it off. A batch is fenced: it is kept with the ticket
of the submission that will use it and copied back only when the context reports that ticket retired, so a range
another submission is still writing is never read half done. A queue held deep (console ordering) can leave batches
waiting: past 64 of them the oldest go back without their ticket, logged once.
- A **window that is refused** (the budget is spent, the arena is full, or the pages are not committed yet) is backed
by a persistent geometry copy of exactly the requested range (`LEONIDA_GEOMETRY_MB`) instead; when no copy can be
made either, the view is written with **no base and no records** — loads return 0 and stores are dropped. A raw
Expand Down
4 changes: 4 additions & 0 deletions docs/linux_proton.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,10 @@ Each item was a stop on at least one of the machines. Tests named in the pull re

## Where it stops

- **Writes into title memory.** A window is a read-side copy, so a UAV or raw write used to stop at the copy: the
missing return copy is the `WRITE_INVALID` device loss of #1537. The layer now copies the reached ranges back to
the title's pages at the next refresh, before the forward copy, and the title's own newer words win. Not yet
measured on a GPU with the world phase in front of it.
- **Streamed memory that reaches its destination late or not at all.** The title calls queue slot 31
(`CopyPageMappingsBatchX`) about 300 times per boot. With #968 this branch maps each batch's pool pages at the
destination and at the paired CPU view the layer reads (`docs/d3d12_vulkan.md`, section 4.9), so most streamed
Expand Down
7 changes: 7 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3647,6 +3647,13 @@ if(TARGET Vulkan::Headers)
# is written zero-size, and a dispatch through it reads zeros.
add_test(NAME d3d12_title_window_cap COMMAND d3d12_title_va_test --window-cap)
set_tests_properties(d3d12_title_window_cap PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_TITLE_WINDOWS_MB=0")
# A window is a read-side mirror refreshed before every submission: what a shader writes into it goes back to
# the title's pages at the next refresh, and the title's own newer words still win (#1537, WRITE_INVALID).
add_test(NAME d3d12_title_window_write_back COMMAND d3d12_title_va_test --window-writeback)
set_tests_properties(d3d12_title_window_write_back PROPERTIES SKIP_RETURN_CODE 77)
# The same return copy for a slot-133 buffer's shadow (the write-back of a compute result the title reads again).
add_test(NAME d3d12_placed_write_back COMMAND d3d12_title_va_test --placed-writeback)
set_tests_properties(d3d12_placed_write_back PROPERTIES SKIP_RETURN_CODE 77)
add_test(NAME d3d12_api_descriptor_copy COMMAND d3d12_title_va_test --api-descriptor-copy)
set_tests_properties(d3d12_api_descriptor_copy PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1")
add_test(NAME d3d12_api_descriptor_copy_off COMMAND d3d12_title_va_test --api-descriptor-copy-off)
Expand Down
145 changes: 144 additions & 1 deletion runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,43 @@ class ShadowPages {
ShadowPages(const ShadowPages&) = delete;
ShadowPages& operator=(const ShadowPages&) = delete;

// What the GPU writes into the copies of [from, to) goes back to the title's pages: the pages are made writable
// first (the tracker guards them) and every target is copied from its shadow. Returns the bytes written. Called
// before the next refresh, so a page the title writes again is copied forward over the result, as on a GPU that
// shares the memory.
std::size_t write_back(std::uintptr_t from, std::uintptr_t to) {
from = std::max(from, first_), to = std::min(to, last_);
if (from >= to) return 0;
AcquireSRWLockExclusive(&lock_);
// A page the title wrote since it was last copied holds the newer bytes already: its GPU result is dropped and
// the refresh's own copy carries the title's. A guarded page (read-only since that copy) or one asked about and
// found unchanged takes the GPU's.
const auto held = [&](std::size_t i) {
const std::uint8_t s = state_[i];
return (s & kZero) || (!(s & kProtected) && !(s & kClean));
};
std::size_t written = 0;
for (std::uintptr_t at = from & ~(kPage - 1); at < ((to + kPage - 1) & ~(kPage - 1));) {
std::size_t pages = 0;
while (at + (pages + 1) * kPage <= ((to + kPage - 1) & ~(kPage - 1)) &&
held((at - first_) / kPage + pages) == held((at - first_) / kPage))
++pages;
if (!held((at - first_) / kPage)) {
const std::uintptr_t a = std::max(at, from), b = std::min(at + pages * kPage, to);
reopen_locked(at, at + pages * kPage);
for (const Target& t : targets_) {
const std::uintptr_t x = std::max(a, t.begin), y = std::min(b, t.end);
if (x >= y || !t.shadow) continue;
std::memcpy(reinterpret_cast<void*>(x), t.shadow + (x - t.begin), y - x);
written += y - x;
}
}
at += pages * kPage;
}
ReleaseSRWLockExclusive(&lock_);
return written;
}

// The bytes of all targets, and how many there are.
std::size_t size() const { return target_bytes_; }
std::size_t targets() const { return targets_.size(); }
Expand Down Expand Up @@ -2125,6 +2162,7 @@ struct DeviceState {
if (!pages) return;
const leonida::submit_phases::Scope timed(leonida::submit_phases::shadows);
std::lock_guard lock(shadow_mutex);
write_back_titles(); // what the last submission wrote in the copies, before the forward copy below
if (shadows.empty()) return;
const auto start = clock::now();
// LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses, which no guard
Expand Down Expand Up @@ -2230,6 +2268,21 @@ struct DeviceState {
std::atomic<std::size_t> title_window_count{0}; // title_windows.size(), read without the mutex
std::uint64_t title_window_bytes = 0;
std::uint64_t title_window_cap = 64ull << 20;
// What the GPU wrote into a copy of the title's memory goes back to the title's pages: the ranges reached since
// the last submission (title_va_alias.h note_reached), copied back at the next refresh before the forward copy.
// A window is a read-side mirror, so without this a UAV or a raw write lands in the copy and the title never sees
// it (#1537, the WRITE_INVALID stop at the world start).
std::mutex title_write_back_mutex; // its own: taken under shadow_mutex, never the other way round
std::map<std::uint64_t, std::uint64_t> title_write_back; // start -> end, of the submission about to run
std::deque<std::pair<std::uint64_t, std::map<std::uint64_t, std::uint64_t>>> title_write_back_pending; // by ticket
std::uint64_t title_write_back_refused = 0; // ranges past the caps, logged once
std::uint64_t title_write_back_bytes = 0; // queued for this submission
std::uint64_t title_write_back_total = 0; // copied back, all submissions
std::uint64_t title_write_back_calls = 0; // log line count
std::uint64_t title_write_back_unfenced = 0;
static constexpr std::size_t kTitleWriteBackBatches = 64; // pending batches before the oldest goes back unfenced
static constexpr std::size_t kTitleWriteBackRanges = 8192; // ranges kept per submission
static constexpr std::uint64_t kTitleWriteBackBytes = 64ull << 20; // bytes copied back per submission
// The stream pools' mappings (title_gpu_views): one per readable run of a pool, kept for the device's life.
struct PoolSpan {
std::uint64_t source; // the readable side of the pair the copy is made from
Expand Down Expand Up @@ -2354,6 +2407,93 @@ struct DeviceState {
return offset;
}

// A binding of the title's memory reached for the coming submission: keep its range for the copy back after it.
// Over-inclusive on purpose (a read-only view costs a copy, a write is never missed: a V# has no read/write bit).
void note_title_write(std::uint64_t va, std::uint64_t bytes) {
static const bool on = [] {
char value[2] = {};
std::size_t length = 0;
return getenv_s(&length, value, sizeof(value), "LEONIDA_TITLE_WRITEBACK") != 0 || value[0] != '0';
}();
if (!on || !va || !bytes) return;
std::uint64_t lo = 0, hi = 0;
if (!leonida::title_va_aliases().title_memory(va, lo, hi) || va >= hi) return;
const std::uint64_t end = va + std::min(bytes, hi - va);
std::lock_guard lock(title_write_back_mutex);
auto it = title_write_back.lower_bound(va);
if (it != title_write_back.begin()) {
auto previous = std::prev(it);
if (previous->second >= va) {
if (previous->second < end) previous->second = end;
return;
}
}
if (it != title_write_back.end() && it->first <= end) {
it->second = std::max(it->second, end);
return;
}
if (title_write_back.size() >= kTitleWriteBackRanges || title_write_back_bytes >= kTitleWriteBackBytes) {
if (!title_write_back_refused++)
log_once("past LEONIDA_TITLE_WRITEBACK's caps: reached ranges are not copied back this submission; "
"ranges refused:",
1);
return;
}
title_write_back_bytes += end - va;
title_write_back.emplace(va, end);
}

// What the GPU wrote into those copies goes back to the title's pages, so a later read by the title or the next
// forward copy sees it. Only once the submission that wrote them has completed: a batch carries the ticket of the
// submission after it (a submission's commands are recorded before it exists), and is copied back when the
// context reports that ticket done. Runs at the start of a refresh, under shadow_mutex and before the forward
// copies, so a page the title wrote again is copied forward over the result.
void write_back_titles() {
if (!&context) return;
const std::uint64_t done = context->completed_retire_ticket();
std::vector<std::pair<uint64_t, std::uint64_t>> finished; // one entry per range, collected under the lock
{
std::lock_guard lock(title_write_back_mutex);
if (!title_write_back.empty()) {
// The ranges of the submission about to execute, which is the next ticket.
title_write_back_pending.push_back({context->submitted_retire_ticket() + 1,
std::move(title_write_back)});
title_write_back.clear();
title_write_back_bytes = 0;
}
bool forced = false;
while (!title_write_back_pending.empty() &&
(title_write_back_pending.front().first <= done ||
title_write_back_pending.size() > kTitleWriteBackBatches)) {
forced = forced || title_write_back_pending.front().first > done;
for (const auto& [begin, end] : title_write_back_pending.front().second)
finished.push_back({begin, end});
title_write_back_pending.pop_front();
}
// A queue held deep (console ordering) can leave batches waiting: the oldest go back anyway, once each.
if (forced && !title_write_back_unfenced++)
log_once("more than 64 title write-back batches wait on their submissions: the oldest are copied "
"back without their ticket; batches:",
1);
}
if (finished.empty()) return;
std::uint64_t written = 0, ranges = 0;
for (const auto& [begin, end] : finished)
for (const ShadowPagesPtr& s : shadows)
if (end > s->first() && begin < s->last()) {
const std::uint64_t bytes = s->write_back(begin, end);
written += bytes;
ranges += bytes != 0;
}
title_write_back_total += written;
if (!written) return;
if (++title_write_back_calls <= 4 || !(title_write_back_calls & (title_write_back_calls - 1)))
std::fprintf(stderr, "[rt] d3d12: %llu KiB of the GPU's writes in %llu reached range(s) went back to the "
"title's pages (%llu KiB so far)\n",
static_cast<unsigned long long>(written >> 10), static_cast<unsigned long long>(ranges),
static_cast<unsigned long long>(title_write_back_total >> 10));
}

// A stream pool's address (a CPU view paired with a GPU-only alias). Rule B
// first: the CPU view is where the host reads the frames, so that is what the copy is made from; the GPU-only
// pages are the same frames through the title's queue slot 31 and are read only when the CPU view is not
Expand Down Expand Up @@ -10946,6 +11086,9 @@ class Device final
[](void* device, std::uint64_t table, std::uint32_t descriptors) {
static_cast<DeviceState*>(device)->scan_title_table(table, descriptors);
});
leonida::title_va_aliases().set_noter([](void* device, std::uint64_t va, std::uint64_t bytes) {
static_cast<DeviceState*>(device)->note_title_write(va, bytes);
});
state_.image_memory = std::make_unique<leonida::ImageMemory>(
[device = info.device, make = state_.context->vk.vkAllocateMemory](std::uint32_t type, std::uint64_t bytes) {
VkMemoryAllocateInfo block{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
Expand Down Expand Up @@ -14913,7 +15056,7 @@ class Device final
// imported, or a shadow copied from them before every submission) and kept until the device goes, up to
// LEONIDA_TITLE_BUFFERS_MB (512 by default).
void make_title_buffer(std::uint64_t va, std::uint64_t bytes) {
if (!state_.context) return;
if (!&context()) return;
static const bool check_size = [] {
wchar_t flag[2]{};
return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_BUFFER_COVERAGE", flag, 2) == 1 && flag[0] == L'0');
Expand Down
24 changes: 24 additions & 0 deletions runtime/src/title_va_alias.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ class TitleVaAliases {
// memory (an arena VA, a buffer of the layer's).
using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va);
using TableScanner = void (*)(void* context, std::uint64_t table_va, std::uint32_t descriptors);
// Every binding resolved to a copy of the title's memory: [va, va + bytes) as they are reached at (the device keeps
// them for the copy back after the submission, see DeviceState::write_back_titles).
using Noter = void (*)(void* context, std::uint64_t va, std::uint64_t bytes);

// [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one
// replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range.
Expand Down Expand Up @@ -147,6 +150,7 @@ class TitleVaAliases {
std::uint64_t to = shader_va(va);
if (to != va) {
translated_[kind].fetch_add(1, std::memory_order_relaxed);
note_reached(va, bytes);
return to;
}
Resolver resolver;
Expand All @@ -158,6 +162,7 @@ class TitleVaAliases {
}
if (!resolver || !resolver(context, va, bytes, to)) return va;
(to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed);
if (to != va) note_reached(va, bytes);
return to;
}

Expand All @@ -167,6 +172,18 @@ class TitleVaAliases {
if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed);
}

// [va, va + bytes) is reached as a copy of the title's memory: the device keeps it for the copy back.
void note_reached(std::uint64_t va, std::uint64_t bytes) {
Noter noter;
void* context;
{
std::lock_guard lock(hook_mutex_);
noter = noter_;
context = hook_context_;
}
if (noter) noter(context, va, bytes);
}

// Before a submission: the device rewrites the buffer V#s of the `descriptors` slots the root signature declares
// for the table at `table_va` (a console VA in one of its shader-visible CBV/SRV/UAV heaps).
void scan_table(std::uint64_t table_va, std::uint32_t descriptors) {
Expand Down Expand Up @@ -307,10 +324,16 @@ class TitleVaAliases {
hook_context_ = nullptr;
resolver_ = nullptr;
scanner_ = nullptr;
noter_ = nullptr;
}
// The resolver alone, for a device that scans its descriptor tables itself.
void set_resolver(void* context, Resolver resolver) { set_hooks(context, resolver, nullptr); }
void clear_resolver(void* context) { clear_hooks(context); }
// Set after set_hooks, so the hook (and its context) stays the device's: what reached a copy of the title's memory.
void set_noter(Noter noter) {
std::lock_guard lock(hook_mutex_);
noter_ = noter;
}

std::size_t size() const { return count_.load(std::memory_order_acquire); }
std::uint64_t invalidations() const { return invalidations_.load(std::memory_order_acquire); }
Expand Down Expand Up @@ -344,6 +367,7 @@ class TitleVaAliases {
BufferMaker maker_ = nullptr;
Resolver resolver_ = nullptr;
TableScanner scanner_ = nullptr;
Noter noter_ = nullptr;
void* source_context_ = nullptr;
DescriptorSource source_ = nullptr;
std::atomic<std::uint64_t> pulled_{0};
Expand Down
Loading