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
9 changes: 9 additions & 0 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -1756,6 +1756,15 @@ The copies:
write-fault handler waits for the trackers' locks while the faulting thread may hold the process heap's lock (the
title's `XMemAlloc` blocks are `_aligned_malloc`'s), so the state changed under those locks allocates from a heap of
the runtime's own (`leonida::host_heap`), never the process heap.
- **What the GPU wrote into a copy stays** until the title changes the bytes under it. Some pages are copied at
every refresh without a sign that the title wrote them (mapped at two addresses, left writable, reopened with the
64 KiB around a written page, write-watched or pinned); copied whole, they overwrote a value a compute program had
stored in the copy for the next frame with the title's unchanged bytes, so it read back as the title's old value
every other frame. `ShadowPages` keeps a 64-bit sum per 256-byte piece of the bytes it copied last
(`runtime/src/shadow_keep.h`) and copies a piece only when the title's bytes differ; a piece zeroed because its page
went away is copied again in full once it comes back. Limit: a title that writes the same bytes again to reset a
value the GPU changed is not seen (that needs the GPU's writes to reach the title's pages). `LEONIDA_SHADOW_KEEP=0`
copies every page as before.
- **Only the title's memory** gets a copy: the blocks and ranges the xmem shims hand the title (`XMemAlloc`,
`XMemAllocDefault`, `XMemVirtualAlloc`, the title's `VirtualAlloc`). An address anywhere else, the runtime's or a
host DLL's memory included, is left as it was and counted, as is an arena VA or a buffer the layer made.
Expand Down
12 changes: 12 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3907,6 +3907,12 @@ if(TARGET Vulkan::Headers)
# 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)
# Two shadows over one page share their sums: a newly filled one must still follow the title's bytes, with
# LEONIDA_SHADOW_KEEP on and off (review by lixonik).
add_test(NAME d3d12_shadow_keep_refill COMMAND d3d12_title_va_test --shadow-keep-refill)
set_tests_properties(d3d12_shadow_keep_refill PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_SHADOW_KEEP=1")
add_test(NAME d3d12_shadow_keep_refill_off COMMAND d3d12_title_va_test --shadow-keep-refill)
set_tests_properties(d3d12_shadow_keep_refill_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_SHADOW_KEEP=0")
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 Expand Up @@ -4684,6 +4690,12 @@ if(TARGET Vulkan::Headers)
target_compile_options(console_heap_vsharp_slots_test PRIVATE /W4 /permissive- /utf-8)
endif()
add_test(NAME console_heap_vsharp_slots COMMAND console_heap_vsharp_slots_test)
# A slot-133 shadow keeps a GPU write until the title's bytes under it change (src/shadow_keep.h).
add_executable(shadow_keep_test test/shadow_keep_test.cpp)
if(WIN32 AND MSVC)
target_compile_options(shadow_keep_test PRIVATE /W4 /permissive- /utf-8)
endif()
add_test(NAME shadow_keep COMMAND shadow_keep_test)
# Queue construction cleans its Vulkan handles if holder registration runs out of host memory.
add_executable(vk_host_texture_order_test test/vk_host_texture_order_test.cpp)
target_link_libraries(vk_host_texture_order_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
Expand Down
1 change: 1 addition & 0 deletions runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
| `LEONIDA_CONSOLE_FIX_US` | `0` | Microseconds one submission may spend fixing the changed slots of a console descriptor heap's copy; `0` sets no limit. Past it, each further changed slot is written as a null descriptor and queued for `LEONIDA_CONSOLE_RETRY_US`, so a shader reads it as empty until its turn comes: a limit changes results, and can hang the GPU. |
| `LEONIDA_CONSOLE_RETRY_US` | `500` | Microseconds one submission may spend retrying, round robin, the console heap slots not settled yet (a T# whose texture does not exist yet, or one deferred by `LEONIDA_CONSOLE_FIX_US`). `0` retries all of them at every submission. |
| `LEONIDA_SHADOW_ALIAS_MS` | `0` | The shortest time, in milliseconds, between two copies of the title-memory pages that XMem maps at two addresses (no write guard can watch them) into the slot-133 shadows and title windows. `0` copies them at every submission; a larger value lets a GPU read of them be up to that many milliseconds behind the title's writes. |
| `LEONIDA_SHADOW_KEEP` | on | The slot-133 shadows and title windows copy a page only in the 256-byte pieces where the title's bytes changed since the last copy, so what a shader stored in the copy stays, also on pages copied without a sign that the title wrote them (aliased, unguarded, pinned). A title writing the same bytes again to reset such a value is not seen. `0` copies those pages whole, as before, overwriting the GPU's writes. |
| `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. |
| `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. |
| `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. |
Expand Down
81 changes: 77 additions & 4 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
#include "../src/resource_detile.h"
#include "../src/console_texture_layout.h"
#include "../src/shader_library.h"
#include "../src/shadow_keep.h"
#include "../src/dstorage_trace.h"
#include "../src/title_page_watch.h"
#include "../src/guarded_copy.h"
Expand Down Expand Up @@ -378,6 +379,7 @@ class ShadowPages {
last_ = (end_ + kPage - 1) & ~(kPage - 1);
state_.assign((last_ - first_) / kPage, 0);
idle_.assign(state_.size(), 0);
sums_.assign(state_.size() * kPieces, 0);
cover_.assign(state_.size(), 1);
targets_.push_back({begin_, end_, shadow});
index_targets();
Expand Down Expand Up @@ -593,6 +595,7 @@ class ShadowPages {
if (state_[i] & kZero) continue;
const auto [offset, bytes] = span_of(i, i + 1);
zero_targets(offset, bytes);
leonida::shadow_keep::forget(sums_.data(), first_, begin_ + offset, begin_ + offset + bytes);
if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset)
zeroed_.back().bytes += bytes;
else
Expand Down Expand Up @@ -660,6 +663,10 @@ class ShadowPages {
pieces_.walk_ms = std::chrono::duration<double, std::milli>(copy_start - walk_start).count();
std::size_t copied = 0;
for (const Job& job : jobs_) {
if (keep_gpu_writes()) { // only the pieces whose title bytes changed (src/shadow_keep.h)
copied += copy_changed(job);
continue;
}
std::uint8_t* run_dst = nullptr;
const std::uint8_t* run_src = nullptr;
std::size_t run_bytes = 0;
Expand Down Expand Up @@ -710,12 +717,14 @@ class ShadowPages {
const std::size_t n = (first_ - first) / kPage;
state_.insert(state_.begin(), n, std::uint8_t(0));
idle_.insert(idle_.begin(), n, std::uint8_t(0));
sums_.insert(sums_.begin(), n * kPieces, std::uint64_t(0));
cover_.insert(cover_.begin(), n, 0u);
first_ = first;
}
if (last > last_) {
state_.resize((last - first_) / kPage, 0);
idle_.resize(state_.size(), 0);
sums_.resize(state_.size() * kPieces, 0);
cover_.resize(state_.size(), 0);
last_ = last;
}
Expand All @@ -735,6 +744,8 @@ class ShadowPages {
state_[at + i] |= other.state_[i];
cover_[at + i] += other.cover_[i];
idle_[at + i] = other.idle_[i];
std::copy_n(other.sums_.begin() + std::ptrdiff_t(i * kPieces), kPieces,
sums_.begin() + std::ptrdiff_t((at + i) * kPieces));
}
targets_.insert(targets_.end(), other.targets_.begin(), other.targets_.end());
if (other.map_generation_ != map_generation_) map_generation_ = ~std::uint64_t(0);
Expand Down Expand Up @@ -779,15 +790,42 @@ class ShadowPages {
kind = classify(region);
}
const std::uintptr_t from = std::max(at, begin), to = std::min(next, end);
if (kind == Kind::zero)
if (kind == Kind::zero) {
std::memset(shadow + (from - begin), 0, to - from);
else
copy_run(shadow + (from - begin), reinterpret_cast<const std::uint8_t*>(from), to - from,
(region.Protect & PAGE_WRITECOMBINE) != 0);
} else {
const bool streaming = (region.Protect & PAGE_WRITECOMBINE) != 0;
copy_run(shadow + (from - begin), reinterpret_cast<const std::uint8_t*>(from), to - from, streaming);
// The sums stand for what every target holds. The new target now holds the title's current bytes, so
// the pieces where those differ from the sums are brought to the other targets too, and the sums
// follow; otherwise a title that later writes the old bytes back would leave the new target behind.
// Whole pieces (inside this page, so this region) up to the targets' ends, as a refresh sums them: a
// piece cut at the new target's edge would be summed short and copied again at the next refresh.
constexpr std::uintptr_t kPiece = leonida::shadow_keep::kPiece;
if (keep_gpu_writes())
reconcile(std::max(from & ~(kPiece - 1), begin_), std::min((to + kPiece - 1) & ~(kPiece - 1), end_),
streaming);
}
at = next;
}
}

// [from, to), readable title pages: the pieces whose bytes differ from the sums are copied to every target over
// them and their sums updated, as a refresh does.
void reconcile(std::uintptr_t from, std::uintptr_t to, bool streaming) {
alignas(64) std::uint8_t page[kPage];
for (std::uintptr_t va = from; va < to;) {
const std::size_t n = std::min<std::size_t>(to - va, kPage - (va & (kPage - 1)));
copy_run(page, reinterpret_cast<const std::uint8_t*>(va), n, streaming);
leonida::shadow_keep::copy_changed(
page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) {
for_each_target(a, b, [&](const Target& t, std::uintptr_t lo, std::uintptr_t hi) {
std::memcpy(t.shadow + (lo - t.begin), source + (lo - a), hi - lo);
});
});
va += n;
}
}

// Under shadow_mutex: `shadow` is no longer a target. Pages no other target covers are made writable again and
// passed over from now on. False when it isn't one of this tracker's.
bool remove_target(const std::uint8_t* shadow) {
Expand Down Expand Up @@ -1082,6 +1120,40 @@ class ShadowPages {
jobs_.push_back({offset, bytes, streaming, aliased});
}

// LEONIDA_SHADOW_KEEP (on; 0: every job copied whole, as before): a job's bytes reach the copies only where they
// differ from those copied last (src/shadow_keep.h), so a shader's write into a copy of pages copied without a
// sign that the title wrote them stays until the title changes those bytes.
// shortcut: a title that rewrites the same bytes to reset a GPU-written value is not seen; needs a real write
// signal (a write-back to the title's pages) then.
static bool keep_gpu_writes() {
static const bool on = [] {
char value[2] = {};
std::size_t length = 0;
return getenv_s(&length, value, sizeof(value), "LEONIDA_SHADOW_KEEP") != 0 || length == 0 ||
value[0] != '0';
}();
return on;
}
static constexpr std::size_t kPieces = kPage / leonida::shadow_keep::kPiece;
std::size_t copy_changed(const Job& job) {
std::size_t copied = 0;
alignas(64) std::uint8_t page[kPage];
for (std::size_t at = job.offset, end = job.offset + job.bytes; at < end;) {
const std::uintptr_t va = begin_ + at;
const std::size_t n = std::min<std::size_t>(end - at, kPage - (va & (kPage - 1)));
copy_run(page, reinterpret_cast<const std::uint8_t*>(va), n, job.streaming);
leonida::shadow_keep::copy_changed(
page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) {
for_each_target(a, b, [&](const Target& t, std::uintptr_t from, std::uintptr_t to) {
std::memcpy(t.shadow + (from - t.begin), source + (from - a), to - from);
copied += to - from;
});
});
at += n;
}
return copied;
}

// The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the
// targets over [from, to) are found from the first whose reach passes `from`.
void index_targets() {
Expand Down Expand Up @@ -1208,6 +1280,7 @@ class ShadowPages {
std::uint64_t reader_ = 0;
std::size_t watched_pages_ = 0, hot_pages_ = 0; // covered pages write-watched, and hot
Vector<std::uint8_t> idle_; // per 4 KiB page: refreshes a hot page went without a write (kCool)
Vector<std::uint64_t> sums_; // per 256-byte piece from first_: sum of the bytes copied last, 0: not known
bool runs_stale_ = false; // a page became hot or cold: watch_runs_ is rebuilt at the next refresh
std::uint64_t refresh_asks_ = 0;
std::uint64_t refresh_written_ = 0;
Expand Down
72 changes: 72 additions & 0 deletions runtime/src/shadow_keep.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// What a shadow copy of the title's pages keeps of the GPU's writes (LEONIDA_SHADOW_KEEP, shims/
// d3d12_vulkan_device.cpp ShadowPages). Some pages are copied at every refresh without a sign that the title wrote
// them (mapped at two addresses, unguarded, reopened with the 64 KiB block around a written page, write-watched or
// pinned): copied whole, their unchanged bytes overwrote what a shader had stored in the copy since. Here the title's
// bytes are compared, per 256-byte piece of the title's address space, with a 64-bit sum of those copied last, and
// only a piece that differs is copied. Portable: no Windows headers, no Vulkan.
#pragma once

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>

namespace leonida::shadow_keep {

inline constexpr std::size_t kPiece = 256;

// The sum of `n` bytes, never 0 (0 is "not known": the piece is copied at its next look).
// Four independent lanes over 32 bytes a step, so the multiplies do not wait on each other: about the speed of a
// copy (one chained lane read about 3.6 GB/s on an RTX 5080 machine's CPU, a copy about 18 GB/s).
inline std::uint64_t sum_of(const std::uint8_t* bytes, std::size_t n) {
constexpr std::uint64_t k = 0xff51afd7ed558ccdull;
const auto rotl = [](std::uint64_t x, int r) { return (x << r) | (x >> (64 - r)); };
std::uint64_t a0 = 0x9e3779b97f4a7c15ull ^ n, a1 = 0xc2b2ae3d27d4eb4full, a2 = 0x165667b19e3779f9ull,
a3 = 0x27d4eb2f165667c5ull;
std::size_t i = 0;
for (; i + 32 <= n; i += 32) {
std::uint64_t v[4];
std::memcpy(v, bytes + i, 32);
a0 = rotl(a0 ^ v[0], 31) * k;
a1 = rotl(a1 ^ v[1], 31) * k;
a2 = rotl(a2 ^ v[2], 31) * k;
a3 = rotl(a3 ^ v[3], 31) * k;
}
for (; i < n; i += 8) {
std::uint64_t v = 0;
std::memcpy(&v, bytes + i, n - i < 8 ? n - i : 8);
a0 = rotl(a0 ^ v, 31) * k;
}
std::uint64_t h = a0 ^ rotl(a1, 17) ^ rotl(a2, 29) ^ rotl(a3, 47);
h ^= h >> 33;
h *= 0xc4ceb9fe1a85ec53ull;
h ^= h >> 29;
return h | 1; // 0: not known
}

// `bytes` holds the title's bytes [va, va + n) as read now. sums[k] is the sum of the piece at base + k * kPiece
// (base kPiece-aligned) as last copied. Each piece, cut at kPiece boundaries of the address (the first and last may be
// partial), whose bytes differ from its sum takes the new sum and is handed to copy(from, to, source).
template <class Copy>
void copy_changed(const std::uint8_t* bytes, std::uintptr_t va, std::size_t n, std::uint64_t* sums,
std::uintptr_t base, Copy&& copy) {
for (std::size_t off = 0; off < n;) {
const std::size_t piece = std::min<std::size_t>(n - off, kPiece - ((va + off) & (kPiece - 1)));
std::uint64_t& known = sums[(va + off - base) / kPiece];
const std::uint64_t sum = sum_of(bytes + off, piece);
if (sum != known) {
known = sum;
copy(va + off, va + off + piece, bytes + off);
}
off += piece;
}
}

// The pieces over [from, to) are not known any more (the copies were changed another way, as zeroed): each is copied
// at its next look.
inline void forget(std::uint64_t* sums, std::uintptr_t base, std::uintptr_t from, std::uintptr_t to) {
if (from >= to) return;
std::fill(sums + (from - base) / kPiece, sums + (to - base + kPiece - 1) / kPiece, std::uint64_t(0));
}

} // namespace leonida::shadow_keep
Loading
Loading