upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/test
diff options
context:
space:
mode:
authorAslan2142 <jan.trencansky@protonmail.com>2026-11-26 15:41:00 +0100
committerGitHub <noreply@github.com>2026-11-26 15:41:00 +0100
commitfbf100b1b10e391625585fe6a8bf4e653662ca9a (patch)
tree497fe3bc8ef8b45d1ac8c68fa9f85196d08f11ad /runtime/test
parent73516a2902a9872e4d21d1bdbbde4e26059497c5 (diff)
parent484b21262a21f9a99148b89ad2458b389faf7bd1 (diff)
Merge pull request #2350 from aslan2142/linux-amd-world
Self-merge by a maintainer, on purpose: current main does not get through the world on Linux/AMD, and this brings the regression fixes (the single-wave round-loop fallback of 9f98dcc61, the wave64 choice driven by llvmpipe) together with eleven PRs the world run needed. Tested on main 73516a290: translator suite 500 files / 6,365 tests, 0 failed; 513 standard-library test files pass; check_no_game_data clean on 80 files; Linux ctest 112/112; Wine suite (clang-cl + xwin, RDNA2 iGPU, RADV) with no test going from pass to fail. Not tested: native Windows, NVIDIA. The included PRs are closed in favour of this one with credit to their authors. AI-assisted (Claude Code, Claude Opus 5.5 and Claude Fable 5.2).
Diffstat (limited to 'runtime/test')
-rw-r--r--runtime/test/address_guard_test.cpp127
-rw-r--r--runtime/test/conservative_raster_test.cpp13
-rw-r--r--runtime/test/console_heap_copy_test.cpp168
-rw-r--r--runtime/test/console_heap_vsharp_slots_test.cpp75
-rw-r--r--runtime/test/d3d12_console_heap_mirror_test.cpp215
-rw-r--r--runtime/test/d3d12_existing_heap_test.cpp137
-rw-r--r--runtime/test/d3d12_mesh_test.cpp30
-rw-r--r--runtime/test/d3d12_title_va_test.cpp210
-rw-r--r--runtime/test/d3d12_translated_draw_test.cpp1
-rw-r--r--runtime/test/d3d12_xmem_placed_test.cpp77
-rw-r--r--runtime/test/dstorage_test.cpp255
-rw-r--r--runtime/test/gameinput_no_sdl_test.cpp10
-rw-r--r--runtime/test/gameinput_test.cpp31
-rw-r--r--runtime/test/geometry_views_test.cpp110
-rw-r--r--runtime/test/heavy_pipeline_cache_test.cpp109
-rw-r--r--runtime/test/list_value_wait_budget_test.cpp348
-rw-r--r--runtime/test/shaders/cs_address_guard.asm57
-rw-r--r--runtime/test/title_memory_map_test.cpp45
-rw-r--r--runtime/test/vk_test_device.h10
-rw-r--r--runtime/test/xapu_chad_test.cpp261
-rw-r--r--runtime/test/xapu_opus_test.cpp193
-rw-r--r--runtime/test/xmem_test.cpp120
-rw-r--r--runtime/test/xs_proxy_mock_test.cpp79
23 files changed, 2620 insertions, 61 deletions
diff --git a/runtime/test/address_guard_test.cpp b/runtime/test/address_guard_test.cpp
new file mode 100644
index 000000000..02baa7bb8
--- /dev/null
+++ b/runtime/test/address_guard_test.cpp
@@ -0,0 +1,127 @@
1// leonida::address_guard::AddressGuardTable (src/address_guard.h): the address guard's page table. Pages any byte
2// of a span touches are backed, a chunk keeps its level-2 block for good, a released span's bits go, negative
3// offsets (a buffer below the arena) and spans across 4 GiB chunks work, only changed words are written, level-2
4// before level-1, and a chunk past the table's room gets the full block. No GPU, no device.
5#include "../src/address_guard.h"
6
7#include <cstdint>
8#include <cstdio>
9#include <utility>
10#include <vector>
11
12#define EXPECT(condition) do { \
13 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
14} while (0)
15
16namespace {
17
18using leonida::address_guard::AddressGuardTable;
19using Spans = std::vector<std::pair<std::uint64_t, std::uint64_t>>;
20namespace ag = leonida::address_guard;
21
22constexpr std::uint64_t kLimit = 0x80000; // the "arena"
23constexpr std::uint64_t kGiB = 1ull << 30;
24
25// A copy of the GPU's table, written only through assign()'s callback, and the order of the writes.
26struct Gpu {
27 std::vector<std::uint32_t> words;
28 std::vector<std::size_t> order;
29 explicit Gpu(const AddressGuardTable& t) : words(t.words()) {}
30 auto writer() {
31 return [this](std::size_t i, std::uint32_t v) {
32 words[i] = v;
33 order.push_back(i);
34 };
35 }
36};
37
38int basics() {
39 AddressGuardTable t(4);
40 Gpu gpu(t);
41 EXPECT(t.word_count() == ag::kGuardLevel1 + 6u * ag::kGuardBlockWords);
42 EXPECT(!t.passes(0x90000, 4, kLimit));
43 EXPECT(t.passes(0x7fffc, 4, kLimit)); // below the limit: no lookup
44 EXPECT(!t.passes(0x7fffc, 8, kLimit)); // its last byte is past it, on an unbacked page
45
46 const Spans spans{{0x90000, 0x90001}, {5 * 4 * kGiB + 0x1000, 5 * 4 * kGiB + 0x3000}};
47 const std::size_t written = t.assign(spans, gpu.writer());
48 EXPECT(written > 0);
49 EXPECT(gpu.words == t.words());
50 EXPECT(t.blocks_used() == 2);
51 EXPECT(t.passes(0x90000, 4, kLimit));
52 EXPECT(t.passes(0x90ffc, 4, kLimit)); // one byte of the span marks the whole page
53 EXPECT(!t.passes(0x90ffc, 8, kLimit)); // the last byte is on the next page
54 EXPECT(t.passes(5 * 4 * kGiB + 0x2ff0, 16, kLimit));
55 EXPECT(!t.passes(5 * 4 * kGiB + 0x3000, 4, kLimit));
56 EXPECT(!t.passes(6 * 4 * kGiB, 4, kLimit));
57
58 // Level-2 words are written before level-1 ones.
59 bool seen_level1 = false;
60 for (const std::size_t i : gpu.order) {
61 if (i < ag::kGuardLevel1) seen_level1 = true;
62 else EXPECT(!seen_level1);
63 }
64
65 // The same spans again: nothing to write.
66 gpu.order.clear();
67 EXPECT(t.assign(spans, gpu.writer()) == 0);
68
69 // A release: its bits go, its chunk keeps its block.
70 const std::uint32_t chunk5 = t.words()[5];
71 EXPECT(chunk5 >= ag::kFirstBlock);
72 EXPECT(t.assign(Spans{{0x90000, 0x91000}}, gpu.writer()) > 0);
73 EXPECT(gpu.words == t.words());
74 EXPECT(!t.passes(5 * 4 * kGiB + 0x2ff0, 4, kLimit));
75 EXPECT(t.words()[5] == chunk5);
76 EXPECT(t.passes(0x90000, 4, kLimit));
77 return 0;
78}
79
80int negative_and_wide() {
81 AddressGuardTable t(4);
82 Gpu gpu(t);
83 // A buffer 8 KiB below heap_base (LEONIDA_IMPORT_BELOW_ARENA=1), as the 48-bit offset a V# holds.
84 const std::uint64_t below = (0ull - 0x2000) & ag::kMask48;
85 // One that runs from below heap_base into the arena's first page: wraps through 2^48.
86 const std::uint64_t wrap = (0ull - 0x1000) & ag::kMask48;
87 // A 6 GiB buffer across two chunks: whole words of bits.
88 const std::uint64_t wide = 8 * kGiB + 0x10000;
89 t.assign(Spans{{below, below + 0x1000}, {wrap, 0x1000}, {wide, wide + 6 * kGiB}}, gpu.writer());
90 EXPECT(gpu.words == t.words());
91 EXPECT(t.passes(below, 4, kLimit));
92 EXPECT(t.passes(0ull - 0x2000, 4, kLimit)); // the same offset sign-extended, as the shaders pass it
93 EXPECT(t.passes(0ull - 4, 8, kLimit)); // across zero: both pages backed
94 EXPECT(!t.passes(0ull - 0x3000, 4, kLimit));
95 EXPECT(t.passes(wide, 4, kLimit));
96 EXPECT(t.passes(wide + 4 * kGiB, 4, kLimit));
97 EXPECT(t.passes(wide + 6 * kGiB - 4, 4, kLimit));
98 EXPECT(!t.passes(wide + 6 * kGiB, 4, kLimit));
99 EXPECT(!t.passes(wide - 4, 8, kLimit));
100 EXPECT(t.blocks_used() == 4); // chunks 0xffff, 0 (the wrap), 2 and 3
101 return 0;
102}
103
104int out_of_room() {
105 AddressGuardTable t(1);
106 Gpu gpu(t);
107 t.assign(Spans{{4 * kGiB, 4 * kGiB + 1}, {8 * kGiB, 8 * kGiB + 1}}, gpu.writer());
108 EXPECT(t.blocks_used() == 1);
109 EXPECT(t.overflowed() == 1);
110 EXPECT(t.passes(4 * kGiB, 4, kLimit));
111 EXPECT(!t.passes(4 * kGiB + 0x1000, 4, kLimit));
112 EXPECT(t.passes(8 * kGiB + 0x5000, 4, kLimit)); // the full block: all of that chunk passes
113 EXPECT(t.words()[2] == ag::kFullBlock);
114 return 0;
115}
116
117} // namespace
118
119int main() {
120 // "LGUARD01" little-endian, as tools/address_guard.py packs it and the shaders compare it.
121 static_assert(ag::magic() == 0x313044524155474Cull);
122 if (int r = basics()) return r;
123 if (int r = negative_and_wide()) return r;
124 if (int r = out_of_room()) return r;
125 std::puts("address_guard_test: ok");
126 return 0;
127}
diff --git a/runtime/test/conservative_raster_test.cpp b/runtime/test/conservative_raster_test.cpp
index b862e5fcb..72ee4d516 100644
--- a/runtime/test/conservative_raster_test.cpp
+++ b/runtime/test/conservative_raster_test.cpp
@@ -1,6 +1,7 @@
1#include "../src/conservative_raster.h" 1#include "../src/conservative_raster.h"
2#include <cstdio> 2#include <cstdio>
3#include <limits> 3#include <limits>
4#include <vector>
4 5
5int main() { 6int main() {
6 using leonida::conservative_raster::tier1; 7 using leonida::conservative_raster::tier1;
@@ -38,6 +39,18 @@ int main() {
38 const auto requirements = inner_coverage_requirements(module); 39 const auto requirements = inner_coverage_requirements(module);
39 check(requirements.valid && requirements.fully_covered && requirements.post_depth); 40 check(requirements.valid && requirements.fully_covered && requirements.post_depth);
40 check(!inner_coverage_requirements(std::span(module).first(9)).valid); 41 check(!inner_coverage_requirements(std::span(module).first(9)).valid);
42 using leonida::conservative_raster::mesh_outputs_triangles;
43 const auto with_mode = [](std::uint32_t mode) {
44 return std::vector<std::uint32_t>{0x07230203, 0x00010500, 0, 2, 0, (3u << 16) | 16, 1, mode};
45 };
46 check(mesh_outputs_triangles(with_mode(5298))); // OutputTrianglesEXT
47 check(!mesh_outputs_triangles(with_mode(5269))); // OutputLinesEXT
48 check(!mesh_outputs_triangles(with_mode(27))); // OutputPoints
49 check(!mesh_outputs_triangles(with_mode(26))); // OutputVertices: no output topology
50 check(!mesh_outputs_triangles({}));
51 auto truncated = with_mode(5298);
52 truncated.pop_back();
53 check(!mesh_outputs_triangles(truncated));
41 const std::uint32_t zero_count[] = {0x07230203, 0x00010500, 0, 2, 0, 0}; 54 const std::uint32_t zero_count[] = {0x07230203, 0x00010500, 0, 2, 0, 0};
42 check(!inner_coverage_requirements(zero_count).valid); 55 check(!inner_coverage_requirements(zero_count).valid);
43 const std::uint32_t ordinary[] = {0x07230203, 0x00010500, 0, 2, 0, (2u << 16) | 17, 1}; 56 const std::uint32_t ordinary[] = {0x07230203, 0x00010500, 0, 2, 0, (2u << 16) | 17, 1};
diff --git a/runtime/test/console_heap_copy_test.cpp b/runtime/test/console_heap_copy_test.cpp
new file mode 100644
index 000000000..48618170e
--- /dev/null
+++ b/runtime/test/console_heap_copy_test.cpp
@@ -0,0 +1,168 @@
1// Portable CPU-only unit test for leonida::ConsoleHeapCopy (runtime/src/console_heap_copy.h): the host-RAM mirror of a
2// console heap's translated copy. A plain buffer stands in for the copy in the GPU address arena. Checks that every
3// write and zero reaches both, that the null guard past the heap stays out of the mirror, that mismatches() finds a
4// write that bypassed the helpers (the LEONIDA_HEAP_MIRROR_CHECK case), and that without a mirror view() is the copy.
5// Then times a filtered release sweep over a large heap reading the mirror (the work refresh_console_heap does per
6// rescan with LEONIDA_CONSOLE_RELEASE_FILTER=1), for reference; no game data.
7#include "../src/console_heap_copy.h"
8#include "../src/console_heap_vsharp_slots.h"
9#include "../src/descriptor_range_changes.h"
10
11#include <chrono>
12#include <cstdint>
13#include <cstdio>
14#include <cstring>
15#include <vector>
16
17#define EXPECT(condition) \
18 do { \
19 if (!(condition)) { \
20 std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \
21 return 1; \
22 } \
23 } while (0)
24
25namespace {
26
27using leonida::ConsoleHeapCopy;
28constexpr std::size_t kSlot = 32;
29
30int test_writes_reach_both() {
31 constexpr std::size_t slots = 256, bytes = slots * kSlot, guard = 4096;
32 std::vector<std::uint8_t> gpu(bytes + guard, 0xCD);
33 ConsoleHeapCopy copy;
34 EXPECT(!copy);
35 copy.attach(gpu.data(), bytes, true);
36 EXPECT(copy && copy.mirrored() && copy.gpu() == gpu.data() && copy.bytes() == bytes);
37 EXPECT(copy.view() != gpu.data());
38 // Creation: the copy and its guard zeroed; the mirror covers the heap only.
39 copy.zero(0, bytes + guard);
40 for (const auto b : gpu) EXPECT(b == 0);
41 std::vector<std::size_t> differ;
42 EXPECT(copy.mismatches(kSlot, 8, differ) == 0 && differ.empty());
43
44 std::uint32_t w[8] = {0x1000, 0x20, 64, 0x3fffu, 0, 0, 0, 0};
45 for (std::size_t s = 0; s < slots; s += 3) {
46 w[0] = std::uint32_t(0x1000 + s * 0x40);
47 copy.write(s * kSlot, w, sizeof(w));
48 }
49 copy.zero(9 * kSlot, kSlot);
50 copy.zero(64 * kSlot, 32 * kSlot); // a zeroed range of slots
51 // A sampler heap's whole range copied at once.
52 std::vector<std::uint8_t> run(5 * kSlot + 7, 0x5A);
53 copy.write(200 * kSlot + 3, run.data(), run.size());
54 EXPECT(std::memcmp(copy.view(), gpu.data(), bytes) == 0);
55 EXPECT(copy.mismatches(kSlot, 8, differ) == 0);
56 // Past the heap: the copy's guard only, nothing out of the mirror's bounds.
57 copy.zero(bytes - kSlot, kSlot + guard);
58 std::uint32_t tail[8];
59 std::memcpy(tail, copy.view() + bytes - kSlot, sizeof(tail));
60 for (const auto t : tail) EXPECT(t == 0);
61 EXPECT(copy.mismatches(kSlot, 8, differ) == 0);
62 std::puts("writes and zeros reach the copy and the mirror; the guard stays out of the mirror");
63 return 0;
64}
65
66int test_mismatch_found() {
67 constexpr std::size_t slots = 8192, bytes = slots * kSlot; // 256 KiB: more than one compare block
68 std::vector<std::uint8_t> gpu(bytes, 0);
69 ConsoleHeapCopy copy;
70 copy.attach(gpu.data(), bytes, true);
71 // Writes that bypass the helpers (a missed write site, or the GPU writing the copy).
72 gpu[5 * kSlot + 4] = 1;
73 gpu[4000 * kSlot] = 2;
74 gpu[4001 * kSlot + 31] = 3;
75 gpu[8191 * kSlot + 16] = 4;
76 std::vector<std::size_t> differ;
77 EXPECT(copy.mismatches(kSlot, 3, differ) == 4);
78 EXPECT(differ.size() == 3 && differ[0] == 5 && differ[1] == 4000 && differ[2] == 4001);
79 EXPECT(copy.mismatches(kSlot, 8, differ) == 4 && differ.size() == 4 && differ[3] == 8191);
80 std::puts("mismatches() finds writes that bypassed the mirror, in slot order");
81 return 0;
82}
83
84int test_without_mirror() {
85 constexpr std::size_t bytes = 64 * kSlot;
86 std::vector<std::uint8_t> gpu(bytes, 0);
87 ConsoleHeapCopy copy;
88 copy.attach(gpu.data(), bytes, false); // the copy is host RAM already
89 EXPECT(!copy.mirrored() && copy.view() == gpu.data());
90 const std::uint32_t w[8] = {1, 2, 3, 4, 5, 6, 7, 8};
91 copy.write(3 * kSlot, w, sizeof(w));
92 EXPECT(!std::memcmp(gpu.data() + 3 * kSlot, w, sizeof(w)));
93 std::vector<std::size_t> differ;
94 EXPECT(copy.mismatches(kSlot, 8, differ) == 0);
95
96 copy.attach(gpu.data(), bytes, true);
97 EXPECT(copy.mirrored());
98 copy.drop_mirror(); // the GPU pass writes the copy from now on
99 EXPECT(!copy.mirrored() && copy.view() == gpu.data());
100 std::puts("without a mirror view() is the copy");
101 return 0;
102}
103
104// The filtered release sweep of refresh_console_heap over a heap of 576k slots (18 MiB) with 470k live V# slots, one
105// released range touching about 2%: the time per sweep with its words read from host RAM.
106int bench_filtered_sweep() {
107 constexpr std::size_t slots = 576 * 1024, bytes = slots * kSlot;
108 std::vector<std::uint8_t> previous(bytes, 0), gpu(bytes, 0);
109 ConsoleHeapCopy copy;
110 copy.attach(gpu.data(), bytes, true);
111 leonida::ConsoleHeapVsharpSlots live;
112 live.reset(slots);
113 constexpr std::uint64_t kBuffers = 4096, kBufferBytes = 1 << 20, kArena = 1ull << 32;
114 for (std::size_t s = 0; s < slots; ++s) {
115 if (s % 11 == 10) continue; // T#s and empty slots
116 const std::uint64_t base = 0x100000 + (s * 2654435761u % kBuffers) * kBufferBytes + (s % 64) * 256;
117 std::uint32_t w[8] = {std::uint32_t(base), std::uint32_t(base >> 32) & 0xffffu, 256, 0x00027fac, 0, 0, 0, 0};
118 std::memcpy(previous.data() + s * kSlot, w, sizeof(w));
119 copy.write(s * kSlot, w, sizeof(w));
120 live.set(s, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w));
121 }
122 leonida::DescriptorRanges backing, aliases;
123 for (std::uint64_t b = 0; b < kBuffers; b += 50) // about 2% of the buffers released
124 backing.ranges.push_back({kArena + 0x100000 + b * kBufferBytes, kArena + 0x100000 + (b + 1) * kBufferBytes - 1});
125 backing.merge();
126 const auto bda = [&](std::uint64_t base) { return kArena + base; };
127 const auto affected = [&](const std::uint32_t* src, const std::uint32_t* dst) {
128 if ((src[3] >> 30) || !src[2]) return false;
129 const std::uint64_t base = std::uint64_t(src[0]) | (std::uint64_t(src[1] & 0xffff) << 32);
130 const std::uint64_t fixed = std::uint64_t(dst[0]) | (std::uint64_t(dst[1] & 0xffff) << 32);
131 const auto stride = (src[1] >> 16) & 0x3fff;
132 const std::uint64_t n = std::uint64_t(src[2]) * (stride ? stride : 1);
133 return aliases.overlaps(base, 1) || backing.overlaps(bda(base), n) || (dst[2] && backing.overlaps(bda(fixed), n));
134 };
135 constexpr int kRuns = 9;
136 double best = 1e30, first = 0;
137 std::size_t hits = 0;
138 for (int run = 0; run < kRuns; ++run) {
139 hits = 0;
140 const auto start = std::chrono::steady_clock::now();
141 const std::uint8_t* const translated = copy.view();
142 live.for_each([&](std::size_t slot) {
143 const auto at = slot * kSlot;
144 const auto* src = reinterpret_cast<const std::uint32_t*>(previous.data() + at);
145 const auto* dst = reinterpret_cast<const std::uint32_t*>(translated + at);
146 if (affected(src, dst) || affected(src + 4, dst + 4)) ++hits;
147 });
148 const double took = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
149 if (!run) first = took;
150 best = std::min(best, took);
151 }
152 EXPECT(hits > 0 && hits < live.live_count() / 10);
153 std::printf("filtered sweep over %zu live slots of %zu MiB, %zu affected: %.2f ms (best of %d, first %.2f), words "
154 "from the host mirror\n",
155 live.live_count(), bytes >> 20, hits, best, kRuns, first);
156 return 0;
157}
158
159} // namespace
160
161int main() {
162 if (test_writes_reach_both()) return 1;
163 if (test_mismatch_found()) return 1;
164 if (test_without_mirror()) return 1;
165 if (bench_filtered_sweep()) return 1;
166 std::puts("ok");
167 return 0;
168}
diff --git a/runtime/test/console_heap_vsharp_slots_test.cpp b/runtime/test/console_heap_vsharp_slots_test.cpp
index ebb74be45..aa56b4fdd 100644
--- a/runtime/test/console_heap_vsharp_slots_test.cpp
+++ b/runtime/test/console_heap_vsharp_slots_test.cpp
@@ -246,6 +246,80 @@ int test_retail_sized_heap_sparse_scan() {
246 return 0; 246 return 0;
247} 247}
248 248
249int test_console_fix_budget_buffer_vsharp_non_deferral() {
250 // Verifies that under fix_console_slots budget expiry (fix_over == true), buffer V# descriptors
251 // (!(w[3] >> 30)) are never deferred/nulled, while image T# descriptors ((w[3] >> 30) != 0) are deferred.
252 constexpr std::size_t kSlots = 16;
253 std::vector<std::array<std::uint32_t, 8>> gpu_copy(kSlots);
254 for (auto& slot : gpu_copy) slot.fill(0);
255
256 ConsoleHeapVsharpSlots tracked;
257 tracked.reset(kSlots);
258
259 // Populate slots with alternating buffer V# and image T# descriptors:
260 // Even slots: live buffer V#s
261 // Odd slots: image T#s
262 for (std::size_t i = 0; i < kSlots; ++i) {
263 std::array<std::uint32_t, 8> w{};
264 if ((i & 1u) == 0) {
265 // Buffer V#: w[3] >> 30 == 0, num_records != 0
266 w[0] = static_cast<std::uint32_t>(0x1000 + i * 0x100);
267 w[1] = 0x20;
268 w[2] = 256;
269 w[3] = 0x00010000u; // w[3] >> 30 == 0
270 } else {
271 // Image T#: w[3] >> 30 != 0
272 w[0] = static_cast<std::uint32_t>(0x5000 + i * 0x100);
273 w[2] = 128;
274 w[3] = (2u << 30) | 0x1234u; // w[3] >> 30 == 2
275 }
276 gpu_copy[i] = w;
277 tracked.set(i, ConsoleHeapVsharpSlots::is_live_vsharp(w.data()));
278 }
279
280 // Now simulate fix_console_slots when budget is expired (fix_over == true):
281 // Buffer V#s must be fixed in-place and never nulled/deferred; only image T#s are deferred.
282 std::size_t deferred_fixes = 0;
283 std::vector<std::uint32_t> retries;
284 const bool fix_over = true;
285
286 for (std::size_t slot = 0; slot < kSlots; ++slot) {
287 const std::array<std::uint32_t, 8>& input = gpu_copy[slot];
288 const std::uint32_t w3 = input[3];
289 const bool is_buffer_vsharp = !(w3 >> 30);
290
291 if (fix_over && !is_buffer_vsharp) {
292 // Image T#: deferred past budget
293 gpu_copy[slot].fill(0);
294 tracked.clear(slot);
295 ++deferred_fixes;
296 retries.push_back(static_cast<std::uint32_t>(slot));
297 continue;
298 }
299
300 // Buffer V#: fixed immediately, not deferred
301 tracked.set(slot, ConsoleHeapVsharpSlots::is_live_vsharp(input.data()));
302 }
303
304 // All odd slots (image T#s) must have been deferred (nulled)
305 EXPECT(deferred_fixes == kSlots / 2);
306 EXPECT(retries.size() == kSlots / 2);
307 for (std::size_t slot : retries) {
308 EXPECT((slot & 1u) == 1u);
309 EXPECT(!tracked.test(slot));
310 EXPECT(gpu_copy[slot][0] == 0 && gpu_copy[slot][2] == 0);
311 }
312
313 // All even slots (buffer V#s) must have been preserved and remain live
314 for (std::size_t i = 0; i < kSlots; i += 2) {
315 EXPECT(tracked.test(i));
316 EXPECT(gpu_copy[i][2] == 256);
317 EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(gpu_copy[i].data()));
318 }
319 EXPECT(tracked.live_count() == kSlots / 2);
320 return 0;
321}
322
249} // namespace 323} // namespace
250 324
251int main() { 325int main() {
@@ -254,6 +328,7 @@ int main() {
254 if (test_in_place_invalidation_mutation()) return 1; 328 if (test_in_place_invalidation_mutation()) return 1;
255 if (test_differential_equivalence_against_linear_copy()) return 1; 329 if (test_differential_equivalence_against_linear_copy()) return 1;
256 if (test_retail_sized_heap_sparse_scan()) return 1; 330 if (test_retail_sized_heap_sparse_scan()) return 1;
331 if (test_console_fix_budget_buffer_vsharp_non_deferral()) return 1;
257 std::printf("console_heap_vsharp_slots_test: ok\n"); 332 std::printf("console_heap_vsharp_slots_test: ok\n");
258 return 0; 333 return 0;
259} 334}
diff --git a/runtime/test/d3d12_console_heap_mirror_test.cpp b/runtime/test/d3d12_console_heap_mirror_test.cpp
new file mode 100644
index 000000000..9a1319bb3
--- /dev/null
+++ b/runtime/test/d3d12_console_heap_mirror_test.cpp
@@ -0,0 +1,215 @@
1// The host-RAM mirror of a console descriptor heap's GPU copy (src/console_heap_copy.h) through a heap's life, with
2// LEONIDA_CONSOLE_RELEASE_FILTER=1 (the release sweep reads the mirror to pick the slots to fix): the first refresh,
3// slots the title rewrites and zeroes after it, and a released buffer whose V#s the sweep must find and null. After
4// each step the GPU copy holds what it should and the mirror agrees with it byte for byte. Run twice by ctest: with
5// the mirror, and with LEONIDA_HEAP_MIRROR=0 (no mirror; the sweep reads the copy, as before it), where the copy must
6// come out the same. Nothing dispatches through a descriptor. No game data.
7#include "vk_test_device.h"
8#include "../shims/d3d12_com.h"
9#include "../src/gfx10_descriptors.h"
10
11#include <cstdint>
12#include <cstdio>
13#include <cstdlib>
14#include <cstring>
15
16#define EXPECT(condition) do { \
17 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
18} while (0)
19
20namespace {
21
22template<class T>
23struct Ref {
24 T* p = nullptr;
25 ~Ref() { reset(); }
26 void reset() {
27 if (p) p->Release();
28 p = nullptr;
29 }
30 T* operator->() const { return p; }
31};
32
33constexpr UINT kDescriptor = 32;
34constexpr UINT kViewBytes = 256;
35constexpr UINT kBufferBytes = 64 * 1024;
36
37D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) {
38 D3D12_RESOURCE_DESC desc{};
39 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
40 desc.Width = bytes;
41 desc.Height = 1;
42 desc.DepthOrArraySize = 1;
43 desc.MipLevels = 1;
44 desc.SampleDesc.Count = 1;
45 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
46 return desc;
47}
48
49leonida::gfx10::BufferWords raw_vsharp(std::uint64_t address) {
50 leonida::gfx10::Buffer b{};
51 b.address = address;
52 b.num_records = kViewBytes;
53 b.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT);
54 b.oob_select = leonida::gfx10::OobSelect::raw;
55 return leonida::gfx10::encode(b);
56}
57
58std::uint64_t base_of(const std::uint32_t* w) { return std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); }
59bool zero_size(const std::uint32_t* w) { return base_of(w) == 0 && w[2] == 0; }
60
61struct Heap {
62 static constexpr UINT slots = 4096;
63 static constexpr std::uint64_t bytes = std::uint64_t(slots) * kDescriptor;
64};
65
66// What a slot of the copy is expected to hold: the buffer it names, or nothing.
67enum class Want { a, b, none, zero };
68
69int check(ID3D12Device* device, std::uint64_t shader_va, std::uint64_t title, const Want* want, std::uint64_t a_va,
70 std::uint64_t b_va, bool mirrored, const char* step) {
71 static std::uint32_t copy[Heap::slots][kDescriptor / 4];
72 EXPECT(rt::d3d12::read_arena(device, shader_va, copy, sizeof(copy)));
73 for (UINT s = 0; s < Heap::slots; ++s) {
74 const std::uint32_t* w = copy[s];
75 bool ok = true;
76 switch (want[s]) {
77 case Want::a: ok = base_of(w) >= a_va && base_of(w) < a_va + kBufferBytes && w[2] == kViewBytes; break;
78 case Want::b: ok = base_of(w) >= b_va && base_of(w) < b_va + kBufferBytes && w[2] == kViewBytes; break;
79 case Want::none: ok = zero_size(w); break;
80 case Want::zero: for (int i = 0; i < 8; ++i) ok = ok && !w[i]; break;
81 }
82 if (!ok) {
83 std::fprintf(stderr, "%s: slot %u holds %08x %08x %08x %08x, wanted %d\n", step, s, w[0], w[1], w[2], w[3],
84 int(want[s]));
85 return 1;
86 }
87 }
88 const long long differ = rt::d3d12::console_heap_mirror_mismatches(device, title);
89 if (mirrored) EXPECT(differ == 0);
90 else EXPECT(differ == -1);
91 std::printf("%s: copy as expected, %s\n", step, mirrored ? "mirror agrees with it" : "no mirror");
92 return 0;
93}
94
95int run(ID3D12Device* device, bool mirrored) {
96 const D3D12_COMMAND_QUEUE_DESC queue_desc{};
97 Ref<ID3D12CommandQueue> queue;
98 Ref<ID3D12Fence> fence;
99 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
100 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
101 UINT64 fence_value = 0;
102 Ref<ID3D12CommandAllocator> allocator;
103 Ref<ID3D12GraphicsCommandList> list;
104 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
105 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
106 IID_PPV_ARGS(&list.p))));
107 EXPECT(SUCCEEDED(list->Close()));
108 ID3D12CommandList* lists[] = {list.p};
109 const auto submit = [&]() -> int { // every submission refreshes the console heaps first
110 queue->ExecuteCommandLists(1, lists);
111 EXPECT(SUCCEEDED(queue->Signal(fence.p, ++fence_value)));
112 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr)));
113 return 0;
114 };
115
116 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
117 const auto desc = buffer_desc(kBufferBytes);
118 Ref<ID3D12Resource> a, b;
119 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc,
120 D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&a.p))));
121 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc,
122 D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&b.p))));
123 const std::uint64_t a_va = a->GetGPUVirtualAddress(), b_va = b->GetGPUVirtualAddress();
124 EXPECT(a_va && b_va);
125
126 auto* title = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, Heap::bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
127 EXPECT(title);
128 static Want want[Heap::slots];
129 const auto put = [&](UINT slot, std::uint64_t va, Want w) {
130 const auto words = raw_vsharp(va);
131 std::memcpy(title + slot * kDescriptor, words.data(), sizeof(words));
132 want[slot] = w;
133 };
134 for (UINT s = 0; s < Heap::slots; ++s) want[s] = Want::zero;
135 // Before the heap exists: slots 0-1023 name A, 1024-2047 B, the rest empty but for one data slot.
136 for (UINT s = 0; s < 1024; ++s) put(s, a_va + (s % 256) * kViewBytes, Want::a);
137 for (UINT s = 1024; s < 2048; ++s) put(s, b_va + (s % 256) * kViewBytes, Want::b);
138 const std::uint32_t data[8] = {0x12345000u, 0x00007777u, 0x00000400u, 0x40000000u, 1, 2, 3, 4};
139 std::memcpy(title + 3000 * kDescriptor, data, sizeof(data));
140 want[3000] = Want::none; // its descriptor half null in the copy (fix_console_slot)
141
142 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, Heap::slots,
143 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
144 Ref<ID3D12DescriptorHeap> heap;
145 const auto title_va = reinterpret_cast<std::uint64_t>(title);
146 EXPECT(SUCCEEDED(rt::d3d12::create_console_descriptor_heap(device, &heap_desc, title_va, Heap::bytes,
147 IID_PPV_ARGS(&heap.p))));
148 D3D12_DESCRIPTOR_HEAP_DESC got{};
149 D3D12_GPU_VIRTUAL_ADDRESS shader_va = 0;
150 EXPECT(rt::d3d12::descriptor_heap_info(heap.p, got, shader_va));
151 if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "first refresh")) return 1;
152
153 // The title rewrites slots after the heap is made (the write watch finds them): a slot of B now names A, new V#s
154 // past what it filled, and a page of A's slots zeroed (128 slots).
155 put(1500, a_va + 0x400, Want::a);
156 for (UINT s = 2048; s < 2112; ++s) put(s, b_va + (s % 256) * kViewBytes, Want::b);
157 std::memset(title + 128 * kDescriptor, 0, 4096);
158 for (UINT s = 128; s < 256; ++s) want[s] = Want::zero;
159 if (submit()) return 1;
160 if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "title writes")) return 1;
161
162 // A goes: the release sweep (filtered: only the V#s naming A) nulls the slots that name it, and only those. Its
163 // memory is given back once its GPU work retires, so a few submissions may pass first.
164 a.reset();
165 for (UINT s = 0; s < Heap::slots; ++s)
166 if (want[s] == Want::a) want[s] = Want::none;
167 bool nulled = false;
168 for (int pass = 0; pass < 32 && !nulled; ++pass) {
169 if (submit()) return 1;
170 std::uint32_t w[8];
171 EXPECT(rt::d3d12::read_arena(device, shader_va + 1500 * kDescriptor, w, sizeof(w)));
172 nulled = zero_size(w);
173 }
174 EXPECT(nulled);
175 if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "A released")) return 1;
176
177 heap.reset();
178 VirtualFree(title, 0, MEM_RELEASE);
179 return 0;
180}
181
182} // namespace
183
184int main() {
185 char value[4] = {};
186 const bool mirrored = !(GetEnvironmentVariableA("LEONIDA_HEAP_MIRROR", value, sizeof(value)) == 1 && value[0] == '0');
187 vktest::Device d;
188 const auto status = d.initialize();
189 if (status == vktest::DeviceStatus::unavailable) {
190 std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n");
191 return 77;
192 }
193 EXPECT(status == vktest::DeviceStatus::ready);
194 {
195 rt::d3d12::VulkanDeviceInfo info{};
196 info.get_instance_proc = d.instance_proc;
197 info.instance = d.instance;
198 info.physical = d.physical;
199 info.device = d.device;
200 info.queue = d.queue;
201 info.queue_family = d.family;
202 info.buffer_device_address = true;
203 info.subgroup = d.subgroup;
204 Ref<ID3D12Device> device;
205 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
206 EXPECT(rt::d3d12::device_arena_size(device.p) > 0);
207 if (run(device.p, mirrored)) return 1;
208 }
209 if (d.validation_errors()) {
210 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
211 return 1;
212 }
213 std::puts("ok");
214 return 0;
215}
diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp
index 25fa1f654..546c76055 100644
--- a/runtime/test/d3d12_existing_heap_test.cpp
+++ b/runtime/test/d3d12_existing_heap_test.cpp
@@ -1359,6 +1359,141 @@ int check_pending_stream_views(ID3D12Device* device) {
1359 return 0; 1359 return 0;
1360} 1360}
1361 1361
1362namespace {
1363std::atomic<DWORD> g_view_av_thread{0};
1364std::atomic<unsigned> g_view_avs{0};
1365
1366LONG CALLBACK count_view_av(PEXCEPTION_POINTERS info) {
1367 if (info && info->ExceptionRecord && info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION &&
1368 GetCurrentThreadId() == g_view_av_thread.load(std::memory_order_relaxed)) {
1369 g_view_avs.fetch_add(1, std::memory_order_relaxed);
1370 }
1371 return EXCEPTION_CONTINUE_SEARCH;
1372}
1373} // namespace
1374
1375// Map changes reported to title_memory_map between submissions must both retire a cached readable answer before a
1376// synchronous slot-70 view hashes decommitted pages, and wake a pending slot-70 view without waiting for a submission.
1377int check_placed_view_map_changes(ID3D12Device* device) {
1378 const char* who = "slot-70 view map changes";
1379 if (!rt::d3d12::bindless_set_layout(device)) return 0;
1380 GpuReader gpu;
1381 EXPECT(!gpu.init(device, 4096));
1382 auto env_is = [](const char* name, const char* want) {
1383 char buf[16]{};
1384 const DWORD n = GetEnvironmentVariableA(name, buf, sizeof(buf));
1385 return n > 0 && n < sizeof(buf) && std::strcmp(buf, want) == 0;
1386 };
1387 auto index = [&](const leonida::gfx10::ImageWords& descriptor) {
1388 std::uint32_t key[8];
1389 std::memcpy(key, descriptor.data(), sizeof(key));
1390 return rt::d3d12::bindless_hash_lookup(device, key);
1391 };
1392
1393 // 1. Committed >256 KiB texture -> decommit interior 64 KiB + map::changed -> synchronous view takes zero AVs.
1394 {
1395 constexpr SIZE_T bytes = 512 * 1024;
1396 auto* pages = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
1397 EXPECT(pages);
1398 std::memset(pages, 0x5a, bytes);
1399 D3D12_RESOURCE_DESC desc{};
1400 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
1401 desc.Width = 512;
1402 desc.Height = 1024;
1403 desc.DepthOrArraySize = desc.MipLevels = 1;
1404 desc.SampleDesc.Count = 1;
1405 desc.Format = DXGI_FORMAT_R8_UNORM;
1406 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
1407 D3D12_SHADER_RESOURCE_VIEW_DESC srv{};
1408 srv.Format = desc.Format;
1409 srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
1410 srv.Texture2D.MipLevels = 1;
1411 srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
1412 leonida::gfx10::ImageWords slot{};
1413 auto write_view = [&](UINT mapping) {
1414 srv.Shader4ComponentMapping = mapping;
1415 std::array<UINT, 14> resource{};
1416 std::array<UINT, 16> words{};
1417 std::memcpy(resource.data(), &desc, sizeof(desc));
1418 std::memcpy(words.data(), &srv, sizeof(srv));
1419 return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(),
1420 reinterpret_cast<UINT64>(pages),
1421 {reinterpret_cast<SIZE_T>(slot.data())});
1422 };
1423 EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING));
1424 EXPECT(index(slot) != 0);
1425
1426 EXPECT(VirtualFree(pages + 65536, 65536, MEM_DECOMMIT) != FALSE);
1427 leonida::title_memory_map::changed(pages + 65536, 65536);
1428
1429 g_view_avs.store(0, std::memory_order_relaxed);
1430 g_view_av_thread.store(GetCurrentThreadId(), std::memory_order_relaxed);
1431 PVOID veh = AddVectoredExceptionHandler(1, &count_view_av);
1432 EXPECT(veh != nullptr);
1433 const bool wrote_after_unmap = write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0));
1434 RemoveVectoredExceptionHandler(veh);
1435 g_view_av_thread.store(0, std::memory_order_relaxed);
1436 EXPECT(wrote_after_unmap);
1437 EXPECT(g_view_avs.load(std::memory_order_relaxed) == 0);
1438
1439 EXPECT(VirtualAlloc(pages + 65536, 65536, MEM_COMMIT, PAGE_READWRITE) == pages + 65536);
1440 leonida::title_memory_map::changed(pages + 65536, 65536);
1441 Ref<ID3D12Resource> placement;
1442 desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
1443 EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&placement.p)), S_OK);
1444 placement.p->Release();
1445 placement.p = nullptr;
1446 VirtualFree(pages, 0, MEM_RELEASE);
1447 }
1448
1449 // 2. Reserved texture -> commit + map::changed (no texel write note, no submission) -> synchronous view publishes.
1450 {
1451 constexpr SIZE_T bytes = 65536;
1452 void* pages = VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS);
1453 EXPECT(pages);
1454 D3D12_RESOURCE_DESC desc{};
1455 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
1456 desc.Width = 32;
1457 desc.Height = 8;
1458 desc.DepthOrArraySize = desc.MipLevels = 1;
1459 desc.SampleDesc.Count = 1;
1460 desc.Format = DXGI_FORMAT_R8_UNORM;
1461 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
1462 D3D12_SHADER_RESOURCE_VIEW_DESC srv{};
1463 srv.Format = desc.Format;
1464 srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
1465 srv.Texture2D.MipLevels = 1;
1466 leonida::gfx10::ImageWords first{}, second{};
1467 auto write_view = [&](UINT mapping, leonida::gfx10::ImageWords& out) {
1468 srv.Shader4ComponentMapping = mapping;
1469 std::array<UINT, 14> resource{};
1470 std::array<UINT, 16> words{};
1471 std::memcpy(resource.data(), &desc, sizeof(desc));
1472 std::memcpy(words.data(), &srv, sizeof(srv));
1473 return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(),
1474 reinterpret_cast<UINT64>(pages),
1475 {reinterpret_cast<SIZE_T>(out.data())});
1476 };
1477 EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, first));
1478 if (!env_is("LEONIDA_TITLE_IMAGE_DEFER", "0")) EXPECT(!index(first));
1479
1480 EXPECT(VirtualAlloc(pages, bytes, MEM_COMMIT, PAGE_READWRITE) == pages);
1481 std::memset(pages, 0x33, bytes);
1482 leonida::title_memory_map::changed(pages, bytes);
1483
1484 EXPECT(write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0), second));
1485 if (!env_is("LEONIDA_TITLE_FILL_ASYNC", "1")) EXPECT(index(first) && index(second));
1486
1487 Ref<ID3D12Resource> placement;
1488 desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
1489 EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&placement.p)), S_OK);
1490 placement.p->Release();
1491 placement.p = nullptr;
1492 VirtualFree(pages, 0, MEM_RELEASE);
1493 }
1494 return 0;
1495}
1496
1362// A persistent Map can become readable without notifying xmem or calling Map a second time. 1497// A persistent Map can become readable without notifying xmem or calling Map a second time.
1363int check_mapped_plane(ID3D12Device* device) { 1498int check_mapped_plane(ID3D12Device* device) {
1364 const char* who = "persistent slot-133 plane"; 1499 const char* who = "persistent slot-133 plane";
@@ -2089,6 +2224,7 @@ int main(int argc, char** argv) {
2089 if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p); 2224 if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p);
2090 if (vk.host_image_copy) { 2225 if (vk.host_image_copy) {
2091 failures += check_pending_stream_views(ours.p); 2226 failures += check_pending_stream_views(ours.p);
2227 failures += check_placed_view_map_changes(ours.p);
2092 failures += check_shared_bc_placements(ours.p); 2228 failures += check_shared_bc_placements(ours.p);
2093 failures += check_mapped_plane(ours.p); 2229 failures += check_mapped_plane(ours.p);
2094 failures += check_mapped_bc_array(ours.p); 2230 failures += check_mapped_bc_array(ours.p);
@@ -2099,6 +2235,7 @@ int main(int argc, char** argv) {
2099 no_host_copy.host_image_copy = false; 2235 no_host_copy.host_image_copy = false;
2100 Ref<ID3D12Device> staged; 2236 Ref<ID3D12Device> staged;
2101 if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; 2237 if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1;
2238 failures += check_placed_view_map_changes(staged.p);
2102 failures += check_mapped_plane(staged.p); 2239 failures += check_mapped_plane(staged.p);
2103 failures += check_mapped_bc_array(staged.p); 2240 failures += check_mapped_bc_array(staged.p);
2104 } 2241 }
diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp
index 775cfeb58..7b529546b 100644
--- a/runtime/test/d3d12_mesh_test.cpp
+++ b/runtime/test/d3d12_mesh_test.cpp
@@ -150,6 +150,7 @@ int main(int argc, char** argv) {
150 rt::d3d12::VulkanDeviceInfo info{}; 150 rt::d3d12::VulkanDeviceInfo info{};
151 info.prepare_on_bind=d.prepare_on_bind; 151 info.prepare_on_bind=d.prepare_on_bind;
152 info.cold_graphics_compile=d.cold_graphics_compile; 152 info.cold_graphics_compile=d.cold_graphics_compile;
153 info.heavy_pipeline_cache=d.heavy_pipeline_cache;
153 info.get_instance_proc = d.instance_proc; 154 info.get_instance_proc = d.instance_proc;
154 info.instance = d.instance; 155 info.instance = d.instance;
155 info.physical = d.physical; 156 info.physical = d.physical;
@@ -161,6 +162,7 @@ int main(int argc, char** argv) {
161 info.mesh_shader = mesh; 162 info.mesh_shader = mesh;
162 info.mesh_shader_queries = mesh && d.mesh_shader_queries; 163 info.mesh_shader_queries = mesh && d.mesh_shader_queries;
163 info.pipeline_statistics_query = d.pipeline_statistics_query; 164 info.pipeline_statistics_query = d.pipeline_statistics_query;
165 info.conservative_rasterization = d.conservative_rasterization;
164 return info; 166 return info;
165 }; 167 };
166 const auto make_device = [&](bool mesh, Ref<ID3D12Device>& device) { 168 const auto make_device = [&](bool mesh, Ref<ID3D12Device>& device) {
@@ -253,6 +255,34 @@ int main(int argc, char** argv) {
253 vs_stream.add(TopologySubobject{.inner = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE}); 255 vs_stream.add(TopologySubobject{.inner = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE});
254 vs_stream.add(TargetsSubobject{.inner = one_target()}); 256 vs_stream.add(TargetsSubobject{.inner = one_target()});
255 EXPECT(SUCCEEDED(create(device.p, vs_stream, vs_pso))); 257 EXPECT(SUCCEEDED(create(device.p, vs_stream, vs_pso)));
258 // Conservative rasterization in a mesh pipeline: its stream has no input assembler, so it need not name a topology
259 // type. A vertex pipeline without TRIANGLE is still refused, as is a wireframe mesh one.
260 {
261 D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
262 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options)));
263 if (options.ConservativeRasterizationTier != D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) {
264 std::printf("conservative rasterization tier %d: mesh pipelines checked\n", int(options.ConservativeRasterizationTier));
265 D3D12_RASTERIZER_DESC conservative{};
266 conservative.FillMode = D3D12_FILL_MODE_SOLID;
267 conservative.CullMode = D3D12_CULL_MODE_NONE;
268 conservative.DepthClipEnable = TRUE;
269 conservative.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON;
270 Ref<ID3D12PipelineState> made;
271 Stream conservative_mesh = mesh_stream;
272 conservative_mesh.add(RasterizerSubobject{.inner = conservative});
273 EXPECT(SUCCEEDED(create(device.p, conservative_mesh, made)) && made.p);
274 conservative.FillMode = D3D12_FILL_MODE_WIREFRAME;
275 Stream wireframe_mesh = mesh_stream;
276 wireframe_mesh.add(RasterizerSubobject{.inner = conservative});
277 EXPECT(create(device.p, wireframe_mesh, refused) == E_INVALIDARG && !refused.p);
278 conservative.FillMode = D3D12_FILL_MODE_SOLID;
279 Stream no_topology_vs;
280 no_topology_vs.add(RootSubobject{.inner = root.p}).add(VsSubobject{.inner = vs}).add(PsSubobject{.inner = ps});
281 no_topology_vs.add(TargetsSubobject{.inner = one_target()});
282 no_topology_vs.add(RasterizerSubobject{.inner = conservative});
283 EXPECT(create(device.p, no_topology_vs, refused) == E_INVALIDARG && !refused.p);
284 }
285 }
256 // A mesh shader translated before the graphics root window would read its root arguments from the wrong 286 // A mesh shader translated before the graphics root window would read its root arguments from the wrong
257 // dwords: refused, with a log line that asks for the shaders stage again. 287 // dwords: refused, with a log line that asks for the shaders stage again.
258 { 288 {
diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp
index e5ef14304..bf0f14f1e 100644
--- a/runtime/test/d3d12_title_va_test.cpp
+++ b/runtime/test/d3d12_title_va_test.cpp
@@ -512,7 +512,194 @@ int check_window_overflow(Context& c) {
512 VirtualFree(ring, 0, MEM_RELEASE); 512 VirtualFree(ring, 0, MEM_RELEASE);
513 return 0; 513 return 0;
514} 514}
515// These fixtures register their own pairs without XMem. Retire each before Wine can reuse either VA. 515// What the GPU writes into a title window goes back to the title's pages (#1537, the WRITE_INVALID stop: a window is
516// a read-side mirror, so a UAV write used to land in the copy and the title never saw it). The shader's write is read
517// back through the pages themselves; then a write by the title must survive the next submission's forward copy.
518struct WriteBack {
519 Context* c;
520 ID3D12CommandAllocator* allocator;
521 ID3D12GraphicsCommandList* list;
522 ID3D12Resource* out;
523 ID3D12DescriptorHeap* heap;
524 UINT64 gpu;
525};
526
527// One submission that dispatches through a root UAV at `va` and waits for it. False on a failed call.
528int submit_write(WriteBack& s, std::uint64_t va) {
529 EXPECT(s.allocator->Reset() == S_OK);
530 EXPECT(s.list->Reset(s.allocator, s.c->pso) == S_OK);
531 ID3D12DescriptorHeap* heaps[] = {s.heap};
532 s.list->SetDescriptorHeaps(1, heaps);
533 s.list->SetComputeRootSignature(s.c->root);
534 s.list->SetComputeRoot32BitConstant(0, 0, 0);
535 s.list->SetComputeRoot32BitConstant(0, 1, 1); // the step: a word the shader writes
536 s.list->SetComputeRootUnorderedAccessView(1, va);
537 s.list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{s.gpu});
538 s.list->Dispatch(1, 1, 1);
539 D3D12_RESOURCE_BARRIER to_copy{};
540 to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
541 to_copy.Transition.pResource = s.out;
542 to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
543 to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
544 to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
545 s.list->ResourceBarrier(1, &to_copy);
546 EXPECT(s.list->Close() == S_OK);
547 ID3D12CommandList* lists[] = {s.list};
548 s.c->queue->ExecuteCommandLists(1, lists);
549 EXPECT(rt::d3d12::last_execute_result(s.c->queue) == leonida::ReplayResult::success);
550 EXPECT(SUCCEEDED(s.c->queue->Signal(s.c->fence, ++s.c->fence_value)));
551 s.c->fence->SetEventOnCompletion(s.c->fence_value, nullptr); // a null event waits, as D3D12 does
552 return 0;
553}
554
555// The same gap on a buffer the title places at its own address (slot 133, the retail case for a compute result it
556// reads back): the pages are not imported here, so the buffer is a shadow, and the write of a root UAV over the
557// title's VA must reach the pages at the next submission - and the title's own newer words must still win.
558int check_placed_write_back(Context& c, bool geometry) {
559 void* pages = VirtualAlloc(nullptr, kPages, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
560 EXPECT(pages);
561 const auto title_va = reinterpret_cast<std::uint64_t>(pages);
562 auto* words = static_cast<std::uint32_t*>(pages);
563 for (UINT i = 0; i < kPages / 4; ++i) words[i] = 0xA0000000u + i * 3u; // never zero, unlike the shader's rows
564 auto& aliases = leonida::title_va_aliases();
565 aliases.add_title_memory(title_va, kPages); // what the xmem shims do for the title's allocations
566 const D3D12_RESOURCE_DESC desc = buffer_desc(kPages);
567 Ref<ID3D12Resource> placed;
568 EXPECT(SUCCEEDED(
569 rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&placed.p))));
570 EXPECT(placed->GetGPUVirtualAddress() == title_va);
571 EXPECT(aliases.shader_va(title_va) != title_va); // there is a copy to be reached through
572
573 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK};
574 const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
575 const auto readback_desc = buffer_desc(kBytes);
576 Ref<ID3D12Resource> out, readback;
577 EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav,
578 D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
579 IID_PPV_ARGS(&out.p))));
580 EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
581 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
582 IID_PPV_ARGS(&readback.p))));
583 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8,
584 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
585 Ref<ID3D12DescriptorHeap> heap;
586 EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p))));
587 Ref<ID3D12CommandAllocator> allocator;
588 Ref<ID3D12GraphicsCommandList> list;
589 EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
590 EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso,
591 IID_PPV_ARGS(&list.p))));
592 EXPECT(list->Close() == S_OK);
593 WriteBack s{&c, allocator.p, list.p, out.p, heap.p,
594 reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 10))(heap.p)};
595
596 const std::vector<std::uint32_t> before(words, words + kElements);
597 EXPECT(submit_write(s, title_va) == 0);
598 UINT untouched = 0;
599 for (UINT i = 0; i < kElements; ++i) untouched += words[i] == before[i];
600 // An imported buffer is the same memory and needs no copy; only a shadow owes the pages the GPU's words.
601 const bool shadow = !geometry && aliases.shader_va(title_va) >= c.arena;
602 if (shadow) {
603 std::printf("placed buffer write back: %u/%u words still held the title's before the next submission\n",
604 untouched, kElements);
605 EXPECT(untouched == kElements);
606 }
607
608 EXPECT(submit_write(s, title_va) == 0);
609 std::vector<std::uint32_t> written(words, words + kElements);
610 UINT reached = 0, changed = 0, nonzero = 0;
611 for (UINT i = 0; i < kElements; ++i) {
612 reached += written[i] == (0xA0000000u + i * 3u);
613 changed += written[i] != before[i];
614 nonzero += written[i] != 0;
615 }
616 std::printf("placed buffer write back: %u/%u words reached the pages (%u changed, %u nonzero)\n", kElements - reached,
617 kElements, changed, nonzero);
618 EXPECT(changed == kElements && nonzero > 0);
619 (void)reached;
620
621 // The title writes its own words over the result: the next submission copies them forward and they stay.
622 for (UINT i = 0; i < kElements; ++i) words[i] = 0xB16B00B5u;
623 EXPECT(submit_write(s, title_va) == 0);
624 UINT kept = 0;
625 for (UINT i = 0; i < kElements; ++i) kept += words[i] == 0xB16B00B5u;
626 std::printf("placed buffer write back: the title's own words survived %u/%u\n", kept, kElements);
627 EXPECT(kept == kElements);
628
629 placed.reset(); // the shadow goes, the pages stay writable
630 aliases.remove_title_memory(title_va);
631 VirtualFree(pages, 0, MEM_RELEASE);
632 return 0;
633}
634
635int check_window_write_back(Context& c, bool geometry) {
636 constexpr UINT64 ring_bytes = 256 * 1024;
637 auto* ring = static_cast<std::uint32_t*>(
638 VirtualAlloc(nullptr, ring_bytes, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
639 EXPECT(ring);
640 const auto ring_va = reinterpret_cast<std::uint64_t>(ring);
641 for (UINT i = 0; i < ring_bytes / 4; ++i) ring[i] = 0;
642 auto& aliases = leonida::title_va_aliases();
643 aliases.add_title_memory(ring_va, ring_bytes);
644
645 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK};
646 const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
647 const auto readback_desc = buffer_desc(kBytes);
648 Ref<ID3D12Resource> out, readback;
649 EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav,
650 D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
651 IID_PPV_ARGS(&out.p))));
652 EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
653 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
654 IID_PPV_ARGS(&readback.p))));
655 D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8,
656 D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0};
657 Ref<ID3D12DescriptorHeap> heap;
658 EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p))));
659 Ref<ID3D12CommandAllocator> allocator;
660 Ref<ID3D12GraphicsCommandList> list;
661 EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
662 EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso,
663 IID_PPV_ARGS(&list.p))));
664 EXPECT(list->Close() == S_OK); // Reset needs it closed, as the title leaves it
665 WriteBack s{&c, allocator.p, list.p, out.p, heap.p,
666 reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 10))(heap.p)};
667
668 // The shader writes the range the root UAV names, which is the title's own pages here, far past the arena: the
669 // resolve already has to make a window for them before the submission.
670 EXPECT(aliases.shader_va(ring_va) == ring_va);
671 EXPECT(submit_write(s, ring_va) == 0);
672 EXPECT(aliases.shader_va(ring_va) != ring_va); // a window was made for the title's pages
673 if (!geometry) EXPECT(ring[0] == 0); // the copy took the write: the pages get it only after the next submission
674
675 // The next submission's refresh copies the GPU's writes back, before it copies the pages forward.
676 EXPECT(submit_write(s, ring_va) == 0);
677 const std::vector<std::uint32_t> written(ring, ring + kElements);
678 UINT nonzero = 0;
679 for (std::uint32_t w : written) nonzero += w != 0;
680 std::printf("write back: %u of %u words the shader wrote are in the title's pages\n", nonzero, kElements);
681 EXPECT(nonzero > 0);
682
683 // The same submission again: the pages keep what they hold, the values do not drift.
684 EXPECT(submit_write(s, ring_va) == 0);
685 UINT stable = 0;
686 for (UINT i = 0; i < kElements; ++i) stable += ring[i] == written[i];
687 std::printf("write back: the pages kept those words across two submissions %u/%u\n", stable, kElements);
688 EXPECT(stable == kElements);
689
690 // A write by the title after a submission is copied forward over the result again, not overwritten by it.
691 for (UINT i = 0; i < kElements; ++i) ring[i] = 0xB16B00B5u;
692 EXPECT(submit_write(s, ring_va) == 0);
693 UINT kept = 0;
694 for (UINT i = 0; i < kElements; ++i) kept += ring[i] == 0xB16B00B5u;
695 std::printf("write back: the title's own words survived the next submission %u/%u\n", kept, kElements);
696 EXPECT(kept == kElements);
697
698 aliases.remove_title_memory(ring_va);
699 VirtualFree(ring, 0, MEM_RELEASE);
700 return 0;
701}
702
516void remove_test_pair(std::uintptr_t gpu, std::uintptr_t cpu) { 703void remove_test_pair(std::uintptr_t gpu, std::uintptr_t cpu) {
517 auto& state = leonida::title_gpu_views::state(); 704 auto& state = leonida::title_gpu_views::state();
518 std::unique_lock lock(state.mutex); 705 std::unique_lock lock(state.mutex);
@@ -987,6 +1174,8 @@ int main(int argc, char** argv) {
987 const bool api_copy = api_copy_off || (argc == 2 && std::strcmp(argv[1], "--api-descriptor-copy") == 0); 1174 const bool api_copy = api_copy_off || (argc == 2 && std::strcmp(argv[1], "--api-descriptor-copy") == 0);
988 const bool rebind = api_copy || mirror_off || second_device || (argc == 2 && std::strcmp(argv[1], "--rebound-tables") == 0); 1175 const bool rebind = api_copy || mirror_off || second_device || (argc == 2 && std::strcmp(argv[1], "--rebound-tables") == 0);
989 const bool window_cap = argc == 2 && std::strcmp(argv[1], "--window-cap") == 0; 1176 const bool window_cap = argc == 2 && std::strcmp(argv[1], "--window-cap") == 0;
1177 const bool window_write_back = argc == 2 && std::strcmp(argv[1], "--window-writeback") == 0;
1178 const bool placed_write_back = argc == 2 && std::strcmp(argv[1], "--placed-writeback") == 0;
990 if (window_cap) { 1179 if (window_cap) {
991 const char* cap = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); 1180 const char* cap = std::getenv("LEONIDA_TITLE_WINDOWS_MB");
992 if (!cap || std::strcmp(cap, "0")) { 1181 if (!cap || std::strcmp(cap, "0")) {
@@ -1101,6 +1290,25 @@ int main(int argc, char** argv) {
1101 std::printf("title memory past the window cap: the views were zero-size and the shader read zeros\n"); 1290 std::printf("title memory past the window cap: the views were zero-size and the shader read zeros\n");
1102 return 0; 1291 return 0;
1103 } 1292 }
1293 if (placed_write_back) {
1294 if (check_placed_write_back(c, geometry)) return 1;
1295 if (d.validation_errors()) {
1296 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
1297 return 1;
1298 }
1299 std::printf("title-placed buffer write back: the GPU's writes reached the title's pages\n");
1300 return 0;
1301 }
1302 if (window_write_back) {
1303 if (check_window_write_back(c, geometry)) return 1;
1304 if (d.validation_errors()) {
1305 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
1306 return 1;
1307 }
1308 std::printf("title window write back: the GPU's writes reached the title's pages and the title's own "
1309 "words won\n");
1310 return 0;
1311 }
1104 if (geometry && check_declined_imports(c)) return 1; 1312 if (geometry && check_declined_imports(c)) return 1;
1105 if (geometry && check_import_over_shadow(c)) return 1; 1313 if (geometry && check_import_over_shadow(c)) return 1;
1106 if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; 1314 if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1;
diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp
index 560110240..b45cc2c84 100644
--- a/runtime/test/d3d12_translated_draw_test.cpp
+++ b/runtime/test/d3d12_translated_draw_test.cpp
@@ -193,6 +193,7 @@ int main(int argc, char** argv) {
193 rt::d3d12::VulkanDeviceInfo info{}; 193 rt::d3d12::VulkanDeviceInfo info{};
194 info.prepare_on_bind=d.prepare_on_bind; 194 info.prepare_on_bind=d.prepare_on_bind;
195 info.cold_graphics_compile=d.cold_graphics_compile; 195 info.cold_graphics_compile=d.cold_graphics_compile;
196 info.heavy_pipeline_cache=d.heavy_pipeline_cache;
196 info.get_instance_proc = d.instance_proc; 197 info.get_instance_proc = d.instance_proc;
197 info.instance = d.instance; 198 info.instance = d.instance;
198 info.physical = d.physical; 199 info.physical = d.physical;
diff --git a/runtime/test/d3d12_xmem_placed_test.cpp b/runtime/test/d3d12_xmem_placed_test.cpp
index 7c64a23cf..33b5d462a 100644
--- a/runtime/test/d3d12_xmem_placed_test.cpp
+++ b/runtime/test/d3d12_xmem_placed_test.cpp
@@ -174,6 +174,82 @@ int queue_remap(ID3D12Device* real, ID3D12Device* proxy) {
174 return 0; 174 return 0;
175} 175}
176 176
177// Queue slot 31 as a retail run takes it: no batch hook, so the queue's default adapter sends each range to xmem's
178// range callback (copy_page_mappings_fn), which mirrors a legacy-paired GPU-only destination at its CPU view. The
179// source is a GPU-only pool backed only through its CPU alias, and the title maps a page of its own at one CPU twin
180// while the remap waits behind queue work (deferred with list values, waited for without them). When the remap is
181// applied, the GPU-only pages change and the title's CPU page keeps its bytes, through the copy and the unmap after it.
182int queue_remap_default_route(ID3D12Device* real, ID3D12Device* proxy) {
183 using rt::xmem::PageBatch;
184 using rt::xmem::PageRange;
185 auto reserve = reinterpret_cast<XMemVirtualAllocFn>(rt::shims::find("xmem.dll", "XMemVirtualAlloc"));
186 auto allocate = reinterpret_cast<XMemAllocatePhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages"));
187 auto map = reinterpret_cast<XMemMapPhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemMapPhysicalPages"));
188 auto free_pages = reinterpret_cast<XMemFreePhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemFreePhysicalPages"));
189 constexpr unsigned n = 2;
190 auto window = [&](DWORD protect) {
191 return static_cast<std::uint8_t*>(reserve(nullptr, n * kPage64k, MEM_RESERVE | kXmem64kPages, 0, protect));
192 };
193 // Two pairs, each a CPU range and then the GPU-only range of its size: the pool's and the destination's.
194 auto* pool_cpu = window(PAGE_READWRITE);
195 auto* pool = window(0x801);
196 auto* cpu = window(PAGE_READWRITE);
197 auto* dst = window(0x801);
198 EXPECT(pool_cpu && pool && cpu && dst);
199 EXPECT(leonida::title_gpu_views::to_cpu(uintptr_t(pool)) == uintptr_t(pool_cpu));
200 EXPECT(leonida::title_gpu_views::to_cpu(uintptr_t(dst)) == uintptr_t(cpu));
201 std::uint64_t pages[n + 1]{}, count = n + 1;
202 EXPECT(allocate(0x280, &count, pages) && count == n + 1);
203 EXPECT(map(pool_cpu, n, pages)); // the pool's pages are mapped at its CPU alias only
204 for (unsigned i = 0; i < n; ++i) pool_cpu[i * kPage64k] = static_cast<std::uint8_t>(40 + i);
205
206 D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_COPY};
207 Ref<ID3D12CommandQueue> queue;
208 Ref<ID3D12Fence> gate;
209 EXPECT(SUCCEEDED(proxy->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue.p))));
210 EXPECT(SUCCEEDED(real->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate.p))));
211 auto* real_queue = rt::d3d12_xs::queue_proxy_real_queue(queue.p);
212 EXPECT(real_queue && SUCCEEDED(real_queue->Wait(gate.p, 1)));
213 rt::d3d12_xs::set_copy_page_mappings_hook(nullptr); // the retail route: the default adapter
214 using Copy = HRESULT(WINAPI*)(void*, UINT, const PageBatch*, std::uintptr_t, UINT, UINT);
215 auto call = reinterpret_cast<Copy>((*reinterpret_cast<void***>(queue.p))[31]);
216 const PageRange copy_run[] = {{0, 0, n}};
217 const PageBatch copy_batch{uintptr_t(dst), 1, copy_run};
218 auto done = std::async(std::launch::async, [&] { return call(queue.p, 1, &copy_batch, uintptr_t(pool), n, 0); });
219 // While the remap waits behind the held work, the title maps a page of its own at the second CPU twin.
220 EXPECT(map(cpu + kPage64k, 1, &pages[n]));
221 cpu[kPage64k] = 77;
222 EXPECT(SUCCEEDED(gate->Signal(1)));
223 EXPECT(SUCCEEDED(done.get()));
224 EXPECT(SUCCEEDED(real_queue->Signal(gate.p, 2)));
225 HANDLE remapped = CreateEventW(nullptr, FALSE, FALSE, nullptr);
226 EXPECT(remapped && SUCCEEDED(gate->SetEventOnCompletion(2, remapped)));
227 const auto completion = WaitForSingleObject(remapped, 10000);
228 CloseHandle(remapped);
229 EXPECT(completion == WAIT_OBJECT_0);
230 EXPECT(dst[0] == 40 && dst[kPage64k] == 41); // the GPU-only pages, found through the pool's CPU alias
231 EXPECT(cpu[0] == 40); // a CPU twin with no mapping of the title's follows the copy
232 EXPECT(cpu[kPage64k] == 77); // the title's own page is kept
233
234 // The unmap: the GPU-only pages and the mirrored twin are unmapped, the title's page stays.
235 const PageRange hole[] = {{2, 0, n}};
236 const PageBatch unmap_batch{uintptr_t(dst), 1, hole};
237 EXPECT(SUCCEEDED(call(queue.p, 1, &unmap_batch, uintptr_t(pool), n, 0)));
238 EXPECT(SUCCEEDED(real_queue->Signal(gate.p, 3)));
239 remapped = CreateEventW(nullptr, FALSE, FALSE, nullptr);
240 EXPECT(remapped && SUCCEEDED(gate->SetEventOnCompletion(3, remapped)));
241 EXPECT(WaitForSingleObject(remapped, 10000) == WAIT_OBJECT_0);
242 CloseHandle(remapped);
243 EXPECT(state_is(dst, MEM_RESERVE) && state_is(dst + kPage64k, MEM_RESERVE) && state_is(cpu, MEM_RESERVE));
244 EXPECT(cpu[kPage64k] == 77);
245
246 EXPECT(map(cpu + kPage64k, 1, nullptr) && map(pool_cpu, n, nullptr));
247 EXPECT(free_pages(n + 1, pages));
248 std::puts("queue slot 31 default route: a source through its CPU alias, a deferred copy and an unmap keep the "
249 "title's own CPU twin page");
250 return 0;
251}
252
177// What a GPU copy of `buffer` reads now (a submission: the shadows are refreshed first). 253// What a GPU copy of `buffer` reads now (a submission: the shadows are refreshed first).
178int read_back(ID3D12Device* real, ID3D12Resource* buffer, UINT64 size, std::vector<std::uint8_t>& out) { 254int read_back(ID3D12Device* real, ID3D12Resource* buffer, UINT64 size, std::vector<std::uint8_t>& out) {
179 D3D12_RESOURCE_DESC desc = buffer->GetDesc(); 255 D3D12_RESOURCE_DESC desc = buffer->GetDesc();
@@ -547,6 +623,7 @@ int main(int argc, char** argv) {
547 failures += run(real.p, device.p, eager); 623 failures += run(real.p, device.p, eager);
548 failures += exposure_map_ranges(device.p); 624 failures += exposure_map_ranges(device.p);
549 failures += queue_remap(real.p, device.p); 625 failures += queue_remap(real.p, device.p);
626 failures += queue_remap_default_route(real.p, device.p);
550 failures += paired_views(real.p); 627 failures += paired_views(real.p);
551 } 628 }
552 } 629 }
diff --git a/runtime/test/dstorage_test.cpp b/runtime/test/dstorage_test.cpp
index c24bcdb65..fa1b529d0 100644
--- a/runtime/test/dstorage_test.cpp
+++ b/runtime/test/dstorage_test.cpp
@@ -18,6 +18,7 @@
18#include <span> 18#include <span>
19#include "../src/bcpack.h" 19#include "../src/bcpack.h"
20#include "../src/bcpack_stream.h" 20#include "../src/bcpack_stream.h"
21#include "../src/dstorage_hold.h"
21#include "../src/title_geometry_watch.h" 22#include "../src/title_geometry_watch.h"
22#include "../src/title_page_watch.h" 23#include "../src/title_page_watch.h"
23#include "xmem.h" 24#include "xmem.h"
@@ -1613,6 +1614,259 @@ void test_extended(Env& env) {
1613 q->Release(); 1614 q->Release();
1614} 1615}
1615 1616
1617// A queue half full submits itself, but a read into physical pages and everything behind it wait for Submit: the
1618// title may fill the page list right before its own Submit. Until then the list names no page (the read would
1619// fail) or the page its slot named before (the data would land in a page that belongs to something else). The two
1620// cases of Marvisak/VIctory eddde73, then the ways a hold ends without Submit.
1621void test_page_reads_wait_for_submit(Env& env) {
1622 const auto alloc = reinterpret_cast<BOOL(WINAPI*)(uint64_t,uint64_t*,uint64_t*)>(
1623 rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages"));
1624 const auto reserve = reinterpret_cast<void*(WINAPI*)(void*,SIZE_T,DWORD,uint64_t,DWORD)>(
1625 rt::shims::find("xmem.dll", "XMemVirtualAlloc"));
1626 const auto map = reinterpret_cast<void*(WINAPI*)(void*,uint64_t,const uint64_t*)>(
1627 rt::shims::find("xmem.dll", "XMemMapPhysicalPages"));
1628 const auto free_pages = reinterpret_cast<BOOL(WINAPI*)(uint64_t,const uint64_t*)>(
1629 rt::shims::find("xmem.dll", "XMemFreePhysicalPages"));
1630 uint64_t pages[2]{}, count = 2;
1631 constexpr size_t page = 65536, bytes = 4096;
1632 auto* window = static_cast<uint8_t*>(reserve(nullptr, 2*page, MEM_RESERVE | 0x20400000, 0x21, PAGE_READWRITE));
1633 const bool allocated = window && alloc(0x280, &count, pages);
1634 const bool mapped = allocated && map(window, 2, pages) == window;
1635 check(mapped, "two physical pages mapped for the held reads");
1636 if (!mapped) {
1637 if (allocated) free_pages(count, pages);
1638 if (window) VirtualFree(window, 0, MEM_RELEASE);
1639 return;
1640 }
1641 auto& h = leonida::dstorage::hold_stats();
1642 const auto plain = pattern(bytes, 9);
1643 const auto into_pages = [&](ULONG_PTR* list) {
1644 DSTORAGE_REQUEST r{};
1645 r.Options.AsUINT64 = options::kSourceMemory | options::kDestinationPages;
1646 r.DestinationPageArray = list;
1647 r.DestinationPageOffset = 0;
1648 r.Source = plain.data();
1649 r.SourceSize = r.DestinationSize = static_cast<uint32_t>(bytes);
1650 return r;
1651 };
1652 const auto into_buffer = [&](uint8_t* out) {
1653 DSTORAGE_REQUEST r{};
1654 r.Options.AsUINT64 = options::kSourceMemory;
1655 r.Destination = out;
1656 r.Source = plain.data();
1657 r.SourceSize = r.DestinationSize = 16;
1658 return r;
1659 };
1660 const auto zero = [&](const uint8_t* at, size_t n) { return std::all_of(at, at + n, [](uint8_t b) { return b == 0; }); };
1661 const auto holds_plain = [&](const uint8_t* at, size_t n) { return std::memcmp(at, plain.data(), n) == 0; };
1662 const auto errors = [&] {
1663 DSTORAGE_STATS stats{};
1664 env.factory->GetStats(&stats);
1665 return stats.ErrorCount;
1666 };
1667 constexpr int kHalf = 0x40; // of a capacity of 0x80
1668 std::vector<uint8_t> outs(kHalf * 16);
1669 const auto reset = [&] {
1670 std::memset(window, 0, 2*page);
1671 std::fill(outs.begin(), outs.end(), uint8_t{0});
1672 };
1673
1674 // The list still names the slot's previous page when the queue submits itself, the right one by Submit.
1675 {
1676 reset();
1677 auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME);
1678 auto* status = make_status(env, 1);
1679 const uint64_t self = h.self_submits.load(), held = h.held_reads.load(), failed = errors();
1680 ULONG_PTR list[] = {static_cast<ULONG_PTR>(pages[0])};
1681 DSTORAGE_REQUEST r = into_buffer(outs.data());
1682 q->EnqueueRequest(&r);
1683 r = into_pages(list);
1684 q->EnqueueRequest(&r);
1685 for (int i = 2; i < kHalf; ++i) {
1686 r = into_buffer(outs.data() + i * 16);
1687 q->EnqueueRequest(&r); // the last one makes half the capacity
1688 }
1689 check(wait_until([&] { return holds_plain(outs.data(), 16); }),
1690 "the entry ahead of a read into pages starts when the queue submits itself");
1691 Sleep(50); // time for an early read to land in the old page
1692 check(zero(window, bytes), "a self-submit does not write the page the list named before the title's Submit");
1693 check(zero(outs.data() + 2 * 16, 16), "entries behind a held read keep their place");
1694 check(h.self_submits.load() == self + 1 && h.held_reads.load() == held + 1,
1695 "one self-submit and one held read are counted");
1696 DSTORAGE_QUEUE_INFO info{};
1697 q->Query(&info);
1698 check(info.EmptySlotCount == 0x7f - (kHalf - 1),
1699 "held entries still take their slots");
1700 list[0] = static_cast<ULONG_PTR>(pages[1]); // the title fills its page table, then submits
1701 q->EnqueueStatus(status, 0);
1702 check_hr(status->GetHResult(0), E_PENDING, "a status behind a held read is pending");
1703 q->Submit();
1704 check(wait_complete(status, 0), "the held entries run at Submit");
1705 check_hr(status->GetHResult(0), S_OK, "a read held for Submit succeeds");
1706 check(holds_plain(window + page, bytes), "the read lands in the page its list names at Submit");
1707 check(zero(window, bytes), "the page the list named before stays untouched");
1708 bool all = true;
1709 for (int i = 2; i < kHalf; ++i) all = all && holds_plain(outs.data() + i * 16, 16);
1710 check(all, "every entry behind the held read ran");
1711 check(errors() == failed, "no entry failed");
1712 status->Release();
1713 q->Release();
1714 }
1715
1716 // The list is still empty when the queue submits itself: no failure, the read waits.
1717 {
1718 reset();
1719 auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME);
1720 auto* status = make_status(env, 1);
1721 const uint64_t page0 = h.page0_entries.load(), failed = errors();
1722 ULONG_PTR list[] = {0};
1723 DSTORAGE_REQUEST r = into_pages(list);
1724 q->EnqueueRequest(&r);
1725 for (int i = 1; i < kHalf; ++i) {
1726 r = into_buffer(outs.data() + i * 16);
1727 q->EnqueueRequest(&r);
1728 }
1729 Sleep(50);
1730 check(h.page0_entries.load() == page0 && errors() == failed, "an empty page list is not read before Submit");
1731 list[0] = static_cast<ULONG_PTR>(pages[0]);
1732 q->EnqueueStatus(status, 0);
1733 q->Submit();
1734 check(wait_complete(status, 0), "the read with a late page list completes");
1735 check_hr(status->GetHResult(0), S_OK, "a page list filled before Submit is written");
1736 check(holds_plain(window, bytes) && errors() == failed, "its bytes are in the page");
1737 status->Release();
1738 q->Release();
1739 }
1740
1741 // A full queue: the title waits in an enqueue and cannot call Submit, so the held entries go.
1742 {
1743 reset();
1744 auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME);
1745 auto* status = make_status(env, 1);
1746 const uint64_t full = h.full_releases.load();
1747 ULONG_PTR list[] = {static_cast<ULONG_PTR>(pages[1])};
1748 constexpr int kMany = 200;
1749 std::vector<uint8_t> sink(kMany * 16);
1750 std::atomic<bool> done{false};
1751 std::thread producer([&] {
1752 DSTORAGE_REQUEST r = into_pages(list);
1753 q->EnqueueRequest(&r);
1754 for (int i = 0; i < kMany; ++i) {
1755 r = into_buffer(sink.data() + i * 16);
1756 q->EnqueueRequest(&r);
1757 }
1758 q->EnqueueStatus(status, 0);
1759 done.store(true);
1760 });
1761 check(wait_until([&] { return done.load(); }), "a full queue with held entries does not wait for Submit");
1762 producer.join();
1763 check(h.full_releases.load() == full + 1, "the full queue's release is counted");
1764 q->Submit();
1765 check(wait_complete(status, 0), "the full queue's entries complete");
1766 check_hr(status->GetHResult(0), S_OK, "they succeed");
1767 bool all = holds_plain(window + page, bytes);
1768 for (int i = 0; i < kMany; ++i) all = all && holds_plain(sink.data() + i * 16, 16);
1769 check(all, "every entry of the full queue has its bytes");
1770 status->Release();
1771 q->Release();
1772 }
1773
1774 // A hold has a time limit: held entries go after LEONIDA_DSTORAGE_HOLD_MS without Submit, 2000 ms unless set.
1775 for (const wchar_t* limit : {static_cast<const wchar_t*>(nullptr), L"200"}) {
1776 reset();
1777 SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", limit);
1778 auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME);
1779 SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", nullptr);
1780 const uint64_t timed = h.timed_releases.load();
1781 ULONG_PTR list[] = {static_cast<ULONG_PTR>(pages[0])};
1782 const auto begin = std::chrono::steady_clock::now();
1783 DSTORAGE_REQUEST r = into_pages(list);
1784 q->EnqueueRequest(&r);
1785 for (int i = 1; i < kHalf; ++i) {
1786 r = into_buffer(outs.data() + i * 16);
1787 q->EnqueueRequest(&r);
1788 }
1789 check(zero(window, bytes), "a hold with a time limit starts as a hold");
1790 if (!limit) {
1791 Sleep(1000);
1792 check(zero(window, bytes), "the default limit is not over after a second");
1793 }
1794 check(wait_until([&] { return holds_plain(window, bytes); }),
1795 limit ? "LEONIDA_DSTORAGE_HOLD_MS ends a hold" : "a hold ends by itself without the variable");
1796 const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>(
1797 std::chrono::steady_clock::now() - begin).count();
1798 check(waited >= (limit ? 150 : 1900) && waited < (limit ? 2000 : 6000),
1799 limit ? "after about the 200 ms asked for" : "after about the default 2000 ms");
1800 check(h.timed_releases.load() == timed + 1, "the timed release is counted");
1801 q->Release();
1802 }
1803
1804 // LEONIDA_DSTORAGE_HOLD_MS=0: no time limit, the entries wait for Submit.
1805 {
1806 reset();
1807 SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", L"0");
1808 auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME);
1809 SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", nullptr);
1810 auto* status = make_status(env, 1);
1811 const uint64_t timed = h.timed_releases.load();
1812 ULONG_PTR list[] = {static_cast<ULONG_PTR>(pages[0])};
1813 DSTORAGE_REQUEST r = into_pages(list);
1814 q->EnqueueRequest(&r);
1815 for (int i = 1; i < kHalf; ++i) {
1816 r = into_buffer(outs.data() + i * 16);
1817 q->EnqueueRequest(&r);
1818 }
1819 Sleep(2300); // past the default limit
1820 check(zero(window, bytes) && h.timed_releases.load() == timed, "with 0 a hold outlasts the default limit");
1821 q->EnqueueStatus(status, 0);
1822 q->Submit();
1823 check(wait_complete(status, 0) && holds_plain(window, bytes), "and ends at Submit");
1824 status->Release();
1825 q->Release();
1826 }
1827
1828 // LEONIDA_DSTORAGE_HOLD_PAGES=0: the self-submit takes everything, as before.
1829 {
1830 reset();
1831 SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_PAGES", L"0");
1832 auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME);
1833 SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_PAGES", nullptr);
1834 const uint64_t held = h.held_reads.load();
1835 ULONG_PTR list[] = {static_cast<ULONG_PTR>(pages[1])};
1836 DSTORAGE_REQUEST r = into_pages(list);
1837 q->EnqueueRequest(&r);
1838 for (int i = 1; i < kHalf; ++i) {
1839 r = into_buffer(outs.data() + i * 16);
1840 q->EnqueueRequest(&r);
1841 }
1842 check(wait_until([&] { return holds_plain(window + page, bytes); }),
1843 "LEONIDA_DSTORAGE_HOLD_PAGES=0 submits a read into pages with the rest");
1844 check(h.held_reads.load() == held, "and holds nothing");
1845 q->Release();
1846 }
1847
1848 // A list that names page 0 when its data is written fails the entry and is counted.
1849 {
1850 auto* q = make_queue(env, 0x80, false, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME);
1851 auto* status = make_status(env, 1);
1852 const uint64_t page0 = h.page0_entries.load();
1853 ULONG_PTR list[] = {0};
1854 DSTORAGE_REQUEST r = into_pages(list);
1855 q->EnqueueRequest(&r);
1856 q->EnqueueStatus(status, 0);
1857 q->Submit();
1858 check(wait_complete(status, 0), "the read with an empty page list completes");
1859 check_hr(status->GetHResult(0), E_INVALIDARG, "a page list naming page 0 at Submit fails its entry");
1860 check(h.page0_entries.load() == page0 + 1, "the entry with page 0 in its list is counted");
1861 status->Release();
1862 q->Release();
1863 }
1864
1865 map(window, 2, nullptr);
1866 free_pages(count, pages);
1867 VirtualFree(window, 0, MEM_RELEASE);
1868}
1869
1616} // namespace 1870} // namespace
1617 1871
1618int main() { 1872int main() {
@@ -1668,6 +1922,7 @@ int main() {
1668 test_stats_timing(env); 1922 test_stats_timing(env);
1669 test_stats(env); 1923 test_stats(env);
1670 test_extended(env); 1924 test_extended(env);
1925 test_page_reads_wait_for_submit(env);
1671 test_guarded_destinations(env); 1926 test_guarded_destinations(env);
1672 test_zlib(env); // after test_stats, whose request totals it would change 1927 test_zlib(env); // after test_stats, whose request totals it would change
1673 1928
diff --git a/runtime/test/gameinput_no_sdl_test.cpp b/runtime/test/gameinput_no_sdl_test.cpp
index a131dc7c9..24a29f2a6 100644
--- a/runtime/test/gameinput_no_sdl_test.cpp
+++ b/runtime/test/gameinput_no_sdl_test.cpp
@@ -98,8 +98,10 @@ Pad read_at(IGameInput* input, IGameInputDevice* device, double seconds) {
98} 98}
99 99
100int scripted_pad(CreateFn create) { 100int scripted_pad(CreateFn create) {
101 // Four presses (two overlapping A presses, Menu, a right-stick throw) and three rejected entries. 101 // Five presses (two overlapping A presses, Menu, B held 0.8 s, a right-stick throw) and seven rejected entries
102 SetEnvironmentVariableA("LEONIDA_INPUT_SCRIPT", "a@1, START@2.5 ,a@1.2,rsup@4,bogus@1,a@-1,"); 102 // (four of them holds that are zero, negative, missing or too long).
103 SetEnvironmentVariableA("LEONIDA_INPUT_SCRIPT",
104 "a@1, START@2.5 ,a@1.2,b@3:0.8 ,rsup@4,bogus@1,a@-1,,x@3:0,x@3:-1,x@3:,x@3:601");
103 rt::gameinput_no_sdl::set_clock(fake_clock); 105 rt::gameinput_no_sdl::set_clock(fake_clock);
104 at(0); 106 at(0);
105 107
@@ -201,6 +203,10 @@ int scripted_pad(CreateFn create) {
201 check(menu.buttons == GameInputGamepadMenu && menu.ui == GameInputUiNavigationMenu, 203 check(menu.buttons == GameInputGamepadMenu && menu.ui == GameInputUiNavigationMenu,
202 "script: START (any case) holds Menu at 2.6 s"); 204 "script: START (any case) holds Menu at 2.6 s");
203 check(read_at(input, device, 2.85).buttons == 0, "script: Menu is released at 2.85 s"); 205 check(read_at(input, device, 2.85).buttons == 0, "script: Menu is released at 2.85 s");
206 check(read_at(input, device, 3.05).buttons == GameInputGamepadB, "script: b@3:0.8 holds B at 3.05 s");
207 check(read_at(input, device, 3.7).buttons == GameInputGamepadB,
208 "script: B is still held at 3.7 s, past the 0.3 s default");
209 check(read_at(input, device, 3.85).buttons == 0, "script: B is released after its 0.8 s hold");
204 const Pad up = read_at(input, device, 4.1); 210 const Pad up = read_at(input, device, 4.1);
205 check(up.buttons == 0 && up.right_y == 1.0f && up.ui == GameInputUiNavigationScrollUp, 211 check(up.buttons == 0 && up.right_y == 1.0f && up.ui == GameInputUiNavigationScrollUp,
206 "script: rsup throws the right stick up at 4.1 s"); 212 "script: rsup throws the right stick up at 4.1 s");
diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp
index be9dc5398..09d959f34 100644
--- a/runtime/test/gameinput_test.cpp
+++ b/runtime/test/gameinput_test.cpp
@@ -1718,10 +1718,12 @@ int main(int argc, char** argv) {
1718 check(create(&input) == S_OK && input, "GameInputCreate returns an instance"); 1718 check(create(&input) == S_OK && input, "GameInputCreate returns an instance");
1719 if (argc == 2 && std::strcmp(argv[1], "--input-script") == 0) { 1719 if (argc == 2 && std::strcmp(argv[1], "--input-script") == 0) {
1720 if (!input) return 1; 1720 if (!input) return 1;
1721 // Only the X after byte 63 is due now. Its later entry must not cancel it. 1721 // Only the X after byte 63 and the Y held 0.6 s are due now. X's later entry must not cancel it; the
1722 // malformed holds at the end hold nothing.
1722 set_env("LEONIDA_INPUT_SCRIPT", 1723 set_env("LEONIDA_INPUT_SCRIPT",
1723 "start@3600,start@3600,start@3600,start@3600,start@3600,start@3600, X@0 \t,x@3600," 1724 "start@3600,start@3600,start@3600,start@3600,start@3600,start@3600, X@0 \t,x@3600,"
1724 "unknown@0,a@,a@x,,a@-0.1,a@nan,a@inf,a@1e999,a@0tail, ,"); 1725 "unknown@0,a@,a@x,,a@-0.1,a@nan,a@inf,a@1e999,a@0tail, ,y@0:0.6,"
1726 "a@0:0,a@0:-1,a@0:,a@0:x,a@0:inf,a@0:601,a@0:1tail");
1725 set_env("LEONIDA_KEYBOARD_PAD", "1"); 1727 set_env("LEONIDA_KEYBOARD_PAD", "1");
1726 rt::gameinput::set_keyboard_source(fake_key_down, fake_focus); 1728 rt::gameinput::set_keyboard_source(fake_key_down, fake_focus);
1727 rt::gameinput::set_cursor_source(fake_cursor); 1729 rt::gameinput::set_cursor_source(fake_cursor);
@@ -1730,27 +1732,32 @@ int main(int argc, char** argv) {
1730 rt::gameinput::reload_config(); 1732 rt::gameinput::reload_config();
1731 rt::gameinput::poll(); 1733 rt::gameinput::poll();
1732 const auto buttons = pad_state(input, nullptr).buttons; 1734 const auto buttons = pad_state(input, nullptr).buttons;
1733 const auto expected = GameInputGamepadX | GameInputGamepadB; 1735 const auto expected = GameInputGamepadX | GameInputGamepadB | GameInputGamepadY;
1734 check((buttons & expected) == expected, "long script: the spaced X after byte 63 and the physical B are held"); 1736 check((buttons & expected) == expected,
1737 "long script: the spaced X after byte 63, the held Y and the physical B are held");
1735 check((buttons & ~expected) == 0, "malformed script entries hold no extra buttons"); 1738 check((buttons & ~expected) == 0, "malformed script entries hold no extra buttons");
1736 g_focus = false; 1739 g_focus = false;
1737 set_env("LEONIDA_INPUT_SCRIPT", "y@0"); 1740 set_env("LEONIDA_INPUT_SCRIPT", "y@0");
1738 rt::gameinput::reload_config(); 1741 rt::gameinput::reload_config();
1739 rt::gameinput::poll(); 1742 rt::gameinput::poll();
1740 check(pad_state(input, nullptr).buttons == GameInputGamepadX, 1743 check(pad_state(input, nullptr).buttons == (GameInputGamepadX | GameInputGamepadY),
1741 "scripted X survives focus loss; reload does not replace it with Y"); 1744 "scripted X and Y survive focus loss; reload does not replace the script with y@0");
1742 Sleep(350); 1745 Sleep(350);
1743 g_focus = true; 1746 g_focus = true;
1744 rt::gameinput::poll(); 1747 rt::gameinput::poll();
1745 // A scripted press lasts its 300 ms and then until the title has read the pads six times since it began 1748 // A scripted press lasts its hold (300 ms, or button@seconds:hold) and then until the title has read the pads
1746 // (update_keyboard_pad: kReads, at most kMaxHold seconds), so a title that polls slowly still sees it. Each 1749 // six times since it began (update_keyboard_pad: kReads), so a title that polls slowly still sees it. Each
1747 // pad_state() is one GetCurrentReading, and this is the third since the X began. 1750 // pad_state() is one GetCurrentReading, and this is the third since X and Y began.
1748 check(pad_state(input, nullptr).buttons == (GameInputGamepadX | GameInputGamepadB), 1751 check(pad_state(input, nullptr).buttons == (GameInputGamepadX | GameInputGamepadB | GameInputGamepadY),
1749 "long script: past its 300 ms the press is still held while the title has read the pads fewer than six times"); 1752 "long script: past its 300 ms X is still held while the title has read the pads fewer than six times");
1750 for (int i = 0; i < 6; ++i) pad_state(input, nullptr); 1753 for (int i = 0; i < 6; ++i) pad_state(input, nullptr);
1751 rt::gameinput::poll(); 1754 rt::gameinput::poll();
1755 check(pad_state(input, nullptr).buttons == (GameInputGamepadB | GameInputGamepadY),
1756 "long script: X ends once the title has read it, y@0:0.6 is still held for its time, the key stays held");
1757 Sleep(400);
1758 rt::gameinput::poll();
1752 check(pad_state(input, nullptr).buttons == GameInputGamepadB, 1759 check(pad_state(input, nullptr).buttons == GameInputGamepadB,
1753 "long script: the timed press ends once the title has read it, while the physical key stays held"); 1760 "long script: Y is released after its 0.6 s hold, the title having read it six times");
1754 input->Release(); 1761 input->Release();
1755 std::printf("%d checks, %d failures\n", g_checks, g_failures); 1762 std::printf("%d checks, %d failures\n", g_checks, g_failures);
1756 return g_failures ? 1 : 0; 1763 return g_failures ? 1 : 0;
diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp
index caac93dc0..d1e9a07d8 100644
--- a/runtime/test/geometry_views_test.cpp
+++ b/runtime/test/geometry_views_test.cpp
@@ -16,7 +16,10 @@
16// 13. a submission's sequence on an idle GPU (completed == submitted): a view retired by the drain in before_execute_ 16// 13. a submission's sequence on an idle GPU (completed == submitted): a view retired by the drain in before_execute_
17// (kAfterExecutes) is freed only after every replay begun before the retirement recorded its submissions and those 17// (kAfterExecutes) is freed only after every replay begun before the retirement recorded its submissions and those
18// completed (a ticket read in the drain reaps it at once); its answers made without an alias are invalidated 18// completed (a ticket read in the drain reaps it at once); its answers made without an alias are invalidated
19// (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device. 19// (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device;
20// 14. LEONIDA_GEOMETRY_HOST picks a system-memory type (write-back for 1, write-combined for 2), never the BAR;
21// 15. a retired view is copied once more from its pages when they are readable (a remap), not when they are not;
22// 16. a full release queue joins touching ranges before it collapses to one covering range.
20#include <windows.h> 23#include <windows.h>
21 24
22#include <cstdint> 25#include <cstdint>
@@ -61,7 +64,7 @@ VKAPI_ATTR void VKAPI_CALL requirements(VkDevice, VkBuffer buffer, VkMemoryRequi
61 *out = {}; 64 *out = {};
62 out->size = reinterpret_cast<FakeBuffer*>(buffer)->size; 65 out->size = reinterpret_cast<FakeBuffer*>(buffer)->size;
63 out->alignment = 65536; 66 out->alignment = 65536;
64 out->memoryTypeBits = 1; 67 out->memoryTypeBits = 0xf; // the four types of test 14's device
65} 68}
66VKAPI_ATTR VkResult VKAPI_CALL bind(VkDevice, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize) { 69VKAPI_ATTR VkResult VKAPI_CALL bind(VkDevice, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize) {
67 reinterpret_cast<FakeBuffer*>(buffer)->memory = memory; 70 reinterpret_cast<FakeBuffer*>(buffer)->memory = memory;
@@ -510,6 +513,109 @@ int main() {
510 } 513 }
511 VirtualFree(fly_title, 0, MEM_RELEASE); 514 VirtualFree(fly_title, 0, MEM_RELEASE);
512 515
516 // 14. LEONIDA_GEOMETRY_HOST: the copies' memory type. A discrete GPU's types: 0 VRAM, 1 VRAM through the BAR,
517 // 2 system memory write-combined, 3 system memory write-back. 1 takes type 3 (write-back preferred), 2 type 2,
518 // unset any host-visible type with device-local preferred (the BAR); a device whose host-visible types are all
519 // device-local (an integrated GPU) keeps them all.
520 {
521 struct TypedDevice : FakeDevice {
522 VkPhysicalDeviceMemoryProperties memory{};
523 std::uint32_t bits = 0;
524 VkMemoryPropertyFlags preferred = 0;
525 VkDeviceMemory allocate(const VkMemoryRequirements& r, VkMemoryPropertyFlags required,
526 VkMemoryPropertyFlags wanted, VkMemoryPropertyFlags* chosen, bool address) {
527 bits = r.memoryTypeBits;
528 preferred = wanted;
529 return FakeDevice::allocate(r, required, wanted, chosen, address);
530 }
531 };
532 constexpr VkMemoryPropertyFlags kLocal = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
533 kHost = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
534 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
535 kCached = VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
536 TypedDevice discrete;
537 discrete.memory.memoryTypeCount = 4;
538 const VkMemoryPropertyFlags discrete_types[4] = {kLocal, kLocal | kHost, kHost, kHost | kCached};
539 for (int i = 0; i < 4; ++i) discrete.memory.memoryTypes[i].propertyFlags = discrete_types[i];
540 TypedDevice integrated;
541 integrated.memory.memoryTypeCount = 2;
542 integrated.memory.memoryTypes[0].propertyFlags = kLocal;
543 integrated.memory.memoryTypes[1].propertyFlags = kLocal | kHost | kCached;
544 auto* host_title =
545 static_cast<std::uint8_t*>(VirtualAlloc(nullptr, kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
546 if (!host_title) return 1;
547 const auto hbase = reinterpret_cast<std::uintptr_t>(host_title);
548 const auto made_with = [&](TypedDevice& dev, const char* setting) {
549 _putenv_s("LEONIDA_GEOMETRY_HOST", setting);
550 dev.bits = ~0u;
551 dev.preferred = 0;
552 rt::d3d12::GeometryViews v;
553 const bool made = v.resolve(dev, hbase, kView, copy) != 0;
554 const int kind = v.system_memory();
555 v.release(dev);
556 return made ? kind : -1;
557 };
558 check(made_with(discrete, "1") == rt::d3d12::TitleBufferWindows::kSystemCached && discrete.bits == 1u << 3 &&
559 discrete.preferred == kCached,
560 "LEONIDA_GEOMETRY_HOST=1 puts the copies in write-back system memory, never the BAR");
561 check(made_with(discrete, "2") == rt::d3d12::TitleBufferWindows::kSystemUncached && discrete.bits == 1u << 2 &&
562 discrete.preferred == 0,
563 "LEONIDA_GEOMETRY_HOST=2 puts them in write-combined system memory");
564 check(made_with(discrete, "") == rt::d3d12::TitleBufferWindows::kDeviceLocal && discrete.bits == 0xfu &&
565 discrete.preferred == kLocal,
566 "unset, every type the buffer allows is tried, device-local first");
567 check(made_with(integrated, "1") == rt::d3d12::TitleBufferWindows::kSystemCached && integrated.bits == 0xfu,
568 "on a device with no host type outside device-local memory, the types are left as they are");
569 _putenv_s("LEONIDA_GEOMETRY_HOST", "");
570 check(g_live_buffers == 0, "the memory-type views free their blocks");
571
572 // 15. A retired view is copied once more from the title's pages when they are readable (a remap gave them new
573 // bytes), and keeps what it held when they are not (freed or unmapped).
574 rt::d3d12::GeometryViews last;
575 std::memset(host_title, 0x11, kView);
576 const std::uint64_t va_l = last.resolve(device, hbase, kView, copy);
577 std::uint64_t host_l = 0, bytes_l = 0;
578 check(va_l && last.lookup(device.arena.address + va_l, host_l, bytes_l), "a view to retire");
579 auto* held = reinterpret_cast<const std::uint8_t*>(host_l);
580 // The remapped pages' bytes: the watched tiles are opened first (no fault handler here).
581 leonida::geometry_writes::notify(hbase, hbase + kView, leonida::geometry_writes::Event::open);
582 std::memset(host_title, 0x22, kView);
583 g_copies.clear();
584 check(last.retire_range(hbase, hbase + kView, 1, [](std::uintptr_t, std::size_t, VkDeviceSize) {}, copy) == 1 &&
585 held[0] == 0x22 && held[kView - 1] == 0x22 && last.final_copies() == 1 && g_copies.size() == 1,
586 "a retired view whose pages are readable is copied from them once more");
587 const std::uint64_t va_l2 = last.resolve(device, hbase, kView, copy);
588 std::uint64_t host_l2 = 0;
589 check(va_l2 && last.lookup(device.arena.address + va_l2, host_l2, bytes_l), "and made again");
590 auto* held2 = reinterpret_cast<const std::uint8_t*>(host_l2);
591 leonida::geometry_writes::notify(hbase, hbase + kView, leonida::geometry_writes::Event::open);
592 std::memset(host_title, 0x33, kView);
593 const auto unreadable = [](std::uint8_t*, const std::uint8_t*, std::size_t) {
594 return rt::d3d12::GeometryCopy::unreadable;
595 };
596 check(last.retire_range(hbase, hbase + kView, 2, [](std::uintptr_t, std::size_t, VkDeviceSize) {},
597 unreadable) == 1 &&
598 held2[0] == 0x22 && last.final_copies() == 1,
599 "one whose pages are not readable keeps what it held");
600 check(last.reap(device, 2) == 2 && last.bytes() == 0, "both are freed at their tickets");
601 last.release(device);
602
603 // 16. A full release queue first joins ranges that touch (remaps report page runs): 65536 neighbouring ranges
604 // and one apart from them are two ranges, not one covering everything between them.
605 rt::d3d12::GeometryViews coalesce;
606 check(coalesce.resolve(device, hbase, kView, copy) != 0, "a view to watch the pages");
607 for (std::size_t i = 0; i < 65536; ++i)
608 leonida::geometry_writes::note_released(hbase + i * 8, hbase + i * 8 + 8);
609 leonida::geometry_writes::note_released(hbase + kView - 4096, hbase + kView);
610 std::vector<std::pair<std::uintptr_t, std::uintptr_t>> joined;
611 leonida::geometry_writes::take_released(coalesce.release_queue(), joined);
612 check(joined.size() == 2 && joined[0] == std::make_pair(hbase, hbase + 65536 * 8) &&
613 joined[1] == std::make_pair(hbase + kView - 4096, hbase + kView),
614 "65536 touching ranges become one, and a range apart from them stays apart");
615 coalesce.release(device);
616 VirtualFree(host_title, 0, MEM_RELEASE);
617 }
618
513 std::printf("%d checks, %d failures\n", g_checks, g_failures); 619 std::printf("%d checks, %d failures\n", g_checks, g_failures);
514 return g_failures ? 1 : 0; 620 return g_failures ? 1 : 0;
515} 621}
diff --git a/runtime/test/heavy_pipeline_cache_test.cpp b/runtime/test/heavy_pipeline_cache_test.cpp
new file mode 100644
index 000000000..8181a047c
--- /dev/null
+++ b/runtime/test/heavy_pipeline_cache_test.cpp
@@ -0,0 +1,109 @@
1// src/heavy_pipeline_cache.h: the LEONIDA_HEAVY_PIPELINE_CACHE_MS threshold and when the heavy cache is written.
2// No Vulkan, no GPU, no files.
3#include "../src/heavy_pipeline_cache.h"
4
5#include <cstdio>
6#include <initializer_list>
7
8#define CHECK(condition) do { \
9 if (!(condition)) { \
10 std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
11 return 1; \
12 } \
13} while (0)
14
15namespace heavy = leonida::heavy_pipeline_cache;
16
17static int test_threshold() {
18 CHECK(heavy::parse_threshold(nullptr).ms == heavy::default_threshold_ms);
19 CHECK(heavy::parse_threshold("").ms == heavy::default_threshold_ms);
20 CHECK(heavy::parse_threshold("0").ms == 0 && heavy::parse_threshold("0").valid); // off
21 CHECK(heavy::parse_threshold("2000").ms == 2000);
22 CHECK(heavy::parse_threshold("0750").ms == 750);
23 // Not a number, a sign, a unit or an absurd value: the default, reported as invalid.
24 for (const char* bad : {"-1", "+5", "1s", "1.5", "abc", "3600001", "99999999999999999999"}) {
25 const auto t = heavy::parse_threshold(bad);
26 CHECK(!t.valid && t.ms == heavy::default_threshold_ms);
27 }
28 CHECK(heavy::parse_threshold("3600000").valid);
29 return 0;
30}
31
32static int test_schedule() {
33 using S = heavy::WriteSchedule;
34 S s;
35 CHECK(!s.dirty() && !s.due(1'000'000));
36 // One heavy compile: written once it has settled.
37 s.note_heavy(1000);
38 CHECK(s.dirty() && !s.due(1000 + S::settle_ms - 1) && s.due(1000 + S::settle_ms));
39 s.written(s.generation(), 1000 + S::settle_ms);
40 CHECK(!s.dirty());
41 // A burst, one compile a second for a minute: the write does not wait for the burst to end.
42 S burst;
43 for (std::uint64_t t = 10'000; t <= 70'000; t += 1000) {
44 burst.note_heavy(t);
45 if (burst.due(t)) {
46 CHECK(t - 10'000 >= S::max_delay_ms); // first write no later than max_delay after the first compile
47 burst.written(burst.generation(), t);
48 break;
49 }
50 }
51 CHECK(!burst.dirty());
52 // A compile that finishes while a write is running is not lost: the cache stays dirty for the next write.
53 S racing;
54 racing.note_heavy(5000);
55 const std::uint64_t start = 5000 + S::settle_ms;
56 const std::uint64_t taken = racing.generation();
57 racing.note_heavy(start + 10); // during the write
58 racing.written(taken, start);
59 CHECK(racing.dirty());
60 CHECK(racing.due(start + 10 + S::settle_ms));
61 // The same, inside one tick of a coarse clock: the compile noted at the write's own start time is still kept.
62 S tick;
63 tick.note_heavy(9000);
64 const std::uint64_t at = 9000 + S::settle_ms;
65 const std::uint64_t before = tick.generation();
66 tick.note_heavy(at);
67 tick.written(before, at);
68 CHECK(tick.dirty());
69 return 0;
70}
71
72static int test_failed_write() {
73 using S = heavy::WriteSchedule;
74 S s;
75 s.note_heavy(1000);
76 std::uint64_t now = 1000 + S::settle_ms;
77 CHECK(s.due(now));
78 // A failed write keeps the cache dirty and waits out the backoff before the next try.
79 s.failed(now);
80 CHECK(s.dirty() && s.failures() == 1);
81 CHECK(!s.due(now) && !s.due(now + S::retry_ms - 1) && s.due(now + S::retry_ms));
82 // Failures in a row double the delay up to the cap, so a write that keeps failing does not spin.
83 std::uint64_t expect = S::retry_ms;
84 for (int i = 0; i < 12; ++i) {
85 now = s.due_ms();
86 s.failed(now);
87 expect = expect * 2 > S::max_retry_ms ? S::max_retry_ms : expect * 2;
88 CHECK(s.due_ms() == now + expect);
89 }
90 CHECK(s.due_ms() - now == S::max_retry_ms);
91 // A heavy compile during the backoff does not bring the retry forward.
92 s.note_heavy(now + 1);
93 CHECK(!s.due(now + S::settle_ms + 1) && s.due(now + S::max_retry_ms));
94 // A successful write clears the dirty flag and the backoff.
95 now = s.due_ms();
96 s.written(s.generation(), now);
97 CHECK(!s.dirty() && s.failures() == 0);
98 s.note_heavy(now + 10);
99 CHECK(s.due(now + 10 + S::settle_ms));
100 return 0;
101}
102
103int main() {
104 if (const int r = test_threshold()) return r;
105 if (const int r = test_schedule()) return r;
106 if (const int r = test_failed_write()) return r;
107 std::printf("heavy_pipeline_cache: threshold parsing, the write schedule and retries after a failed write\n");
108 return 0;
109}
diff --git a/runtime/test/list_value_wait_budget_test.cpp b/runtime/test/list_value_wait_budget_test.cpp
new file mode 100644
index 000000000..6bf9bfbf5
--- /dev/null
+++ b/runtime/test/list_value_wait_budget_test.cpp
@@ -0,0 +1,348 @@
1// Portable CPU-only unit tests for runtime/src/list_value_wait_budget.h (RT-LIST-VALUE-WAIT-WORK-AWARE-TIMEOUT):
2// work-aware timeout pausing, finite pause caps across all pause reasons (including releaser_busy and
3// matching_producer), demoted-gate cap scaling, cycle detection across multi-queue write/gate chains, overwrite-aware
4// write matching, action gates, and a mock Pump tick driver. No Windows, D3D12, or Vulkan headers; no game files.
5#include "../src/list_value_wait_budget.h"
6
7#include <climits>
8#include <cstdio>
9#include <vector>
10
11#define CHECK(cond) do { \
12 if (!(cond)) { \
13 std::fprintf(stderr, "line %d: CHECK failed: %s\n", __LINE__, #cond); \
14 return 1; \
15 } \
16} while (0)
17
18namespace {
19
20constexpr bool test_met(std::uint32_t comparison, std::uint64_t value, std::uint64_t reference, bool wide) {
21 if (!wide) {
22 value &= 0xffffffffu;
23 reference &= 0xffffffffu;
24 }
25 switch (comparison) {
26 case 2: return value < reference;
27 case 3: return value == reference;
28 case 4: return value <= reference;
29 case 5: return value > reference;
30 case 6: return value != reference;
31 case 7: return value >= reference;
32 default: return true;
33 }
34}
35
36} // namespace
37
38int main() {
39 using namespace leonida::list_value_wait;
40
41 int q1_tag = 0, q2_tag = 0, q3_tag = 0;
42 const void* const q1 = &q1_tag;
43 const void* const q2 = &q2_tag;
44 const void* const q3 = &q3_tag;
45
46 // 1. Idle unmodelled wait: PauseReason::none -> expires at exact budget_us.
47 {
48 const WaitPredicate waits[] = {{0x1000, 5, 7, true}}; // >= 5
49 const PendingGate gates[] = {{q1, 1, false, waits}};
50 CHECK(pause_reason(false, {}, gates, 0, test_met) == PauseReason::none);
51
52 GateTimeoutState t;
53 const PauseCaps caps = default_pause_caps(200, false);
54 t.reset(200'000, caps.active_us, caps.max_us);
55 CHECK(!t.advance(100'000, PauseReason::none));
56 CHECK(t.elapsed_us == 100'000 && !t.paused_ever);
57 CHECK(!t.advance(99'999, PauseReason::none));
58 CHECK(t.advance(1, PauseReason::none));
59 CHECK(t.elapsed_us == 200'000);
60 }
61
62 // 2. Releaser actively executing held work pauses the timeout clock (covering multi-minute world-phase pipeline
63 // builds without burning idle budget), yet still expires at the finite max_pause_cap_us if a Signal hangs.
64 {
65 const WaitPredicate waits[] = {{0x1000, 5, 7, true}};
66 const PendingGate gates[] = {{q1, 1, false, waits}};
67 CHECK(pause_reason(true, {}, gates, 0, test_met) == PauseReason::releaser_busy);
68
69 GateTimeoutState t;
70 const PauseCaps caps = default_pause_caps(200, false);
71 CHECK(caps.active_us == 60'000'000ull && caps.max_us == 300'000'000ull);
72 t.reset(200'000, caps.active_us, caps.max_us);
73 // 120 seconds of releaser executing pipeline builds/copies burns 0 us of idle timeout budget.
74 for (int i = 0; i < 120; ++i) CHECK(!t.advance(1'000'000, PauseReason::releaser_busy));
75 CHECK(t.elapsed_us == 0 && t.total_paused_us == 120'000'000ull && t.paused_ever);
76 // Once idle again, still gets its full 200 ms budget before expiring.
77 CHECK(!t.advance(199'000, PauseReason::none));
78 CHECK(t.advance(1'000, PauseReason::none));
79
80 // Hung Signal (releaser_busy forever) hits the finite max_pause_cap_us and then drains budget_us.
81 GateTimeoutState hung;
82 hung.reset(200'000, caps.active_us, caps.max_us);
83 for (int i = 0; i < 300; ++i) CHECK(!hung.advance(1'000'000, PauseReason::releaser_busy));
84 CHECK(hung.total_paused_us == 300'000'000ull && hung.elapsed_us == 0);
85 CHECK(!hung.advance(199'000, PauseReason::releaser_busy));
86 CHECK(hung.advance(1'000, PauseReason::releaser_busy));
87 CHECK(hung.elapsed_us == 200'000);
88 }
89
90 // 3. Matching unblocked producer write on another queue (Wait-before-Signal) -> PauseReason::matching_producer.
91 {
92 const WaitPredicate waits[] = {{0x2000, 10, 7, true}}; // >= 10
93 const PendingWrite w_ok[] = {{0x2000, 12, 8, false}};
94 const PendingWriteGroup groups[] = {{q2, 0, w_ok}};
95 const PendingGate gates[] = {{q1, 1, false, waits}};
96 CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::matching_producer);
97
98 // Timestamp write to the same address also matches (final value unknown until landing).
99 const PendingWrite w_ts[] = {{0x2000, 0, 8, true}};
100 const PendingWriteGroup ts_groups[] = {{q2, 0, w_ts}};
101 CHECK(pause_reason(false, ts_groups, gates, 0, test_met) == PauseReason::matching_producer);
102
103 // Matching write overwritten later in the same WriteGroup by a non-matching value does NOT match,
104 // falling back to active_work (since q2's group is unblocked).
105 const PendingWrite w_overwritten[] = {{0x2000, 12, 8, false}, {0x2000, 3, 8, false}};
106 const PendingWriteGroup ow_groups[] = {{q2, 0, w_overwritten}};
107 CHECK(pause_reason(false, ow_groups, gates, 0, test_met) == PauseReason::active_work);
108
109 // Partial overlap by a later write in the same group invalidates the earlier matching write.
110 const PendingWrite w_partial[] = {{0x2000, 12, 8, false}, {0x2004, 0, 4, false}};
111 const PendingWriteGroup part_groups[] = {{q2, 0, w_partial}};
112 CHECK(pause_reason(false, part_groups, gates, 0, test_met) == PauseReason::active_work);
113
114 // 4-byte write cannot satisfy an 8-byte (wide) wait.
115 const PendingWrite w_narrow[] = {{0x2000, 12, 4, false}};
116 const PendingWriteGroup nar_groups[] = {{q2, 0, w_narrow}};
117 CHECK(pause_reason(false, nar_groups, gates, 0, test_met) == PauseReason::active_work);
118
119 // 8-byte write CAN satisfy a 4-byte wait (low 32 bits compared).
120 const WaitPredicate wait32[] = {{0x2000, 10, 7, false}};
121 const PendingWrite w_hi_lo[] = {{0x2000, 0x100000000ull | 12ull, 8, false}};
122 const PendingWriteGroup hilo_groups[] = {{q2, 0, w_hi_lo}};
123 const PendingGate gates32[] = {{q1, 1, false, wait32}};
124 CHECK(pause_reason(false, hilo_groups, gates32, 0, test_met) == PauseReason::matching_producer);
125 }
126
127 // 4. Same-queue ordering: a write submitted BEFORE the gate (after_gate < gate.value) IS a live producer;
128 // a write submitted AFTER the gate (after_gate >= gate.value) is a self-deadlock and MUST NOT pause the gate.
129 {
130 const WaitPredicate waits[] = {{0x3000, 1, 7, true}};
131 const PendingWrite w[] = {{0x3000, 1, 8, false}};
132 const PendingGate gates[] = {{q1, 2, false, waits}};
133
134 const PendingWriteGroup before_gate[] = {{q1, 1, w}}; // after_gate 1 < gate.value 2 (unblocked!)
135 CHECK(pause_reason(false, before_gate, gates, 0, test_met) == PauseReason::matching_producer);
136
137 const PendingWriteGroup behind_gate[] = {{q1, 2, w}}; // after_gate 2 == gate.value 2 (held by itself!)
138 CHECK(pause_reason(false, behind_gate, gates, 0, test_met) == PauseReason::none);
139 }
140
141 // 5. Mutual 2-queue cycle (Q1 waits on Q2's write behind G2; Q2 waits on Q1's write behind G1):
142 // NEITHER gate pauses, so the cycle breaks cleanly instead of deadlocking.
143 {
144 const WaitPredicate w1[] = {{0x4000, 1, 7, true}};
145 const WaitPredicate w2[] = {{0x5000, 1, 7, true}};
146 const PendingWrite pw1[] = {{0x5000, 1, 8, false}}; // Q1 writes what Q2 waits for, behind Q1's gate 1
147 const PendingWrite pw2[] = {{0x4000, 1, 8, false}}; // Q2 writes what Q1 waits for, behind Q2's gate 1
148 const PendingWriteGroup groups[] = {{q1, 1, pw1}, {q2, 1, pw2}};
149 const PendingGate gates[] = {{q1, 1, false, w1}, {q2, 1, false, w2}};
150 CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::none);
151 CHECK(pause_reason(false, groups, gates, 1, test_met) == PauseReason::none);
152 }
153
154 // 6. 3-queue cycle involving a SECOND (non-front) gate on Q2:
155 // Q1 gate 1 waits on W2 (behind Q2 gates 1 & 2); Q2 gate 2 waits on W1 (behind Q1 gate 1).
156 // Checking all gates <= after_gate catches this indirect cycle!
157 {
158 const WaitPredicate w_q1[] = {{0x6000, 1, 7, true}};
159 const WaitPredicate w_q2_g1[] = {{0x6100, 1, 7, true}}; // unrelated front gate on Q2
160 const WaitPredicate w_q2_g2[] = {{0x6200, 1, 7, true}}; // second gate on Q2 waits on Q1
161 const PendingWrite pw_q1[] = {{0x6200, 1, 8, false}}; // behind Q1 gate 1
162 const PendingWrite pw_q2[] = {{0x6000, 1, 8, false}}; // behind Q2 gate 2 (after_gate = 2)
163 const PendingWriteGroup groups[] = {{q1, 1, pw_q1}, {q2, 2, pw_q2}};
164 const PendingGate gates[] = {
165 {q1, 1, false, w_q1},
166 {q2, 1, false, w_q2_g1},
167 {q2, 2, false, w_q2_g2},
168 };
169 CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::none);
170 CHECK(pause_reason(false, groups, gates, 2, test_met) == PauseReason::none);
171 }
172
173 // 7. Acyclic 3-queue chain (Q1 -> Q2 -> Q3 where Q3's gate has no producer):
174 // Q3 does NOT pause (times out first), while Q2 and Q1 wait for their upstream producers to run in order!
175 {
176 const WaitPredicate w_q1[] = {{0x7000, 1, 7, true}};
177 const WaitPredicate w_q2[] = {{0x7100, 1, 7, true}};
178 const WaitPredicate w_q3[] = {{0x7200, 1, 7, true}}; // unmodelled wait on Q3
179 const PendingWrite pw_q2[] = {{0x7000, 1, 8, false}}; // Q2 feeds Q1 (behind Q2 gate 1)
180 const PendingWrite pw_q3[] = {{0x7100, 1, 8, false}}; // Q3 feeds Q2 (behind Q3 gate 1)
181 const PendingWriteGroup groups[] = {{q2, 1, pw_q2}, {q3, 1, pw_q3}};
182 const PendingGate gates[] = {
183 {q1, 1, false, w_q1},
184 {q2, 1, false, w_q2},
185 {q3, 1, false, w_q3},
186 };
187 CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::matching_producer);
188 CHECK(pause_reason(false, groups, gates, 1, test_met) == PauseReason::matching_producer);
189 CHECK(pause_reason(false, groups, gates, 2, test_met) == PauseReason::none);
190 }
191
192 // 8. Action gate on another queue counts as active_work when unblocked, and does NOT count when blocked behind a
193 // memory gate on its own queue.
194 {
195 const WaitPredicate w_q1[] = {{0x8000, 1, 7, true}};
196 const WaitPredicate w_q2[] = {{0x8100, 1, 7, true}};
197 const PendingGate unblocked_action[] = {
198 {q1, 1, false, w_q1},
199 {q2, 1, true, {}}, // unblocked action gate on Q2
200 };
201 CHECK(pause_reason(false, {}, unblocked_action, 0, test_met) == PauseReason::active_work);
202
203 const PendingGate blocked_action[] = {
204 {q1, 1, false, w_q1},
205 {q2, 1, false, w_q2}, // memory gate blocking Q2
206 {q2, 2, true, {}}, // action gate behind Q2's memory gate
207 };
208 CHECK(pause_reason(false, {}, blocked_action, 0, test_met) == PauseReason::none);
209 }
210
211 // 9. Bounded pause caps: active_work, matching_producer, releaser_busy, combined alternating reasons, and
212 // demoted-gate cap scaling.
213 {
214 CHECK(default_active_pause_cap_us(200) == 60'000'000ull);
215 CHECK(default_max_pause_cap_us(200) == 300'000'000ull);
216 CHECK(default_active_pause_cap_us(30) == 9'000'000ull);
217 CHECK(default_max_pause_cap_us(30) == 45'000'000ull);
218 CHECK(default_active_pause_cap_us(1) == 300'000ull);
219 CHECK(default_max_pause_cap_us(1) == 1'500'000ull);
220 CHECK(default_active_pause_cap_us(30000) == 600'000'000ull);
221 CHECK(default_max_pause_cap_us(30000) == 600'000'000ull);
222 CHECK(default_active_pause_cap_us(UINT_MAX) == 600'000'000ull);
223 CHECK(default_max_pause_cap_us(UINT_MAX) == 600'000'000ull);
224
225 // Demoted (cut_short) gates scale caps with their short 4 ms budget instead of inheriting 60 s / 300 s.
226 const PauseCaps dem = default_pause_caps(4, true);
227 CHECK(dem.active_us == 4'000ull && dem.max_us == 16'000ull);
228 GateTimeoutState dem_active;
229 dem_active.reset(4'000, dem.active_us, dem.max_us);
230 CHECK(!dem_active.advance(4'000, PauseReason::active_work)); // absorbs 4 ms cap
231 CHECK(dem_active.active_paused_us == 4'000 && dem_active.elapsed_us == 0);
232 CHECK(!dem_active.advance(3'999, PauseReason::active_work));
233 CHECK(dem_active.advance(1, PauseReason::active_work)); // expires at 8 ms total, not 60 s!
234
235 GateTimeoutState dem_prod;
236 dem_prod.reset(4'000, dem.active_us, dem.max_us);
237 CHECK(!dem_prod.advance(16'000, PauseReason::matching_producer));
238 CHECK(dem_prod.total_paused_us == 16'000 && dem_prod.elapsed_us == 0);
239 CHECK(dem_prod.advance(4'000, PauseReason::matching_producer)); // expires at 20 ms total
240
241 // Normal gate active_work cap (5 s) vs larger max cap (20 s).
242 GateTimeoutState t;
243 t.reset(200'000, 5'000'000, 20'000'000);
244 for (int i = 0; i < 5; ++i) CHECK(!t.advance(1'000'000, PauseReason::active_work));
245 CHECK(t.active_paused_us == 5'000'000 && t.total_paused_us == 5'000'000 && t.elapsed_us == 0 && t.paused_ever);
246 CHECK(!t.advance(199'000, PauseReason::active_work));
247 CHECK(t.advance(1'000, PauseReason::active_work));
248 CHECK(t.elapsed_us == 200'000);
249
250 // Stuck matching_producer + alternating releaser_busy share total_paused_us <= max_pause_cap_us.
251 GateTimeoutState stuck;
252 stuck.reset(200'000, 2'000'000, 10'000'000);
253 CHECK(!stuck.advance(2'000'000, PauseReason::active_work)); // total = 2 s
254 CHECK(!stuck.advance(5'000'000, PauseReason::matching_producer)); // total = 7 s
255 CHECK(!stuck.advance(3'100'000, PauseReason::releaser_busy)); // 3 s paused (hits 10 s cap), 100 ms elapsed
256 CHECK(stuck.total_paused_us == 10'000'000 && stuck.elapsed_us == 100'000);
257 CHECK(!stuck.advance(99'999, PauseReason::matching_producer));
258 CHECK(stuck.advance(1, PauseReason::matching_producer));
259 CHECK(stuck.elapsed_us == 200'000);
260
261 // Partial step straddling active_pause_cap_us splits cleanly between active_paused_us and elapsed_us.
262 GateTimeoutState t2;
263 t2.reset(200'000, 500'000, 1'000'000);
264 CHECK(!t2.advance(600'000, PauseReason::active_work)); // 500k paused, 100k elapsed
265 CHECK(t2.active_paused_us == 500'000 && t2.total_paused_us == 500'000 && t2.elapsed_us == 100'000);
266 CHECK(t2.advance(100'000, PauseReason::active_work));
267
268 // active_cap > max_cap is clamped to max_cap by reset().
269 GateTimeoutState clamped;
270 clamped.reset(100'000, 9'000'000, 3'000'000);
271 CHECK(clamped.active_pause_cap_us == 3'000'000 && clamped.max_pause_cap_us == 3'000'000);
272 }
273
274 // 10. Overflow-safe address / dt_us guards and zero-dt paused tick.
275 {
276 const WaitPredicate overflow_wait[] = {{UINT64_MAX - 2, 1, 7, true}};
277 const PendingWrite overflow_write[] = {{UINT64_MAX - 2, 1, 8, false}};
278 const PendingWriteGroup groups[] = {{q2, 0, overflow_write}};
279 const PendingGate gates[] = {{q1, 1, false, overflow_wait}};
280 // Write doesn't match due to address wrap guard, falls back to active_work for the unblocked group.
281 CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::active_work);
282
283 GateTimeoutState t;
284 t.reset(1000, 0, 0);
285 CHECK(t.advance(UINT64_MAX, PauseReason::none));
286 CHECK(t.elapsed_us == UINT64_MAX);
287
288 GateTimeoutState z;
289 z.reset(0, 1000, 1000);
290 CHECK(!z.advance(0, PauseReason::releaser_busy));
291 CHECK(!z.paused_ever);
292 }
293
294 // 11. Mock Pump tick loop driving start_gate + pause_reason + GateTimeoutState end-to-end across 1 ms steps.
295 {
296 // (a) 200 ms gate held while releaser runs a 110 s pipeline build, then producer lands at 110.5 s: met!
297 const WaitPredicate waits[] = {{0x9000, 7, 7, true}};
298 const PendingWrite prod_write[] = {{0x9000, 7, 8, false}};
299 const PendingWriteGroup prod_groups[] = {{q2, 0, prod_write}};
300 const PendingGate gates[] = {{q1, 1, false, waits}};
301
302 GateTimeoutState gate;
303 const PauseCaps full_caps = default_pause_caps(200, false);
304 gate.reset(200'000, full_caps.active_us, full_caps.max_us);
305 for (int ms = 0; ms < 110'000; ++ms) {
306 const PauseReason r = pause_reason(true, prod_groups, gates, 0, test_met);
307 CHECK(r == PauseReason::releaser_busy && !gate.advance(1'000, r));
308 }
309 for (int ms = 0; ms < 500; ++ms) {
310 const PauseReason r = pause_reason(false, prod_groups, gates, 0, test_met);
311 CHECK(r == PauseReason::matching_producer && !gate.advance(1'000, r));
312 }
313 CHECK(gate.elapsed_us == 0 && gate.total_paused_us == 110'500'000ull);
314
315 // (b) Same gate with a matching producer stuck behind an untracked title fence wait: expires at 300.2 s!
316 GateTimeoutState stuck_gate;
317 stuck_gate.reset(200'000, full_caps.active_us, full_caps.max_us);
318 int expired_at_ms = -1;
319 for (int ms = 1; ms <= 305'000; ++ms) {
320 const PauseReason r = pause_reason(false, prod_groups, gates, 0, test_met);
321 if (stuck_gate.advance(1'000, r)) {
322 expired_at_ms = ms;
323 break;
324 }
325 }
326 CHECK(expired_at_ms == 300'200);
327
328 // (c) Demoted gate (4 ms budget) with continuous unrelated GPU work on q2: expires at 8 ms!
329 const PendingWrite unrelated[] = {{0xA000, 1, 8, false}};
330 const PendingWriteGroup unrel_groups[] = {{q2, 0, unrelated}};
331 GateTimeoutState dem_gate;
332 const PauseCaps dem_caps = default_pause_caps(4, true);
333 dem_gate.reset(4'000, dem_caps.active_us, dem_caps.max_us);
334 int dem_expired_ms = -1;
335 for (int ms = 1; ms <= 100; ++ms) {
336 const PauseReason r = pause_reason(false, unrel_groups, gates, 0, test_met);
337 CHECK(r == PauseReason::active_work);
338 if (dem_gate.advance(1'000, r)) {
339 dem_expired_ms = ms;
340 break;
341 }
342 }
343 CHECK(dem_expired_ms == 8);
344 }
345
346 std::printf("list_value_wait_budget_test: all checks passed\n");
347 return 0;
348}
diff --git a/runtime/test/shaders/cs_address_guard.asm b/runtime/test/shaders/cs_address_guard.asm
new file mode 100644
index 000000000..fad068a66
--- /dev/null
+++ b/runtime/test/shaders/cs_address_guard.asm
@@ -0,0 +1,57 @@
1; group: 1,1,1
2; rsrc2: 0x8090
3; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm
4; The address guard (rdna2spirv.py --address-guard; docs/d3d12_vulkan.md, "Address guard"). Translated with the guard,
5; run by scripts/run_address_guard_gpu_test.py on a 2 MiB heap whose page table (built by that script) backs the
6; arena (offsets below 0x80000, the header's limit) and the one 4 KiB page at 0x90000, and nothing else. The heap's
7; real memory continues past both, so every address below is inside the buffer: with the guard off the same program
8; reads and writes it, with the guard on the page table refuses the accesses outside 0x90000..0x90fff. Seeds:
9; 0x90000 0xa11ce000 0x90004 0xa11ce004 0x90ffc 0xf00df00d 0x91000 0xf00df00e
10; 0xa0000 0xbadbad00 0xa0004 0xbadbad04 0xa0008 0xbadbad08
11; Words stored to out[0..7] with the guard on (off: the second value):
12; out[0] global_load_dword at 0x90000, a backed page outside the arena = 0xa11ce000 (0xa11ce000)
13; out[1] global_load_dword at 0xa0000, unbacked = 0 (0xbadbad00)
14; out[2] global_atomic_add glc at 0xa0008 with 1, unbacked: the old value = 0 (0xbadbad08)
15; out[3] global_load_dwordx2 at 0x90ffc: its last byte is on an unbacked page, so all of it is refused
16; = 0 (0xf00df00d)
17; out[4] its second dword = 0 (0xf00df00e)
18; out[5] buffer_load_dword through a V# built in SGPRs, base 0xa0000 = 0 (0xbadbad00)
19; out[6] s_load_dword at 0x90004, backed = 0xa11ce004 (0xa11ce004)
20; out[7] s_load_dword at 0xa0000, unbacked = 0 (0xbadbad00)
21; global_store_dword 0x5707 at 0xa0004 (unbacked) goes to the dump area (0x78004) instead, and the atomic to 0x78008;
22; the six refused accesses count themselves at header + 24 (0x70018) and the last one's offset is at 0x70020.
23; Run: VKC_HEAP_INIT=<heap> VKC_OUT_WORDS=524288 VKC_DUMP=<file> vk_compute_test cs_address_guard.spv 1 dump
24v_mov_b32_e32 v0, 0x90000
25v_mov_b32_e32 v1, 0
26global_load_dword v2, v[0:1], off
27v_mov_b32_e32 v0, 0xa0000
28global_load_dword v3, v[0:1], off
29v_mov_b32_e32 v4, 0x5707
30global_store_dword v[0:1], v4, off offset:4
31v_mov_b32_e32 v5, 1
32global_atomic_add v5, v[0:1], v5, off offset:8 glc
33v_mov_b32_e32 v0, 0x90ffc
34global_load_dwordx2 v[6:7], v[0:1], off
35s_mov_b32 s4, 0xa0000
36s_mov_b32 s5, 0
37s_mov_b32 s6, 0x100
38s_mov_b32 s7, 0x31016fac
39v_mov_b32_e32 v8, 0
40buffer_load_dword v8, v8, s[4:7], 0 offen
41s_mov_b32 s8, 0x90000
42s_mov_b32 s9, 0
43s_load_dword s10, s[8:9], 0x4
44s_load_dword s11, s[4:5], 0x0
45s_waitcnt vmcnt(0) lgkmcnt(0)
46v_mov_b32_e32 v9, 0
47buffer_store_dword v2, v9, s[0:3], 0 offen
48buffer_store_dword v3, v9, s[0:3], 0 offen offset:4
49buffer_store_dword v5, v9, s[0:3], 0 offen offset:8
50buffer_store_dword v6, v9, s[0:3], 0 offen offset:12
51buffer_store_dword v7, v9, s[0:3], 0 offen offset:16
52buffer_store_dword v8, v9, s[0:3], 0 offen offset:20
53v_mov_b32_e32 v10, s10
54buffer_store_dword v10, v9, s[0:3], 0 offen offset:24
55v_mov_b32_e32 v11, s11
56buffer_store_dword v11, v9, s[0:3], 0 offen offset:28
57s_endpgm
diff --git a/runtime/test/title_memory_map_test.cpp b/runtime/test/title_memory_map_test.cpp
index ba5a518a1..ff226d648 100644
--- a/runtime/test/title_memory_map_test.cpp
+++ b/runtime/test/title_memory_map_test.cpp
@@ -7,7 +7,8 @@
7// 3. a reader further behind than the journal holds is told so (it then looks at everything); 7// 3. a reader further behind than the journal holds is told so (it then looks at everything);
8// 4. a change with no range overlaps every reader; 8// 4. a change with no range overlaps every reader;
9// 5. TextureReadability keeps a positive answer, when asked to, until a retry; 9// 5. TextureReadability keeps a positive answer, when asked to, until a retry;
10// 6. a pass over 20,000 waiting textures probes only those under the one mapped block. 10// 6. a pass over 20,000 waiting textures probes only those under the one mapped block;
11// 7. between passes, sync_map retries only when a map change overlaps the texture's footprint.
11#include <windows.h> 12#include <windows.h>
12 13
13#include <cstdint> 14#include <cstdint>
@@ -142,6 +143,48 @@ int main() {
142 check(pass() == 4 && probes == 0, "a pass with no change probes nothing"); 143 check(pass() == 4 && probes == 0, "a pass with no change probes nothing");
143 } 144 }
144 145
146 // 7. Synchronous view checks between passes (sync_map): unrelated map changes cost no probe, an overlapping unmap
147 // defers without reading, and an overlapping map wakes a waiting texture before the next pass.
148 {
149 constexpr std::uintptr_t cpu = kBase + 0x20000000;
150 constexpr std::uint64_t size = 512 * 1024;
151 const std::uint64_t pass_generation = map::generation();
152 bool mapped = true;
153 unsigned probes = 0;
154 leonida::TextureReadability r;
155 const auto probe = [&] {
156 ++probes;
157 return mapped;
158 };
159 check(r.check(0, true, probe, true) && probes == 1 && !r.pending(),
160 "sync_map: initial probe caches a readable answer");
161 for (std::uintptr_t i = 0; i < 32; ++i)
162 map::changed(cpu + size + i * 0x10000, cpu + size + (i + 1) * 0x10000);
163 r.sync_map(pass_generation, cpu, size);
164 check(r.check(0, true, probe, true) && probes == 1,
165 "sync_map: map changes outside the footprint keep the cached answer");
166 r.sync_map(pass_generation, cpu, size);
167 check(r.check(0, true, probe, true) && probes == 1,
168 "sync_map: a second check at the same generation does nothing");
169
170 mapped = false;
171 map::changed(cpu + 0x10000, cpu + 0x20000);
172 r.sync_map(pass_generation, cpu, size);
173 check(!r.check(0, true, probe, true) && r.pending() && probes == 2,
174 "sync_map: an overlapping unmap between passes reprobes and defers");
175
176 map::changed(cpu - 0x10000, cpu);
177 r.sync_map(pass_generation, cpu, size);
178 check(!r.check(0, true, probe, true) && r.pending() && probes == 2,
179 "sync_map: an adjacent non-overlapping change leaves a pending texture waiting");
180
181 mapped = true;
182 map::changed(cpu, cpu + size);
183 r.sync_map(pass_generation, cpu, size);
184 check(r.check(0, true, probe, true) && !r.pending() && probes == 3,
185 "sync_map: an overlapping map between passes wakes a pending texture at once");
186 }
187
145 std::printf("%d checks, %d failures\n", g_checks, g_failures); 188 std::printf("%d checks, %d failures\n", g_checks, g_failures);
146 return g_failures ? 1 : 0; 189 return g_failures ? 1 : 0;
147} 190}
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index eb1be0a2c..8369d594c 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -123,6 +123,7 @@ public:
123 bool occlusion_query_precise = false; // occlusionQueryPrecise enabled 123 bool occlusion_query_precise = false; // occlusionQueryPrecise enabled
124 bool prepare_on_bind=false; 124 bool prepare_on_bind=false;
125 bool cold_graphics_compile = false; 125 bool cold_graphics_compile = false;
126 bool heavy_pipeline_cache = false; // LEONIDA_HEAVY_PIPELINE_CACHE_MS set and pipelineCreationCacheControl on
126 bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled 127 bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled
127 bool request_multi_draw_indirect = false, request_draw_indirect_count = false; 128 bool request_multi_draw_indirect = false, request_draw_indirect_count = false;
128 bool draw_indirect_count_enabled = false; 129 bool draw_indirect_count_enabled = false;
@@ -412,8 +413,13 @@ private:
412 // (zero-based VS ids) is in; harmless before. 413 // (zero-based VS ids) is in; harmless before.
413 const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); 414 const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE");
414 const bool cache_only = compile_mode && std::strcmp(compile_mode, "cache-only") == 0; 415 const bool cache_only = compile_mode && std::strcmp(compile_mode, "cache-only") == 0;
415 v13_.enable_pipeline_cache_control = cache_only && v13_.core && v13_.pipeline_cache_control; 416 // LEONIDA_HEAVY_PIPELINE_CACHE_MS other than 0: the heavy pipeline cache path, as the runtime takes it by default
416 cold_graphics_compile = v13_.enable_pipeline_cache_control; 417 // (src/heavy_pipeline_cache.h). Tests leave it off unless asked.
418 const char* heavy_ms = std::getenv("LEONIDA_HEAVY_PIPELINE_CACHE_MS");
419 const bool heavy = heavy_ms && *heavy_ms && std::strcmp(heavy_ms, "0") != 0;
420 v13_.enable_pipeline_cache_control = (cache_only || heavy) && v13_.core && v13_.pipeline_cache_control;
421 cold_graphics_compile = cache_only && v13_.enable_pipeline_cache_control;
422 heavy_pipeline_cache = heavy && v13_.enable_pipeline_cache_control;
417 prepare_on_bind = compile_mode && std::strcmp(compile_mode, "on-demand") == 0; 423 prepare_on_bind = compile_mode && std::strcmp(compile_mode, "on-demand") == 0;
418 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, 424 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES,
419 v13_.enable(conditional_rendering ? &enable_conditional : nullptr)}; 425 v13_.enable(conditional_rendering ? &enable_conditional : nullptr)};
diff --git a/runtime/test/xapu_chad_test.cpp b/runtime/test/xapu_chad_test.cpp
index dffa74404..7e667492c 100644
--- a/runtime/test/xapu_chad_test.cpp
+++ b/runtime/test/xapu_chad_test.cpp
@@ -1,7 +1,11 @@
1// Checks the registered xapu.dll and chad.dll shims in the call shapes the executable uses (runtime/shims/xapu_chad.cpp): 1// Checks the registered xapu.dll and chad.dll shims (runtime/shims/xapu_queue.cpp and runtime/shims/xapu_chad.cpp)
2// the connections succeed, the APU's shared buffer is zeroed and writable at the offsets the title reaches, commands 2// in the call shapes the executable uses and against the layouts xapu_queue.cpp documents.
3// are accepted, an open and a close each give one result and nothing else does, XDspActivate hands out zeroed status 3//
4// and stream memory, and both disconnect. 4// xapu.dll: the connection's limits and its zeroed memory, writable at the offsets the title reaches; one result per
5// accepted command, in command order, with its id echoed; the per-stream queue limit; the error codes, returned or in
6// the result; a process command's frame count taken from the Opus packet's table-of-contents byte (RFC 6716, section
7// 3.1) and clipped, with silence written; and the result event. The packets are hand-made TOC bytes, not audio.
8// chad.dll: XDspActivate hands out zeroed status and stream memory, and both disconnect.
5#include <windows.h> 9#include <windows.h>
6 10
7#include <cstdint> 11#include <cstdint>
@@ -12,10 +16,10 @@
12 16
13namespace { 17namespace {
14 18
15using XApuConnectFn = HRESULT(__stdcall*)(void*, void*, void**); 19using XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**);
16using XApuDisconnectFn = HRESULT(__stdcall*)(void*); 20using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t);
17using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const uint32_t*, uint64_t); 21using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*);
18using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint64_t); 22using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*);
19using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); 23using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*);
20using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**); 24using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**);
21using XDspActivateFn = HRESULT(__stdcall*)(void*, const void*, void**, void**); 25using XDspActivateFn = HRESULT(__stdcall*)(void*, const void*, void**, void**);
@@ -23,6 +27,55 @@ using XDspDeactivateFn = HRESULT(__stdcall*)(void*, uint64_t, uint64_t, uint64_t
23using XDspDisconnectFn = HRESULT(__stdcall*)(void*); 27using XDspDisconnectFn = HRESULT(__stdcall*)(void*);
24using XDspSubmitCommandFn = HRESULT(__stdcall*)(void*, void*, uint32_t*); 28using XDspSubmitCommandFn = HRESULT(__stdcall*)(void*, void*, uint32_t*);
25 29
30constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u);
31constexpr HRESULT kNoResult = static_cast<HRESULT>(0x8AC81001u);
32constexpr HRESULT kInvalidCommand = static_cast<HRESULT>(0x8AC81002u);
33constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u);
34constexpr HRESULT kAlreadyActive = static_cast<HRESULT>(0x8AC81005u);
35constexpr HRESULT kBadPacket = static_cast<HRESULT>(0x8AC81008u);
36
37#pragma pack(push, 1)
38struct ConnectInput {
39 uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options;
40};
41struct ConnectOutput {
42 void* memory;
43 HANDLE result_event;
44};
45struct CommandId {
46 uint32_t kind, stream, sequence, options;
47 uint64_t context;
48};
49struct ActivateCommand {
50 CommandId id;
51 uint32_t channels, init_bytes;
52 const void* init;
53 float start_pitch;
54 uint32_t processing_bytes;
55 void* processing;
56};
57struct ProcessCommand {
58 CommandId id;
59 float pitch_ramp, target_pitch;
60 uint32_t first_frame, frame_count, input_bytes;
61 const uint8_t* input;
62 uint32_t output_bytes;
63 uint8_t* output;
64};
65struct Result {
66 CommandId id;
67 uint32_t state;
68 uint64_t state_data, usec;
69 HRESULT error;
70 uint32_t frames, output_bytes;
71 uint8_t* output;
72 float pitch;
73 uint32_t input_bytes;
74 const uint8_t* input;
75};
76#pragma pack(pop)
77static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts");
78
26int g_checks = 0; 79int g_checks = 0;
27int g_failures = 0; 80int g_failures = 0;
28 81
@@ -39,6 +92,8 @@ T get(const char* dll, const char* name) {
39 return reinterpret_cast<T>(fn); 92 return reinterpret_cast<T>(fn);
40} 93}
41 94
95CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; }
96
42} // namespace 97} // namespace
43 98
44int main() { 99int main() {
@@ -56,39 +111,165 @@ int main() {
56 check(rt::shims::owns_dll("xapu.dll") && rt::shims::owns_dll("chad.dll"), "the shims own xapu.dll and chad.dll"); 111 check(rt::shims::owns_dll("xapu.dll") && rt::shims::owns_dll("chad.dll"), "the shims own xapu.dll and chad.dll");
57 if (g_failures) return 1; 112 if (g_failures) return 1;
58 113
59 // XApuConnect(block24*, out16*, handle*), success read as SUCCEEDED. 114 // XApuConnect(const ConnectInput*, ConnectOutput*, handle*): the first argument is read, never written.
60 uint8_t out24[24]; 115 ConnectOutput out{};
61 uint64_t out16[2] = {};
62 std::memset(out24, 0xcc, sizeof out24);
63 void* apu = nullptr; 116 void* apu = nullptr;
64 check(SUCCEEDED(connect(out24, out16, &apu)) && apu, "XApuConnect succeeds with a handle"); 117 ConnectInput bad{1, 0, 2, 0x10000, 0, 0};
65 check(out24[0] == 0xcc && out24[23] == 0xcc, "XApuConnect leaves the title's 24-byte block alone"); 118 check(connect(&bad, &out, &apu) == E_INVALIDARG, "zero streams is E_INVALIDARG");
66 auto* base = reinterpret_cast<uint8_t*>(out16[0]); 119 bad = {1, 501, 2, 0x10000, 0, 0};
67 check(base != nullptr && out16[1] >= 0x14000 + 128 * 0x1E00, "XApuConnect returns the shared buffer and its size"); 120 check(connect(&bad, &out, &apu) == E_INVALIDARG, "more than 500 streams is E_INVALIDARG");
68 if (base) { 121 bad = {1, 4, 17, 0x10000, 0, 0};
69 const size_t last_output = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; // the end of slot 127's output 122 check(connect(&bad, &out, &apu) == E_INVALIDARG, "more than 16 commands per stream is E_INVALIDARG");
70 check(base[0] == 0 && base[last_output] == 0, "the shared buffer is zeroed"); 123 bad = {1, 4, 2, 0, 0, 0};
71 base[127 * 0x280] = 1; 124 check(connect(&bad, &out, &apu) == E_INVALIDARG, "no memory is E_INVALIDARG");
72 base[last_output] = 1; 125 bad = {1, 4, 2, 0x10000, 256, 0};
73 check(base[127 * 0x280] == 1 && base[last_output] == 1, "the shared buffer is writable at slot 127"); 126 check(connect(&bad, &out, &apu) == E_INVALIDARG, "frames per output for decoding is E_INVALIDARG");
74 } 127 bad = {2, 4, 2, 0x10000, 0, 0};
75 check(connect(out24, out16, nullptr) == E_INVALIDARG, "XApuConnect without a handle pointer fails"); 128 check(connect(&bad, &out, &apu) == static_cast<HRESULT>(rt::shims::kENotImpl),
129 "a processing kind other than Opus decoding is E_NOTIMPL");
130 check(apu == nullptr, "a failed XApuConnect hands out no handle");
131
132 // The memory the title addresses: input at base + slot * 0x280, output at base + 0x14000 + slot * 0x1E00.
133 constexpr uint32_t kMemory = 0x14000 + 128 * 0x1E00;
134 const ConnectInput in{1, 128, 2, kMemory, 0, 8};
135 const ConnectInput in_copy = in;
136 check(SUCCEEDED(connect(&in, &out, &apu)) && apu, "XApuConnect for Opus decoding, 128 streams, 2 commands each");
137 check(std::memcmp(&in, &in_copy, sizeof in) == 0, "XApuConnect leaves its input alone");
138 check(out.memory != nullptr && out.result_event != nullptr, "it hands out memory and a result event");
139 if (!apu || !out.memory) return 1;
140 auto* base = static_cast<uint8_t*>(out.memory);
141 const size_t last_output = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; // the end of slot 127's output
142 check(base[0] == 0 && base[last_output] == 0, "the memory is zeroed");
143 base[127 * 0x280] = 1;
144 base[last_output] = 1;
145 check(base[127 * 0x280] == 1 && base[last_output] == 1, "the memory is writable at slot 127");
146 base[127 * 0x280] = 0;
147 base[last_output] = 0;
148
149 Result r{};
150 check(dequeue(apu, &r) == kNoResult, "XApuDequeueResult with nothing queued is 0x8AC81001");
151 uint32_t dequeued = 99;
152 check(count(apu, &dequeued) == 0 && dequeued == 0, "XApuGetResultCount: nothing ready, none dequeued");
76 153
77 // Command types 1, 2 and 3 as the title builds them; the third argument is 0 at every site. 154 // Activate stream 3 (stereo) and process one packet; the title's sites pass a null third argument.
78 for (uint32_t type = 1; type <= 3; ++type) { 155 const ActivateCommand activate{id(1, 3), 2, 0, nullptr, 1.0f, 0, nullptr};
79 uint32_t command[16] = {type, 5}; 156 check(enqueue(apu, &activate, nullptr) == S_OK, "activate stream 3 with a null count pointer");
80 check(enqueue(apu, command, 0) == S_OK, "XApuEnqueueCommand accepts a command"); 157 check(WaitForSingleObject(out.result_event, 0) == WAIT_TIMEOUT, "a command not asking for it leaves the event");
158 uint8_t* const packet = base + 3 * 0x280;
159 uint8_t* const pcm = base + 0x14000 + 3 * 0x1E00;
160 packet[0] = (31 << 3) | 0; // one 20 ms CELT frame (config 31, code 0): 960 frames per channel
161 std::memset(pcm, 0x55, 0x1E00 + 16); // the slot and the start of the next, to see nothing past it is written
162 ProcessCommand process{id(3, 3, 1), 0.0f, 1.0f, 0, 960, 40, packet, 960 * 8, pcm};
163 uint32_t total = 0;
164 check(enqueue(apu, &process, &total) == S_OK && total == 2, "process on stream 3; two commands accepted");
165 check(WaitForSingleObject(out.result_event, 0) == WAIT_OBJECT_0, "a command asking for it signals the event");
166 check(WaitForSingleObject(out.result_event, 0) == WAIT_TIMEOUT, "the event resets itself");
167 check(enqueue(apu, &process, &total) == kQueueFull && total == 2,
168 "a third command on a stream of two is 0x8AC81000 and not counted");
169 check(count(apu, nullptr) == 2, "two results ready, with a null dequeued pointer");
170
171 check(dequeue(apu, &r) == S_OK && r.id.kind == 1 && r.id.stream == 3 && r.id.sequence == 7 &&
172 r.id.context == 0x1234 && r.error == S_OK && r.pitch == 1.0f,
173 "results come in command order: the activate first, its id echoed");
174 check(dequeue(apu, &r) == S_OK && r.id.kind == 3 && r.error == S_OK, "the process result follows");
175 uint32_t dword34 = 0;
176 std::memcpy(&dword34, reinterpret_cast<const uint8_t*>(&r) + 0x34, 4);
177 check(r.frames == 960 && dword34 == 960 * 8 && r.output == pcm && r.input == packet && r.input_bytes == 40,
178 "960 stereo float frames, the byte count at +0x34, the buffers echoed");
179 bool silent = true;
180 for (int i = 0; i < 960 * 8; ++i) silent = silent && pcm[i] == 0;
181 check(silent && pcm[960 * 8] == 0x55, "the output range is silence, and nothing past it is written");
182 check(count(apu, &dequeued) == 0 && dequeued == 2, "nothing ready, two dequeued");
183
184 // The TOC byte's frame size and count (RFC 6716, section 3.1), one stereo packet each.
185 struct Toc {
186 uint8_t toc, count;
187 uint32_t frames;
188 const char* what;
189 } const tocs[] = {
190 {(0 << 3) | 0, 0, 480, "SILK 10 ms, code 0: 480 frames"},
191 {(3 << 3) | 1, 0, 5760, "SILK 60 ms, code 1 (two frames): 5760 frames"},
192 {(13 << 3) | 2, 0, 1920, "hybrid 20 ms, code 2 (two frames): 1920 frames"},
193 {(16 << 3) | 3, 5, 600, "CELT 2.5 ms, code 3 with five frames: 600 frames"},
194 };
195 for (const Toc& t : tocs) {
196 packet[0] = t.toc;
197 packet[1] = t.count;
198 process = {id(3, 3), 0.0f, 1.0f, 0, 6000, 40, packet, 0x1E00 * 4, pcm};
199 r = {};
200 check(enqueue(apu, &process, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK &&
201 r.frames == (t.frames < 0x1E00 * 4 / 8 ? t.frames : 0x1E00 * 4 / 8),
202 t.what);
81 } 203 }
82 check(count(apu, 0) == 2, "the open and the close each queued a result, the type 3 command none"); 204
83 for (uint32_t type = 1; type <= 2; ++type) { 205 // first_frame and frame_count clip like a decode: three 20 ms frames (code 3, count 3) = 2880, from frame 2000.
84 uint32_t queued[0x50 / 4] = {}; 206 packet[0] = (31 << 3) | 3;
85 check(dequeue(apu, queued) == S_OK && queued[0] == type && queued[1] == 5 && queued[2] == 0 && queued[13] == 0, 207 packet[1] = 3;
86 "XApuDequeueResult returns the type and slot and leaves the rest zeroed"); 208 process = {id(3, 3), 0.0f, 1.0f, 2000, 4000, 40, packet, 0x1E00, pcm};
209 enqueue(apu, &process, nullptr);
210 dequeue(apu, &r);
211 check(r.error == S_OK && r.frames == 880 && r.output_bytes == 880 * 8, "frames from first_frame to the packet's end");
212 process.frame_count = 300;
213 enqueue(apu, &process, nullptr);
214 dequeue(apu, &r);
215 check(r.frames == 300, "no more than frame_count");
216 process.frame_count = 4000;
217 process.output_bytes = 100 * 8 + 7;
218 enqueue(apu, &process, nullptr);
219 dequeue(apu, &r);
220 check(r.frames == 100 && r.output_bytes == 800, "and no more than the output holds");
221
222 // Errors carried in the result: the command is accepted and its result says what went wrong.
223 packet[1] = 7; // seven 20 ms frames: 140 ms, longer than an Opus packet may be
224 enqueue(apu, &process, nullptr);
225 dequeue(apu, &r);
226 check(r.error == kBadPacket && r.frames == 0, "an impossible packet: 0x8AC81008 in the result");
227 packet[0] = (31 << 3) | 3;
228 packet[1] = 0;
229 enqueue(apu, &process, nullptr);
230 dequeue(apu, &r);
231 check(r.error == kBadPacket, "a code 3 packet of zero frames: 0x8AC81008");
232 ProcessCommand empty = process;
233 empty.input_bytes = 0;
234 check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG,
235 "an empty input: E_INVALIDARG in the result");
236 empty = process;
237 empty.output = nullptr;
238 check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG,
239 "a null output: E_INVALIDARG in the result");
240 ProcessCommand stray = process;
241 stray.id.stream = 4;
242 check(enqueue(apu, &stray, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream,
243 "a process on a stream never activated: 0x8AC81003 in the result");
244 check(enqueue(apu, &activate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kAlreadyActive,
245 "activating an active stream: 0x8AC81005 in the result");
246 ActivateCommand surround = activate;
247 surround.id.stream = 5;
248 surround.channels = 6;
249 check(enqueue(apu, &surround, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG,
250 "six channels: E_INVALIDARG in the result");
251
252 // Errors returned at once, with no result.
253 stray.id.stream = 128;
254 check(enqueue(apu, &stray, nullptr) == kInvalidStream, "a stream past the connection's is 0x8AC81003");
255 const CommandId unknown = id(9, 3);
256 check(enqueue(apu, &unknown, nullptr) == kInvalidCommand, "an unknown kind is 0x8AC81002");
257 check(count(apu, nullptr) == 0, "neither left a result");
258
259 // Notify and reset give a result; deactivate gives one and closes the stream.
260 for (uint32_t kind : {4u, 5u, 2u}) {
261 const CommandId command = id(kind, 3);
262 check(enqueue(apu, &command, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.id.kind == kind &&
263 r.id.stream == 3 && r.error == S_OK,
264 "notify, reset and deactivate each give a result of their kind for their stream");
87 } 265 }
88 check(count(apu, 0) == 0, "XApuGetResultCount is 0 again"); 266 process.id.stream = 3;
89 uint8_t result[0x50] = {}; 267 enqueue(apu, &process, nullptr);
90 check(FAILED(dequeue(apu, result)), "XApuDequeueResult on the empty queue fails"); 268 dequeue(apu, &r);
91 check(disconnect(apu) == S_OK, "XApuDisconnect succeeds"); 269 check(r.error == kInvalidStream, "after deactivate the stream takes no process command");
270 check(enqueue(apu, &activate, &total) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK,
271 "and it can be activated again");
272 check(disconnect(apu, 0x20) == S_OK, "XApuDisconnect(handle, 0x20)");
92 273
93 // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*), success read as a return of 0. 274 // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*), success read as a return of 0.
94 alignas(64) static uint8_t dsp_buffer[4096]; 275 alignas(64) static uint8_t dsp_buffer[4096];
@@ -99,10 +280,10 @@ int main() {
99 void* stream = nullptr; 280 void* stream = nullptr;
100 check(dsp_activate(dsp, description, reinterpret_cast<void**>(&status), &stream) == 0, "XDspActivate returns 0"); 281 check(dsp_activate(dsp, description, reinterpret_cast<void**>(&status), &stream) == 0, "XDspActivate returns 0");
101 check(status && stream && static_cast<void*>(status) != stream, "XDspActivate writes both outputs"); 282 check(status && stream && static_cast<void*>(status) != stream, "XDspActivate writes both outputs");
102 uint32_t id = 0; 283 uint32_t dsp_id = 0;
103 check(dsp_submit(stream, dsp_buffer, &id) == 0, "XDspSubmitCommand returns 0"); 284 check(dsp_submit(stream, dsp_buffer, &dsp_id) == 0, "XDspSubmitCommand returns 0");
104 // What the title's wait reads: no error at +0xc and the submitted id at +4. 285 // What the title's wait reads: no error at +0xc and the submitted id at +4.
105 check(status && status[3] == 0 && status[1] == id, "the status block reports the submitted command as done"); 286 check(status && status[3] == 0 && status[1] == dsp_id, "the status block reports the submitted command as done");
106 check(dsp_deactivate(dsp, 0, 0, 0) == 0, "XDspDeactivate returns 0"); 287 check(dsp_deactivate(dsp, 0, 0, 0) == 0, "XDspDeactivate returns 0");
107 check(dsp_disconnect(dsp) == 0, "XDspDisconnect returns 0"); 288 check(dsp_disconnect(dsp) == 0, "XDspDisconnect returns 0");
108 289
diff --git a/runtime/test/xapu_opus_test.cpp b/runtime/test/xapu_opus_test.cpp
new file mode 100644
index 000000000..30eb33cfe
--- /dev/null
+++ b/runtime/test/xapu_opus_test.cpp
@@ -0,0 +1,193 @@
1// Checks the decoded path of the registered xapu.dll shim (runtime/shims/xapu_queue.cpp) with
2// runtime/opus_decoder built: the title's ConnectInput, activate/process/deactivate, one result per
3// command in order, the 0x50-byte result layout, and a generated 440 Hz stereo packet decoded to
4// 960 frames of f32 PCM, then clipped by first_frame / frame_count / output_bytes. The packet is
5// encoded here; no game data.
6#include <windows.h>
7
8#include <cmath>
9#include <cstdint>
10#include <cstdio>
11#include <cstring>
12#include <vector>
13
14#include "leonida_opus_decoder.h"
15#include "shims.h"
16
17namespace {
18
19using XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**);
20using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t);
21using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*);
22using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*);
23using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*);
24
25constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u);
26constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u);
27
28#pragma pack(push, 1)
29struct ConnectInput {
30 uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options;
31};
32struct ConnectOutput {
33 void* memory;
34 HANDLE result_event;
35};
36struct CommandId {
37 uint32_t kind, stream, sequence, options;
38 uint64_t context;
39};
40struct ActivateCommand {
41 CommandId id;
42 uint32_t channels, init_bytes;
43 const void* init;
44 float start_pitch;
45 uint32_t processing_bytes;
46 void* processing;
47};
48struct ProcessCommand {
49 CommandId id;
50 float pitch_ramp, target_pitch;
51 uint32_t first_frame, frame_count, input_bytes;
52 const uint8_t* input;
53 uint32_t output_bytes;
54 uint8_t* output;
55};
56struct Result {
57 CommandId id;
58 uint32_t state;
59 uint64_t state_data, usec;
60 HRESULT error;
61 uint32_t frames, output_bytes;
62 uint8_t* output;
63 float pitch;
64 uint32_t input_bytes;
65 const uint8_t* input;
66};
67#pragma pack(pop)
68static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts");
69
70int g_checks = 0;
71int g_failures = 0;
72
73void check(bool condition, const char* what) {
74 ++g_checks;
75 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
76 if (!condition) ++g_failures;
77}
78
79template <typename T>
80T get(const char* dll, const char* name) {
81 void* fn = rt::shims::find(dll, name);
82 check(fn != nullptr, name);
83 return reinterpret_cast<T>(fn);
84}
85
86CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; }
87
88} // namespace
89
90int main() {
91 std::printf("xapu_opus_test: decoded xapu.dll path\n");
92 const auto connect = get<XApuConnectFn>("xapu.dll", "XApuConnect");
93 const auto disconnect = get<XApuDisconnectFn>("xapu.dll", "XApuDisconnect");
94 const auto enqueue = get<XApuEnqueueCommandFn>("xapu.dll", "XApuEnqueueCommand");
95 const auto count = get<XApuGetResultCountFn>("xapu.dll", "XApuGetResultCount");
96 const auto dequeue = get<XApuDequeueResultFn>("xapu.dll", "XApuDequeueResult");
97 if (g_failures) return 1;
98
99 constexpr uint32_t kMemory = 0x14000 + 128 * 0x1E00;
100 const ConnectInput in{1, 128, 2, kMemory, 0, 0};
101 const ConnectInput in_copy = in;
102 ConnectOutput out{};
103 void* apu = nullptr;
104 check(SUCCEEDED(connect(&in, &out, &apu)) && apu, "XApuConnect for Opus decoding");
105 check(std::memcmp(&in, &in_copy, sizeof in) == 0, "XApuConnect leaves its input alone");
106 auto* base = static_cast<uint8_t*>(out.memory);
107 if (!apu || !base) return 1;
108 check(base[0] == 0 && base[kMemory - 1] == 0, "the shared memory is zeroed");
109
110 const ActivateCommand activate{id(1, 3), 2, 0, nullptr, 1.0f, 0, nullptr};
111 check(enqueue(apu, &activate, nullptr) == S_OK, "activate stream 3 (stereo)");
112
113 std::vector<float> tone(960 * 2);
114 for (uint32_t i = 0; i < 960; ++i) {
115 const float sample = static_cast<float>(std::sin(double(i) * 440.0 * 6.283185307179586 / 48000.0)) * 0.5f;
116 tone[2 * i] = sample;
117 tone[2 * i + 1] = sample;
118 }
119 uint8_t encoded[1500];
120 size_t encoded_len = 0;
121 check(leonida_opus_encode_test(tone.data(), 960, 2, encoded, sizeof encoded, &encoded_len) == LEONIDA_OPUS_OK &&
122 encoded_len > 0,
123 "a synthetic 20 ms stereo Opus packet encodes");
124 std::memcpy(base, encoded, encoded_len);
125 auto* const pcm = base + 0x14000 + 3 * 0x1E00;
126 std::memset(pcm, 0x55, 0x1E00 + 64);
127 ProcessCommand process{id(3, 3, 1), 0.0f, 1.0f, 0, 960, static_cast<uint32_t>(encoded_len), base, 0x1E00, pcm};
128 uint32_t total = 0;
129 check(enqueue(apu, &process, &total) == S_OK && total == 2, "process on stream 3; two commands accepted");
130 check(enqueue(apu, &process, &total) == kQueueFull && total == 2,
131 "a third command on a stream of two is 0x8AC81000");
132 check(count(apu, nullptr) == 2, "two results ready");
133
134 Result r{};
135 check(dequeue(apu, &r) == S_OK && r.id.kind == 1 && r.id.stream == 3 && r.error == S_OK,
136 "results come in command order: the activate first");
137 check(dequeue(apu, &r) == S_OK && r.id.kind == 3 && r.error == S_OK, "the process result follows");
138 uint32_t dword34 = 0;
139 std::memcpy(&dword34, reinterpret_cast<const uint8_t*>(&r) + 0x34, 4);
140 check(r.frames == 960 && dword34 == 960 * 8 && r.output == pcm && r.input == base &&
141 r.input_bytes == static_cast<uint32_t>(encoded_len),
142 "960 stereo float frames, the byte count at +0x34, the buffers echoed");
143 float energy = 0.0f;
144 const auto* floats = reinterpret_cast<const float*>(pcm);
145 for (uint32_t i = 0; i < 960 * 2; ++i) energy += floats[i] * floats[i];
146 energy /= 960 * 2;
147 check(energy > 0.01f, "the decoded tone has energy");
148 check(pcm[960 * 8] == 0x55, "nothing past the decoded range is written");
149 check(count(apu, nullptr) == 0, "the queue is empty after both results");
150
151 // first_frame, frame_count and what output_bytes holds each clip the decoded frames.
152 process.first_frame = 500;
153 process.frame_count = 4000;
154 enqueue(apu, &process, nullptr);
155 dequeue(apu, &r);
156 check(r.error == S_OK && r.frames == 460 && r.output_bytes == 460 * 8, "frames from first_frame to the packet's end");
157 process.frame_count = 300;
158 enqueue(apu, &process, nullptr);
159 dequeue(apu, &r);
160 check(r.frames == 300 && r.output_bytes == 300 * 8, "no more than frame_count");
161 process.frame_count = 4000;
162 process.output_bytes = 100 * 8 + 7;
163 enqueue(apu, &process, nullptr);
164 dequeue(apu, &r);
165 check(r.frames == 100 && r.output_bytes == 800, "and no more than the output holds");
166
167 // Errors carried in the result.
168 ProcessCommand empty = process;
169 empty.input_bytes = 0;
170 check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG,
171 "an empty input: E_INVALIDARG in the result");
172 empty = process;
173 empty.output = nullptr;
174 check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG,
175 "a null output: E_INVALIDARG in the result");
176 ProcessCommand stray = process;
177 stray.id.stream = 4;
178 check(enqueue(apu, &stray, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream,
179 "a process on a stream never activated: 0x8AC81003 in the result");
180
181 // Deactivate closes the stream; activating again creates a fresh decoder.
182 const CommandId deactivate = id(2, 3);
183 check(enqueue(apu, &deactivate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK,
184 "deactivate gives a result and closes the stream");
185 check(enqueue(apu, &process, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream,
186 "after deactivate the stream takes no process command");
187 check(enqueue(apu, &activate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK,
188 "the stream can be activated again");
189 check(disconnect(apu, 0x20) == S_OK, "XApuDisconnect(handle, 0x20)");
190
191 std::printf("%d checks, %d failures\n", g_checks, g_failures);
192 return g_failures ? 1 : 0;
193}
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index 991388c7f..adc24cca3 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -31,6 +31,7 @@
31#include "startup_trace.h" 31#include "startup_trace.h"
32#include "xmem.h" 32#include "xmem.h"
33#include "../src/title_page_watch.h" 33#include "../src/title_page_watch.h"
34#include "../src/title_geometry_watch.h"
34 35
35// The process heap as test_heap_lock_faults needs it (the same gate as d3d12_existing_heap_test's): an allocation that 36// The process heap as test_heap_lock_faults needs it (the same gate as d3d12_existing_heap_test's): an allocation that
36// waits while a thread holds the heap's lock. The NT heap's low-fragmentation front end serves most small sizes 37// waits while a thread holds the heap's lock. The NT heap's low-fragmentation front end serves most small sizes
@@ -429,6 +430,78 @@ struct PhysicalApi {
429 XMemMapPhysicalPagesScatterFn scatter; 430 XMemMapPhysicalPagesScatterFn scatter;
430}; 431};
431 432
433// A remap that gives watched pages another frame reports them released (geometry_writes::note_released), so the
434// geometry copies of what they held are retired; a page mapped again to the frame it had is no change. Through
435// XMemMapPhysicalPages, the scatter call and CopyPageMappingsBatchX.
436void test_remap_releases(const PhysicalApi& api) {
437 namespace watch = leonida::geometry_writes;
438 constexpr uint64_t kPages = 3;
439 auto* const window = static_cast<uint8_t*>(api.virtual_alloc(
440 nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE));
441 uint64_t pages[4]{};
442 uint64_t count = 4;
443 if (!window || api.allocate(0x280, &count, pages) != TRUE || count != 4) {
444 check(false, "remap releases: a window and four physical pages");
445 return;
446 }
447 const auto base = reinterpret_cast<uintptr_t>(window);
448 watch::ReleaseQueue queue;
449 watch::subscribe(queue);
450 for (uint64_t i = 0; i < kPages; ++i) watch::acquire(base + i * kPage64k); // as a geometry copy over the pages
451 std::vector<std::pair<uintptr_t, uintptr_t>> released;
452 const auto take = [&] {
453 watch::take_released(queue, released);
454 return released;
455 };
456 const auto covers = [&](uintptr_t from, uintptr_t to) {
457 for (const auto& [lo, hi] : released)
458 if (lo <= from && hi >= to) return true;
459 return false;
460 };
461 const auto any_overlap = [&](uintptr_t from, uintptr_t to) {
462 for (const auto& [lo, hi] : released)
463 if (lo < to && hi > from) return true;
464 return false;
465 };
466
467 const uint64_t first[kPages] = {pages[0], pages[1], pages[2]};
468 check(api.map(window, kPages, first) == window && take().empty(),
469 "remap releases: a first mapping of unmapped pages releases nothing");
470 check(api.map(window + kPage64k, 1, &pages[1]) == window + kPage64k && take().empty(),
471 "remap releases: a page mapped again to the frame it has is no change");
472 check(api.map(window + kPage64k, 1, &pages[3]) == window + kPage64k && !take().empty() &&
473 covers(base + kPage64k, base + 2 * kPage64k) && !any_overlap(base, base + kPage64k) &&
474 !any_overlap(base + 2 * kPage64k, base + 3 * kPage64k),
475 "remap releases: a page given another frame is released, its neighbours are not");
476 const uint64_t rotated[kPages] = {pages[2], pages[0], pages[1]};
477 check(api.map(window, kPages, rotated) == window && !take().empty() && covers(base, base + 3 * kPage64k),
478 "remap releases: a run given other frames is released whole");
479 const uint64_t partly[kPages] = {pages[2], pages[3], pages[1]};
480 check(api.map(window, kPages, partly) == window && !take().empty() &&
481 covers(base + kPage64k, base + 2 * kPage64k) && !any_overlap(base, base + kPage64k) &&
482 !any_overlap(base + 2 * kPage64k, base + 3 * kPage64k),
483 "remap releases: of a remapped run, only the page whose frame changed is released");
484 void* const last = window + 2 * kPage64k;
485 check(api.scatter(&last, 1, &pages[0]) == TRUE && !take().empty() &&
486 covers(base + 2 * kPage64k, base + 3 * kPage64k) && !any_overlap(base, base + 2 * kPage64k),
487 "remap releases: the scatter call releases the page it gives another frame");
488 check(api.scatter(&last, 1, &pages[0]) == TRUE && take().empty(),
489 "remap releases: the scatter call with the frame the page has releases nothing");
490 // CopyPageMappingsBatchX: page 0 gets the frame at page 1 (kind 0 from a pool at the window itself).
491 const rt::xmem::PageRange range{0, 1, 1};
492 const rt::xmem::PageBatch batch{base, 1, &range};
493 check(rt::xmem::copy_page_mappings(1, &batch, base, kPages, 0) && !take().empty() &&
494 covers(base, base + kPage64k) && !any_overlap(base + kPage64k, base + 3 * kPage64k),
495 "remap releases: CopyPageMappingsBatchX releases the page it gives another frame");
496
497 check(api.map(window, kPages, nullptr) == window && !take().empty() && covers(base, base + 3 * kPage64k),
498 "remap releases: unmapping releases the range");
499 for (uint64_t i = 0; i < kPages; ++i) watch::release(base + i * kPage64k);
500 watch::unsubscribe(queue);
501 api.free_pages(4, pages);
502 VirtualFree(window, 0, MEM_RELEASE);
503}
504
432// Physical pages in a 64 KiB-page window, as the measured callers use them: reserve a window, allocate pages, map them, 505// Physical pages in a 64 KiB-page window, as the measured callers use them: reserve a window, allocate pages, map them,
433// remap them elsewhere and in another order, unmap, free. 506// remap them elsewhere and in another order, unmap, free.
434void test_physical_pages(const PhysicalApi& api) { 507void test_physical_pages(const PhysicalApi& api) {
@@ -741,7 +814,19 @@ void test_copy_page_mappings_cpu_view(const PhysicalApi& api) {
741 check(readable(other) && page_holds(other, 0x7300u), 814 check(readable(other) && page_holds(other, 0x7300u),
742 "a GPU-only source page unmapped there is looked up at its CPU range"); 815 "a GPU-only source page unmapped there is looked up at its CPU range");
743 816
744 // A null source unmaps both ranges. 817 // A CPU page the title mapped itself is the title's: a copy onto its GPU-only page, or an unmap of it, changes the
818 // GPU-only page alone (the console's CopyPageMappingsBatchX edits only that range's page table).
819 check(copy(gpu + 2 * kPage64k, pool + kPage64k, 1, false), "a copy onto a GPU-only page whose CPU page is the title's");
820 check(readable(gpu + 2 * kPage64k) && page_holds(gpu + 2 * kPage64k, 0x7301u),
821 "the GPU-only page shows the copied pool page");
822 check(readable(cpu + 2 * kPage64k) && page_holds(cpu + 2 * kPage64k, 0x7300u),
823 "the title's own mapping at the paired CPU page is kept, not replaced by the copy");
824 check(copy(gpu + 2 * kPage64k, nullptr, 1, false), "a null source unmaps a GPU-only page whose CPU page is the title's");
825 check(!readable(gpu + 2 * kPage64k), "the GPU-only page is unmapped");
826 check(readable(cpu + 2 * kPage64k) && page_holds(cpu + 2 * kPage64k, 0x7300u),
827 "the title's own mapping at the paired CPU page survives the unmap");
828
829 // A null source unmaps both ranges where the CPU pages are the copy's own.
745 check(copy(gpu, nullptr, kPool, false), "a null source unmaps the GPU-only range"); 830 check(copy(gpu, nullptr, kPool, false), "a null source unmaps the GPU-only range");
746 check(!readable(gpu) && !readable(cpu) && !readable(cpu + kPage64k), "the paired CPU range is unmapped with it"); 831 check(!readable(gpu) && !readable(cpu) && !readable(cpu + kPage64k), "the paired CPU range is unmapped with it");
747 832
@@ -1544,6 +1629,38 @@ void test_physical_pages_commit_on_touch(const PhysicalApi& api) {
1544 check(read_ok, "ReadFile fills a page that commit_physical_range committed"); 1629 check(read_ok, "ReadFile fills a page that commit_physical_range committed");
1545 1630
1546 check(api.map(second, 2, nullptr) == second && api.map(window, kMapped, nullptr) == window, "they unmap"); 1631 check(api.map(second, 2, nullptr) == second && api.map(window, kMapped, nullptr) == window, "they unmap");
1632 {
1633 // A host guarded read (outside the title image at 0x140000000) of an unmapped window page exits as
1634 // passed_guarded without counting as left_to_title; a title read still counts as left_to_title.
1635 void* const stub_page = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
1636 const uint8_t mov_eax_rcx_ret[] = {0x8b, 0x01, 0xc3};
1637 DWORD stub_old = 0;
1638 bool stub_ready = false;
1639 if (stub_page) {
1640 std::memcpy(stub_page, mov_eax_rcx_ret, sizeof(mov_eax_rcx_ret));
1641 stub_ready = VirtualProtect(stub_page, 4096, PAGE_EXECUTE_READ, &stub_old) != FALSE;
1642 FlushInstructionCache(GetCurrentProcess(), stub_page, sizeof(mov_eax_rcx_ret));
1643 }
1644 const auto host_read_faults = [&](const void* p) {
1645 __try {
1646 reinterpret_cast<uint32_t (*)(const void*)>(stub_page)(p);
1647 return false;
1648 } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER
1649 : EXCEPTION_CONTINUE_SEARCH) {
1650 return true;
1651 }
1652 };
1653 const uint64_t guarded_before = rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded);
1654 const uint64_t left_before = rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title);
1655 check(stub_ready && host_read_faults(second) &&
1656 rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded) == guarded_before + 1 &&
1657 rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before,
1658 "a host guarded read of an unmapped window page exits as passed_guarded");
1659 check(access_faults(reinterpret_cast<volatile uint32_t*>(second), false) &&
1660 rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before + 1,
1661 "a title read of an unmapped window page still exits as left_to_title");
1662 if (stub_page) VirtualFree(stub_page, 0, MEM_RELEASE);
1663 }
1547 check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them"); 1664 check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them");
1548} 1665}
1549 1666
@@ -2655,6 +2772,7 @@ int main(int argc, char** argv) {
2655 // Keep the direct SEC_RESERVE control ahead of the first physical allocation, which installs xmem's VEH. 2772 // Keep the direct SEC_RESERVE control ahead of the first physical allocation, which installs xmem's VEH.
2656 g_section_write_control = measure_section_write_control(); 2773 g_section_write_control = measure_section_write_control();
2657 test_physical_pages(physical); 2774 test_physical_pages(physical);
2775 test_remap_releases(physical);
2658 if (argc == 2 && std::strcmp(argv[1], "--file-pools") == 0) { 2776 if (argc == 2 && std::strcmp(argv[1], "--file-pools") == 0) {
2659 test_placeholders(physical); 2777 test_placeholders(physical);
2660 print_result(); 2778 print_result();
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp
index cb350820e..e80825623 100644
--- a/runtime/test/xs_proxy_mock_test.cpp
+++ b/runtime/test/xs_proxy_mock_test.cpp
@@ -4644,6 +4644,85 @@ int check_list_values_more() {
4644 WaitForSingleObject(job, INFINITE); 4644 WaitForSingleObject(job, INFINITE);
4645 CloseHandle(job); 4645 CloseHandle(job);
4646 4646
4647 // 11. Work-aware timeout in Pump (src/list_value_wait_budget.h):
4648 // a) a matching in-flight producer pauses a held memory gate past the idle timeout until the producer lands;
4649 // b) a busy releaser executing an action gate pauses a concurrent memory gate past the idle timeout;
4650 // c) a demoted gate (4 ms budget) scales its pause caps with its short budget so unrelated active work does not
4651 // hold it for the full timeout's cap;
4652 // d) a matching producer stuck behind an unsignalled fence still hits a finite pause cap instead of hanging.
4653 const auto write_on_a = [&](int index, std::uint64_t value, std::uint64_t& signal_value) -> bool {
4654 if (FAILED(hr_of(raw(direct, 139, word(allocator), 0)))) return false;
4655 raw(direct, 14, 1, 1, 1); // Dispatch
4656 raw(direct, 72, word(&g_cells2[index]), value, 0, 0); // write64
4657 if (FAILED(hr_of(raw(direct, 9)))) return false;
4658 g_queue_call_count = 0;
4659 if (submit(qa, direct) != 0) return false;
4660 signal_value = logged_signal(qa_mock, a_written);
4661 return signal_value != 0;
4662 };
4663 xs::set_list_value_wait_timeout_ms(40);
4664 xs::reset_list_value_stats();
4665 // 11a. Wait on qb before qa submits its matching write (so relay() misses it and Pump holds a gate).
4666 EXPECT(hold_on(qb, 27, 1));
4667 std::uint64_t producer_sig = 0;
4668 EXPECT(write_on_a(27, 1, producer_sig));
4669 EXPECT(!xs::list_values_idle(150)); // >3x the 40 ms idle timeout: pauses while producer is in flight
4670 stats = xs::list_value_stats();
4671 EXPECT(stats.gates_timed_out == 0 && stats.gates_met == 0 && cell2(27) == 0);
4672 fence_signal(a_written, producer_sig);
4673 EXPECT(xs::list_values_idle(3000) && cell2(27) == 1);
4674 stats = xs::list_value_stats();
4675 EXPECT(stats.gates_met == 1 && stats.gates_timed_out == 0);
4676
4677 // 11b. Releaser inside a 150 ms action gate pauses a concurrent memory gate past the 40 ms idle timeout.
4678 xs::set_copy_page_mappings_hook([](std::uint32_t, const rt::xmem::PageBatch*, std::uintptr_t, std::uint32_t,
4679 std::uint32_t) -> bool {
4680 Sleep(150);
4681 InterlockedExchange64(reinterpret_cast<volatile LONG64*>(&g_cells2[28]), 1);
4682 return true;
4683 });
4684 g_queue_call_count = 0;
4685 EXPECT(hr_of(raw(qc, 31, 1, word(remap), 0x7000000000, 16, 0)) == S_OK);
4686 const std::uint64_t action_sig = logged_signal(qc_mock, c_written);
4687 EXPECT(action_sig != 0);
4688 const std::uint64_t met_before_rel = xs::list_value_stats().gates_met;
4689 const std::uint64_t to_before_rel = xs::list_value_stats().gates_timed_out;
4690 EXPECT(hold_on(qb, 28, 1));
4691 fence_signal(c_written, action_sig);
4692 EXPECT(xs::list_values_idle(3000) && cell2(28) == 1);
4693 xs::set_copy_page_mappings_hook(nullptr);
4694 stats = xs::list_value_stats();
4695 EXPECT(stats.gates_met == met_before_rel + 1 && stats.gates_timed_out == to_before_rel);
4696
4697 // 11c. Demoted gate (3 timeouts -> 4 ms budget) with unrelated in-flight work on qa times out in a few ms, not
4698 // the 12 s active-work cap of the 40 ms full timeout.
4699 for (int i = 0; i < 3; ++i) EXPECT(hold_on(qb, 29, 1) && xs::list_values_idle(3000));
4700 std::uint64_t unrelated_sig = 0;
4701 EXPECT(write_on_a(30, 1, unrelated_sig));
4702 const std::uint64_t short_before_dem = xs::list_value_stats().gates_short;
4703 const std::uint64_t to_before_dem = xs::list_value_stats().gates_timed_out;
4704 started = Clock::now();
4705 EXPECT(hold_on(qb, 29, 1));
4706 for (int i = 0; i < 1000 && xs::list_value_stats().gates_timed_out == to_before_dem; ++i) Sleep(1);
4707 const auto demoted_active_ms = ms_since(started);
4708 EXPECT(xs::list_value_stats().gates_timed_out == to_before_dem + 1 &&
4709 xs::list_value_stats().gates_short == short_before_dem + 1 && demoted_active_ms < 500);
4710 fence_signal(a_written, unrelated_sig);
4711 EXPECT(xs::list_values_idle(3000));
4712
4713 // 11d. Stuck matching producer (fence never signals) still hits the finite max pause cap instead of hanging.
4714 const std::uint64_t to_before_stuck = xs::list_value_stats().gates_timed_out;
4715 started = Clock::now();
4716 EXPECT(hold_on(qb, 29, 1));
4717 std::uint64_t stuck_sig = 0;
4718 EXPECT(write_on_a(29, 1, stuck_sig));
4719 for (int i = 0; i < 1000 && xs::list_value_stats().gates_timed_out == to_before_stuck; ++i) Sleep(1);
4720 const auto stuck_producer_ms = ms_since(started);
4721 EXPECT(xs::list_value_stats().gates_timed_out == to_before_stuck + 1 && stuck_producer_ms < 500);
4722 fence_signal(a_written, stuck_sig);
4723 EXPECT(xs::list_values_idle(3000));
4724 xs::set_list_value_wait_timeout_ms(5000);
4725
4647 // 8. stop() ends both threads. Afterwards nothing new is landed or opened (the process is ending: a gate 4726 // 8. stop() ends both threads. Afterwards nothing new is landed or opened (the process is ending: a gate
4648 // signalled from another thread could open one whose remap was skipped, or go below one still to come), and 4727 // signalled from another thread could open one whose remap was skipped, or go below one still to come), and
4649 // CopyPageMappingsBatchX remaps at the call rather than wait for a queue whose gates stay shut. 4728 // CopyPageMappingsBatchX remaps at the call rather than wait for a queue whose gates stay shut.