diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-26 16:55:04 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-26 16:55:04 -0500 |
| commit | df92abca8ee2a8f9093efea7fcaa4dadc3ddaebc (patch) | |
| tree | 97ef8f95544fe263049d3f7360823f16100de209 /runtime/test | |
| parent | 49a0b69fcdb80db1f2a44ce7ca0ab8dfdec1e403 (diff) | |
| parent | e5a7c8942678b323f655939c81f5d8855d20c248 (diff) | |
Merge main e5a7c8942 into shadow-aliased-guard (#1867)
One conflict, runtime/README.md: this branch rewrote the LEONIDA_SHADOW_ALIAS_MS
row, main (#2163) added the LEONIDA_SHADOW_KEEP row after it. Both rows kept;
the keep row's "aliased" now reads "aliased while they can't be guarded at every
address", since aliased pages are no longer copied without a sign of a write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/test')
42 files changed, 4496 insertions, 411 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 | |||
| 16 | namespace { | ||
| 17 | |||
| 18 | using leonida::address_guard::AddressGuardTable; | ||
| 19 | using Spans = std::vector<std::pair<std::uint64_t, std::uint64_t>>; | ||
| 20 | namespace ag = leonida::address_guard; | ||
| 21 | |||
| 22 | constexpr std::uint64_t kLimit = 0x80000; // the "arena" | ||
| 23 | constexpr 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. | ||
| 26 | struct 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 | |||
| 38 | int 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 | |||
| 80 | int 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 | |||
| 104 | int 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 | |||
| 119 | int 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/bindless_sizing_test.cpp b/runtime/test/bindless_sizing_test.cpp index b7d501aab..b83294852 100644 --- a/runtime/test/bindless_sizing_test.cpp +++ b/runtime/test/bindless_sizing_test.cpp | |||
| @@ -133,18 +133,18 @@ int main() { | |||
| 133 | const Device d = uniform(1048576, 1048576); | 133 | const Device d = uniform(1048576, 1048576); |
| 134 | BindlessFeatures f = with_ms(update_after_bind); | 134 | BindlessFeatures f = with_ms(update_after_bind); |
| 135 | EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12)); | 135 | EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12)); |
| 136 | EXPECT(count(f, D::dim_2d) == bindless::max_2d_images); | 136 | EXPECT(count(f, D::dim_2d) == bindless::max_images); |
| 137 | EXPECT(f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); | 137 | EXPECT(f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); |
| 138 | EXPECT(f.counts[bindless::sampler_binding] > 2048); // a full sampler heap and the fallback | 138 | EXPECT(f.counts[bindless::sampler_binding] > 2048); // a full sampler heap and the fallback |
| 139 | EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices); | 139 | EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices); |
| 140 | // The other dimensions grow too (a title's cube maps, texture arrays and 1D lookups outnumber the defaults); | 140 | // The other dimensions grow as far as 2D (a title's textures are of whichever dimension it chose); their |
| 141 | // their storage arrays hold as many indices as the 2D one. The storage-only 1D array keeps its 256. | 141 | // storage arrays hold as many indices as the 2D one. The storage-only 1D array keeps its 256. |
| 142 | EXPECT(count(f, D::dim_2d_array) == bindless::max_2d_array_images && | 142 | EXPECT(count(f, D::dim_2d_array) == bindless::max_images && count(f, D::dim_3d) == bindless::max_images && |
| 143 | count(f, D::dim_3d) == bindless::max_3d_images && count(f, D::dim_1d) == bindless::max_1d_images); | 143 | count(f, D::dim_1d) == bindless::max_images); |
| 144 | EXPECT(storage(f, D::dim_2d_array) == bindless::max_storage_indices && | 144 | EXPECT(storage(f, D::dim_2d_array) == bindless::max_storage_indices && |
| 145 | storage(f, D::dim_3d) == bindless::max_storage_indices && | 145 | storage(f, D::dim_3d) == bindless::max_storage_indices && |
| 146 | storage(f, D::dim_1d) == bindless::max_storage_indices); | 146 | storage(f, D::dim_1d) == bindless::max_storage_indices); |
| 147 | EXPECT(storage(f, D::dim_1d_array) == 256 && totals(f).all == 153697); | 147 | EXPECT(storage(f, D::dim_1d_array) == 256 && totals(f).all == 325729); |
| 148 | EXPECT(f.ms_samples[0] == VK_SAMPLE_COUNT_4_BIT && f.ms_samples[2] == VK_SAMPLE_COUNT_4_BIT); | 148 | EXPECT(f.ms_samples[0] == VK_SAMPLE_COUNT_4_BIT && f.ms_samples[2] == VK_SAMPLE_COUNT_4_BIT); |
| 149 | EXPECT(storage_consistent(f)); | 149 | EXPECT(storage_consistent(f)); |
| 150 | if (update_after_bind) | 150 | if (update_after_bind) |
| @@ -152,6 +152,44 @@ int main() { | |||
| 152 | count(f, D::dim_2d), f.counts[bindless::sampler_binding], storage(f, D::dim_2d), totals(f).all); | 152 | count(f, D::dim_2d), f.counts[bindless::sampler_binding], storage(f, D::dim_2d), totals(f).all); |
| 153 | } | 153 | } |
| 154 | 154 | ||
| 155 | // RADV (Mesa 26.3, a Raphael iGPU and an RX 7900 XTX alike) and llvmpipe: their update-after-bind limits hold | ||
| 156 | // every sampled dimension at the full size. A world run kept 4090 live 1D textures, filling the 4096 1D indices | ||
| 157 | // the set used to stop at whatever the device held; now 1D, 3D and 2D-array images get as many as 2D. | ||
| 158 | { | ||
| 159 | Device radv = uniform(8388606, 8388606); | ||
| 160 | radv.limits.maxPerStageResources = radv.v12.maxPerStageUpdateAfterBindResources = 8388606; | ||
| 161 | radv.v12.maxUpdateAfterBindDescriptorsInAllPools = 67108863; | ||
| 162 | radv.v11.maxPerSetDescriptors = 22369621; | ||
| 163 | radv.limits.maxSamplerAllocationCount = 4294967295u; | ||
| 164 | Device lvp = uniform(1015808, 1015808); | ||
| 165 | lvp.limits.maxPerStageResources = lvp.v12.maxPerStageUpdateAfterBindResources = 1015808; | ||
| 166 | lvp.v11.maxPerSetDescriptors = 1015808; | ||
| 167 | lvp.limits.maxSamplerAllocationCount = 32768; | ||
| 168 | for (const Device* d : {&radv, &lvp}) { | ||
| 169 | BindlessFeatures f = with_ms(true); | ||
| 170 | EXPECT(bindless::size_bindings(f, d->limits, d->v11, d->v12)); | ||
| 171 | for (const D dimension : {D::dim_2d, D::dim_2d_array, D::dim_3d, D::dim_1d}) { | ||
| 172 | EXPECT(count(f, dimension) == bindless::max_images); | ||
| 173 | EXPECT(count(f, dimension) > 4096 + 1); // more than 4096 live images and the fallback | ||
| 174 | } | ||
| 175 | EXPECT(storage_consistent(f)); | ||
| 176 | } | ||
| 177 | } | ||
| 178 | |||
| 179 | // A device whose limits stop growth short of max_images: the 2D-array, 3D and 1D arrays share what is left alike, | ||
| 180 | // whichever is grown first. | ||
| 181 | { | ||
| 182 | Device d = uniform(1048576, 1048576); | ||
| 183 | d.v12.maxPerStageDescriptorUpdateAfterBindSampledImages = 65536 + 3 * 20000 + 6 * 256 + bindless::growth_headroom; | ||
| 184 | BindlessFeatures f = with_ms(true); | ||
| 185 | EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12)); | ||
| 186 | EXPECT(count(f, D::dim_2d) == bindless::max_images); | ||
| 187 | EXPECT(count(f, D::dim_2d_array) == count(f, D::dim_3d) && count(f, D::dim_3d) == count(f, D::dim_1d)); | ||
| 188 | EXPECT(count(f, D::dim_1d) > 4096 && count(f, D::dim_1d) <= 20000); | ||
| 189 | EXPECT(totals(f).sampled + bindless::growth_headroom <= d.v12.maxPerStageDescriptorUpdateAfterBindSampledImages); | ||
| 190 | EXPECT(storage_consistent(f)); | ||
| 191 | } | ||
| 192 | |||
| 155 | // At today's sizes exactly (5632 sampled images, 1024 samplers, 4352 storage images): no MS pairs. | 193 | // At today's sizes exactly (5632 sampled images, 1024 samplers, 4352 storage images): no MS pairs. |
| 156 | { | 194 | { |
| 157 | Device d = uniform(1048576, 1048576); | 195 | Device d = uniform(1048576, 1048576); |
| @@ -191,7 +229,7 @@ int main() { | |||
| 191 | BindlessFeatures uab = with_ms(true), plain = with_ms(false); | 229 | BindlessFeatures uab = with_ms(true), plain = with_ms(false); |
| 192 | EXPECT(bindless::size_bindings(uab, d.limits, d.v11, d.v12)); | 230 | EXPECT(bindless::size_bindings(uab, d.limits, d.v11, d.v12)); |
| 193 | EXPECT(bindless::size_bindings(plain, d.limits, d.v11, d.v12)); | 231 | EXPECT(bindless::size_bindings(plain, d.limits, d.v11, d.v12)); |
| 194 | EXPECT(count(uab, D::dim_2d) == bindless::max_2d_images); | 232 | EXPECT(count(uab, D::dim_2d) == bindless::max_images); |
| 195 | const Totals t = totals(plain); | 233 | const Totals t = totals(plain); |
| 196 | EXPECT(count(plain, D::dim_2d) > 4096 && count(plain, D::dim_2d) < 16384); | 234 | EXPECT(count(plain, D::dim_2d) > 4096 && count(plain, D::dim_2d) < 16384); |
| 197 | EXPECT(t.sampled + bindless::growth_headroom <= 16384 && t.storage + bindless::growth_headroom <= 16384); | 235 | EXPECT(t.sampled + bindless::growth_headroom <= 16384 && t.storage + bindless::growth_headroom <= 16384); |
| @@ -232,7 +270,7 @@ int main() { | |||
| 232 | BindlessFeatures f = with_ms(true); | 270 | BindlessFeatures f = with_ms(true); |
| 233 | EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, all_supported)); | 271 | EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, all_supported)); |
| 234 | EXPECT(asked > 0 && asked_within == 0 && missing_storage == 0); | 272 | EXPECT(asked > 0 && asked_within == 0 && missing_storage == 0); |
| 235 | EXPECT(count(f, D::dim_2d) == bindless::max_2d_images && | 273 | EXPECT(count(f, D::dim_2d) == bindless::max_images && |
| 236 | f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); | 274 | f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); |
| 237 | EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices && storage_consistent(f)); | 275 | EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices && storage_consistent(f)); |
| 238 | 276 | ||
diff --git a/runtime/test/check_atexit.cmake b/runtime/test/check_atexit.cmake index 255bb3a4f..6b34c9d81 100644 --- a/runtime/test/check_atexit.cmake +++ b/runtime/test/check_atexit.cmake | |||
| @@ -26,6 +26,12 @@ set(code_c_exit 12) | |||
| 26 | # exit(7) is running a slow handler when a second thread calls _exit(7): the exit lock holds it back. | 26 | # exit(7) is running a slow handler when a second thread calls _exit(7): the exit lock holds it back. |
| 27 | set(expect_concurrent_exit "${ctors};slow handler started;slow handler done;${handlers}") | 27 | set(expect_concurrent_exit "${ctors};slow handler started;slow handler done;${handlers}") |
| 28 | set(code_concurrent_exit 7) | 28 | set(code_concurrent_exit 7) |
| 29 | # The main thread's thread_local object ends before the atexit handlers and static destructors ([basic.start.term]): | ||
| 30 | # the UCRT calls the EXE's thread-local destructor callback first in exit() and _cexit(). | ||
| 31 | set(expect_thread_local_exit "${ctors};ctor thread_local;dtor thread_local;${handlers}") | ||
| 32 | set(code_thread_local_exit 13) | ||
| 33 | set(expect_thread_local_cexit "${ctors};ctor thread_local;dtor thread_local;${handlers};after _cexit") | ||
| 34 | set(code_thread_local_cexit 14) | ||
| 29 | 35 | ||
| 30 | # The program's own lines, in order, without the prefix; everything gta6rt prints is dropped. | 36 | # The program's own lines, in order, without the prefix; everything gta6rt prints is dropped. |
| 31 | function(guest_lines output result) | 37 | function(guest_lines output result) |
| @@ -42,7 +48,7 @@ function(guest_lines output result) | |||
| 42 | endfunction() | 48 | endfunction() |
| 43 | 49 | ||
| 44 | set(failures "") | 50 | set(failures "") |
| 45 | foreach(mode return exit _exit quick_exit ExitProcess cexit c_exit concurrent_exit) | 51 | foreach(mode return exit _exit quick_exit ExitProcess cexit c_exit concurrent_exit thread_local_exit thread_local_cexit) |
| 46 | execute_process(COMMAND ${RUNNER} "${GUEST}" ${mode} | 52 | execute_process(COMMAND ${RUNNER} "${GUEST}" ${mode} |
| 47 | WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60 | 53 | WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60 |
| 48 | RESULT_VARIABLE native_code OUTPUT_VARIABLE native_out ERROR_VARIABLE native_err) | 54 | RESULT_VARIABLE native_code OUTPUT_VARIABLE native_out ERROR_VARIABLE native_err) |
| @@ -68,4 +74,4 @@ endforeach() | |||
| 68 | if(failures) | 74 | if(failures) |
| 69 | message(FATAL_ERROR "atexit/termination differences:${failures}") | 75 | message(FATAL_ERROR "atexit/termination differences:${failures}") |
| 70 | endif() | 76 | endif() |
| 71 | message(STATUS "tiny_atexit: 8 termination paths match the Windows sequence") | 77 | message(STATUS "tiny_atexit: 10 termination paths match the Windows sequence") |
diff --git a/runtime/test/check_precompile_skip_list.cmake b/runtime/test/check_precompile_skip_list.cmake new file mode 100644 index 000000000..5945db761 --- /dev/null +++ b/runtime/test/check_precompile_skip_list.cmake | |||
| @@ -0,0 +1,123 @@ | |||
| 1 | # gta6rt --precompile-pipelines and LEONIDA_SKIP_COMPUTE (shims/d3d12_precompile.h): the play-time skip list does not | ||
| 2 | # keep programs out of the pipeline journal; --skip-listed does, and the closing line counts both. | ||
| 3 | # cmake -DGTA6RT=<gta6rt.exe> [-DRUNNER=<wine>] -DSPV_A=<compute .spv> -DSPV_B=<another compute .spv> | ||
| 4 | # -DTEST_DIR=<scratch folder> -P check_precompile_skip_list.cmake | ||
| 5 | # A library of two synthetic compute entries, one of them named by LEONIDA_SKIP_COMPUTE, is precompiled three times: | ||
| 6 | # 1. into an empty journal with the list set and no flag: both entries are built; | ||
| 7 | # 2. into another empty journal with --skip-listed: only the unlisted one is, and the listed one is reported; | ||
| 8 | # 3. into the first journal again: both are journaled already, nothing is built. | ||
| 9 | # The verdicts are read from the output and the journal folders, since under Wine an exit status alone can look fine. | ||
| 10 | cmake_minimum_required(VERSION 3.24) | ||
| 11 | |||
| 12 | foreach(var GTA6RT SPV_A SPV_B TEST_DIR) | ||
| 13 | if(NOT DEFINED ${var} OR "${${var}}" STREQUAL "") | ||
| 14 | message(FATAL_ERROR "check_precompile_skip_list.cmake: -D${var}=... is required") | ||
| 15 | endif() | ||
| 16 | endforeach() | ||
| 17 | |||
| 18 | file(REMOVE_RECURSE "${TEST_DIR}") | ||
| 19 | file(MAKE_DIRECTORY "${TEST_DIR}/shaders") | ||
| 20 | # Two different modules: entries with the same module and layout share one journal file. | ||
| 21 | file(COPY_FILE "${SPV_A}" "${TEST_DIR}/shaders/precompile_kept.spv") | ||
| 22 | file(COPY_FILE "${SPV_B}" "${TEST_DIR}/shaders/precompile_listed.spv") | ||
| 23 | # The runtime's library takes an entry only with a program hash; these two name no real program. | ||
| 24 | set(meta "\"stage\":\"cs\",\"bindings\":[],\"push_constant_bytes\":144,\"local_size\":[1,1,1],\"wave64\":false") | ||
| 25 | string(REPEAT "a" 64 hash_kept) | ||
| 26 | string(REPEAT "b" 64 hash_listed) | ||
| 27 | file(WRITE "${TEST_DIR}/shaders/index.json" | ||
| 28 | "{\"precompile_kept\":{\"fssm_sha256\":\"${hash_kept}\",${meta}}," | ||
| 29 | "\"precompile_listed\":{\"fssm_sha256\":\"${hash_listed}\",${meta}}}\n") | ||
| 30 | |||
| 31 | # Only what this test sets: a journal setting or helper from the caller's environment would change the counts. | ||
| 32 | foreach(var LEONIDA_PIPELINE_JOURNAL LEONIDA_PIPELINE_CACHE_BYTES LEONIDA_PIPELINE_JOURNAL_BYTES | ||
| 33 | LEONIDA_PIPELINE_JOURNAL_SEED_DIR LEONIDA_COMPILE_HELPER LEONIDA_LAZY_COMPUTE) | ||
| 34 | unset(ENV{${var}}) | ||
| 35 | endforeach() | ||
| 36 | file(TO_NATIVE_PATH "${TEST_DIR}/shaders" shaders) | ||
| 37 | set(ENV{LEONIDA_SHADERS} "${shaders}") | ||
| 38 | set(ENV{LEONIDA_SKIP_COMPUTE} "precompile_listed") | ||
| 39 | |||
| 40 | set(failures "") | ||
| 41 | set(all_output "") | ||
| 42 | # Runs the precompile with the journal in <cache> and the extra arguments; sets `out` and `code` in the caller. | ||
| 43 | function(precompile label cache) | ||
| 44 | file(TO_NATIVE_PATH "${TEST_DIR}/${cache}" cache_dir) | ||
| 45 | set(ENV{LEONIDA_PIPELINE_CACHE_DIR} "${cache_dir}") | ||
| 46 | execute_process(COMMAND ${RUNNER} "${GTA6RT}" --precompile-pipelines --threads 1 ${ARGN} | ||
| 47 | WORKING_DIRECTORY "${TEST_DIR}" | ||
| 48 | TIMEOUT 90 | ||
| 49 | RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE output) | ||
| 50 | string(REPLACE "\r\n" "\n" output "\n${output}\n") | ||
| 51 | set(out "${output}" PARENT_SCOPE) | ||
| 52 | set(code "${result}" PARENT_SCOPE) | ||
| 53 | set(all_output "${all_output}--- ${label} (exit ${result}) ---${output}" PARENT_SCOPE) | ||
| 54 | endfunction() | ||
| 55 | # Functions, not macros: a macro would substitute the patterns' text and undo their backslash escapes. | ||
| 56 | function(expect label pattern) | ||
| 57 | if(NOT out MATCHES "${pattern}") | ||
| 58 | set(failures "${failures}${label}: no match for '${pattern}'\n" PARENT_SCOPE) | ||
| 59 | endif() | ||
| 60 | endfunction() | ||
| 61 | function(expect_not label pattern) | ||
| 62 | if(out MATCHES "${pattern}") | ||
| 63 | set(failures "${failures}${label}: unexpected match for '${pattern}'\n" PARENT_SCOPE) | ||
| 64 | endif() | ||
| 65 | endfunction() | ||
| 66 | function(expect_exit label want) | ||
| 67 | if(NOT "${code}" STREQUAL "${want}") | ||
| 68 | set(failures "${failures}${label}: exit ${code}, not ${want}\n" PARENT_SCOPE) | ||
| 69 | endif() | ||
| 70 | endfunction() | ||
| 71 | function(journal_files cache var) | ||
| 72 | file(GLOB files "${TEST_DIR}/${cache}/pipeline_cache.d/cs-*.bin") | ||
| 73 | list(LENGTH files count) | ||
| 74 | set(${var} ${count} PARENT_SCOPE) | ||
| 75 | endfunction() | ||
| 76 | |||
| 77 | # 1. The list is set, no flag: both entries are built and nothing is reported as left out by the list. | ||
| 78 | precompile("list set, no flag" cache_all) | ||
| 79 | if(code STREQUAL "1" AND out MATCHES "the Vulkan device could not be created|the runtime builds no compute pipeline") | ||
| 80 | message("SKIP: no Vulkan device for the precompile here${all_output}") | ||
| 81 | return() | ||
| 82 | endif() | ||
| 83 | expect_exit("list set, no flag" 0) | ||
| 84 | expect("list set, no flag" "\n\\[precompile\\] LEONIDA_SKIP_COMPUTE names 1 of the entries: built anyway") | ||
| 85 | expect("list set, no flag" "\n\\[precompile\\] 2 compute entries to build ") | ||
| 86 | expect_not("list set, no flag" "precompile_listed: not built") | ||
| 87 | expect("list set, no flag" "\n\\[precompile\\] done: 2 built \\([0-9]+ compiled, [0-9]+ from a cache\\), 0 journaled already, 0 being built by another process, 0 failed; left out: 0 of 1 listed in LEONIDA_SKIP_COMPUTE, 0 not buildable, 0 filtered out; in [0-9]+ s\n") | ||
| 88 | # A driver that returns no cache data leaves no journal file; then step 3 has nothing to find. | ||
| 89 | set(journaled TRUE) | ||
| 90 | if(out MATCHES "compiled \\(not journaled\\)") | ||
| 91 | set(journaled FALSE) | ||
| 92 | message("note: the driver gave no cache data, so the journal-file checks are left out") | ||
| 93 | else() | ||
| 94 | journal_files(cache_all count) | ||
| 95 | if(NOT count EQUAL 2) | ||
| 96 | string(APPEND failures "list set, no flag: ${count} journal files, not 2\n") | ||
| 97 | endif() | ||
| 98 | endif() | ||
| 99 | |||
| 100 | # 2. --skip-listed: the listed entry is left out and named, the other one is built. | ||
| 101 | precompile("--skip-listed" cache_listed --skip-listed) | ||
| 102 | expect_exit("--skip-listed" 0) | ||
| 103 | expect("--skip-listed" "\n\\[precompile\\] precompile_listed: not built \\(LEONIDA_SKIP_COMPUTE, --skip-listed\\)\n") | ||
| 104 | expect("--skip-listed" "\n\\[precompile\\] 1 compute entries to build \\([^)]*, 1 left out by --skip-listed, 0 not buildable\\)") | ||
| 105 | expect("--skip-listed" "\n\\[precompile\\] done: 1 built \\([0-9]+ compiled, [0-9]+ from a cache\\), 0 journaled already, 0 being built by another process, 0 failed; left out: 1 of 1 listed in LEONIDA_SKIP_COMPUTE \\(--skip-listed\\), 0 not buildable, 0 filtered out; in [0-9]+ s\n") | ||
| 106 | if(journaled) | ||
| 107 | journal_files(cache_listed count) | ||
| 108 | if(NOT count EQUAL 1) | ||
| 109 | string(APPEND failures "--skip-listed: ${count} journal files, not 1\n") | ||
| 110 | endif() | ||
| 111 | endif() | ||
| 112 | |||
| 113 | # 3. The first journal again: both entries are there, nothing is built. | ||
| 114 | if(journaled) | ||
| 115 | precompile("again" cache_all) | ||
| 116 | expect_exit("again" 0) | ||
| 117 | expect("again" "\n\\[precompile\\] done: 0 built \\(0 compiled, 0 from a cache\\), 2 journaled already, 0 being built by another process, 0 failed; left out: 0 of 1 listed in LEONIDA_SKIP_COMPUTE, 0 not buildable, 0 filtered out; in [0-9]+ s\n") | ||
| 118 | endif() | ||
| 119 | |||
| 120 | if(failures) | ||
| 121 | message(FATAL_ERROR "gta6rt --precompile-pipelines and LEONIDA_SKIP_COMPUTE:\n${failures}${all_output}") | ||
| 122 | endif() | ||
| 123 | message("precompile and LEONIDA_SKIP_COMPUTE: built regardless of the list, left out with --skip-listed${all_output}") | ||
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 | ||
| 5 | int main() { | 6 | int 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_slot_records_test.cpp b/runtime/test/console_heap_slot_records_test.cpp new file mode 100644 index 000000000..c5fcfbe9a --- /dev/null +++ b/runtime/test/console_heap_slot_records_test.cpp | |||
| @@ -0,0 +1,347 @@ | |||
| 1 | // leonida::ConsoleHeapSlotRecords (src/console_heap_slot_records.h): a change of the address space finds exactly the | ||
| 2 | // console-heap slots whose V#s it touches, without walking the heap. Portable, CPU only, no game data. | ||
| 3 | // | ||
| 4 | // A small model stands in for the device: backings (device ranges), alias ranges (title VA -> arena offset) and a | ||
| 5 | // resolver that follows DeviceState::vsharp_address's order (an alias first, refused when its copy is not backed; then | ||
| 6 | // the base as an arena offset). fix() is fix_console_slot: it resolves both halves of a slot, writes the "copy" and the | ||
| 7 | // records. apply() is apply_slot_changes: the slots touched() names are fixed again. After every step the copy is | ||
| 8 | // compared with a full re-resolution of every slot: a slot left naming a range that went (a GPU page fault in the | ||
| 9 | // runtime) or a waiting slot left null after its buffer came fails the comparison. | ||
| 10 | #include "../src/console_heap_slot_records.h" | ||
| 11 | |||
| 12 | #include <array> | ||
| 13 | #include <cstdint> | ||
| 14 | #include <cstdio> | ||
| 15 | #include <iterator> | ||
| 16 | #include <map> | ||
| 17 | #include <random> | ||
| 18 | #include <vector> | ||
| 19 | |||
| 20 | #define EXPECT(condition) do { \ | ||
| 21 | if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ | ||
| 22 | } while (0) | ||
| 23 | |||
| 24 | namespace { | ||
| 25 | |||
| 26 | using leonida::ConsoleHeapSlotRecords; | ||
| 27 | using leonida::SlotChange; | ||
| 28 | |||
| 29 | constexpr std::uint64_t kArena = 0x7f0000000000ull; // the arena's device address | ||
| 30 | constexpr std::uint64_t kMask = (1ull << 48) - 1; | ||
| 31 | |||
| 32 | struct HalfWords { | ||
| 33 | std::uint64_t base = 0, span = 0; // span 0: no V# in this half | ||
| 34 | }; | ||
| 35 | |||
| 36 | struct Model { | ||
| 37 | using Words = HalfWords; | ||
| 38 | struct Alias { | ||
| 39 | std::uint64_t end, shader; | ||
| 40 | }; | ||
| 41 | std::vector<std::array<Words, 2>> slots; | ||
| 42 | std::vector<std::array<std::uint64_t, 2>> copy; // the device address each half names, 0: null | ||
| 43 | std::map<std::uint64_t, std::uint64_t> backings; // device start -> end | ||
| 44 | std::map<std::uint64_t, Alias> aliases; // title VA -> range | ||
| 45 | ConsoleHeapSlotRecords records; | ||
| 46 | std::vector<SlotChange> changes; | ||
| 47 | std::uint64_t fixes = 0; | ||
| 48 | |||
| 49 | explicit Model(std::size_t n) : slots(n), copy(n, {0, 0}) { records.reset(n); } | ||
| 50 | |||
| 51 | bool backed(std::uint64_t address, std::uint64_t span) const { | ||
| 52 | auto it = backings.upper_bound(address); | ||
| 53 | if (it == backings.begin()) return false; | ||
| 54 | --it; | ||
| 55 | return address >= it->first && address + span <= it->second; | ||
| 56 | } | ||
| 57 | // As vsharp_address: 0 when nothing backs it, with `refused` an alias copy that is not backed. | ||
| 58 | std::uint64_t resolve(std::uint64_t base, std::uint64_t span, std::uint64_t& refused) const { | ||
| 59 | refused = 0; | ||
| 60 | auto it = aliases.upper_bound(base); | ||
| 61 | if (it != aliases.begin() && base < std::prev(it)->second.end) { | ||
| 62 | --it; | ||
| 63 | const std::uint64_t to = kArena + it->second.shader + (base - it->first); | ||
| 64 | if (base + span > it->second.end || !backed(to, span)) { | ||
| 65 | refused = to; | ||
| 66 | return 0; | ||
| 67 | } | ||
| 68 | return to; | ||
| 69 | } | ||
| 70 | if (base < (1ull << 40) && backed(kArena + base, span)) return kArena + base; | ||
| 71 | return 0; | ||
| 72 | } | ||
| 73 | void fix(std::size_t slot) { | ||
| 74 | ++fixes; | ||
| 75 | for (unsigned half = 0; half < 2; ++half) { | ||
| 76 | const Words& w = slots[slot][half]; | ||
| 77 | if (!w.span) { | ||
| 78 | records.set(slot, half, ConsoleHeapSlotRecords::none, 0, 0, 0); | ||
| 79 | copy[slot][half] = 0; | ||
| 80 | continue; | ||
| 81 | } | ||
| 82 | std::uint64_t refused = 0; | ||
| 83 | const std::uint64_t to = resolve(w.base, w.span, refused); | ||
| 84 | records.set(slot, half, to ? ConsoleHeapSlotRecords::resolved : ConsoleHeapSlotRecords::waiting, w.base, | ||
| 85 | w.span, to ? to : refused); | ||
| 86 | copy[slot][half] = to; | ||
| 87 | } | ||
| 88 | } | ||
| 89 | void write(std::size_t slot, Words a, Words b = Words{}) { | ||
| 90 | slots[slot] = {a, b}; | ||
| 91 | fix(slot); | ||
| 92 | } | ||
| 93 | void zero(std::size_t slot) { | ||
| 94 | slots[slot] = {}; | ||
| 95 | copy[slot] = {0, 0}; | ||
| 96 | records.clear(slot); | ||
| 97 | } | ||
| 98 | // The changes the device notes (DeviceState::backing, alias_changed). | ||
| 99 | void add_backing(std::uint64_t offset, std::uint64_t bytes) { | ||
| 100 | backings[kArena + offset] = kArena + offset + bytes; | ||
| 101 | changes.push_back({SlotChange::target_added, kArena + offset, kArena + offset + bytes}); | ||
| 102 | changes.push_back({SlotChange::source_added, offset & kMask, (offset & kMask) + bytes}); | ||
| 103 | } | ||
| 104 | void release_backing(std::uint64_t offset) { | ||
| 105 | const auto it = backings.find(kArena + offset); | ||
| 106 | changes.push_back({SlotChange::target_gone, it->first, it->second}); | ||
| 107 | backings.erase(it); | ||
| 108 | } | ||
| 109 | void add_alias(std::uint64_t title, std::uint64_t bytes, std::uint64_t shader) { | ||
| 110 | for (auto it = aliases.begin(); it != aliases.end();) { | ||
| 111 | if (it->first < title + bytes && it->second.end > title) { | ||
| 112 | remove_change(it->first, it->second); | ||
| 113 | it = aliases.erase(it); | ||
| 114 | } else { | ||
| 115 | ++it; | ||
| 116 | } | ||
| 117 | } | ||
| 118 | aliases[title] = {title + bytes, shader}; | ||
| 119 | changes.push_back({SlotChange::source_added, title, title + bytes}); | ||
| 120 | } | ||
| 121 | void remove_alias(std::uint64_t title) { | ||
| 122 | const auto it = aliases.find(title); | ||
| 123 | remove_change(it->first, it->second); | ||
| 124 | aliases.erase(it); | ||
| 125 | } | ||
| 126 | void remove_change(std::uint64_t title, const Alias& a) { | ||
| 127 | changes.push_back({SlotChange::source_gone, title, a.end}); | ||
| 128 | changes.push_back({SlotChange::target_gone, kArena + a.shader, kArena + a.shader + (a.end - title)}); | ||
| 129 | } | ||
| 130 | // apply_slot_changes: the slots looked at (index entries) and fixed again. | ||
| 131 | std::uint64_t looked = 0; | ||
| 132 | std::vector<std::uint32_t> touched; | ||
| 133 | void apply() { | ||
| 134 | const std::uint64_t before = records.looked_at(); | ||
| 135 | records.touched(changes.data(), changes.size(), touched); | ||
| 136 | looked = records.looked_at() - before; | ||
| 137 | changes.clear(); | ||
| 138 | for (const std::uint32_t slot : touched) fix(slot); | ||
| 139 | } | ||
| 140 | // Every slot as a full re-resolution would leave it: the copy the walk this replaced would have produced. | ||
| 141 | bool consistent() const { | ||
| 142 | for (std::size_t slot = 0; slot < slots.size(); ++slot) | ||
| 143 | for (unsigned half = 0; half < 2; ++half) { | ||
| 144 | const Words& w = slots[slot][half]; | ||
| 145 | std::uint64_t refused = 0; | ||
| 146 | const std::uint64_t want = w.span ? resolve(w.base, w.span, refused) : 0; | ||
| 147 | if (copy[slot][half] != want) { | ||
| 148 | std::fprintf(stderr, "slot %zu half %u names 0x%llx, a full re-resolution gives 0x%llx\n", slot, half, | ||
| 149 | static_cast<unsigned long long>(copy[slot][half]), | ||
| 150 | static_cast<unsigned long long>(want)); | ||
| 151 | return false; | ||
| 152 | } | ||
| 153 | } | ||
| 154 | return true; | ||
| 155 | } | ||
| 156 | }; | ||
| 157 | |||
| 158 | // The design's case: 60,010 live slots, 10 of them name buffer B. Releasing B looks at those 10 and fixes only them; | ||
| 159 | // the walk this replaced looked at all 60,010. | ||
| 160 | int release_looks_at_its_slots_only() { | ||
| 161 | constexpr std::size_t kSlots = 65536; | ||
| 162 | Model m(kSlots); | ||
| 163 | constexpr std::uint64_t a = 0x100000, b = 0x900000; | ||
| 164 | m.add_backing(a, 0x10000); | ||
| 165 | m.add_backing(b, 0x10000); | ||
| 166 | m.changes.clear(); | ||
| 167 | for (std::size_t slot = 0; slot < 60000; ++slot) m.write(slot, {a + (slot % 64) * 0x100, 0x100}); | ||
| 168 | for (std::size_t slot = 60000; slot < 60010; ++slot) m.write(slot, {b + (slot - 60000) * 0x100, 0x100}); | ||
| 169 | EXPECT(m.records.recorded() == 60010 && m.records.waiting_count() == 0 && m.consistent()); | ||
| 170 | m.fixes = 0; | ||
| 171 | m.release_backing(b); | ||
| 172 | m.apply(); | ||
| 173 | const std::uint64_t looked = m.looked; | ||
| 174 | EXPECT(looked <= 10); | ||
| 175 | EXPECT(m.touched.size() == 10 && m.touched.front() == 60000 && m.touched.back() == 60009); | ||
| 176 | EXPECT(m.fixes == 10 && m.records.waiting_count() == 10 && m.consistent()); | ||
| 177 | // Nothing changed: nothing looked at. | ||
| 178 | m.apply(); | ||
| 179 | EXPECT(m.looked == 0 && m.touched.empty()); | ||
| 180 | std::printf("release: 60,010 live slots, 10 name the buffer: %llu looked at, 10 fixed again\n", | ||
| 181 | static_cast<unsigned long long>(looked)); | ||
| 182 | return 0; | ||
| 183 | } | ||
| 184 | |||
| 185 | // An alias range removed, replaced and added again; a slot overwritten or zeroed after it was recorded; a release that | ||
| 186 | // only partly overlaps a slot's range; two slots naming one backing; a buffer that comes back. | ||
| 187 | int cases() { | ||
| 188 | Model m(4096); | ||
| 189 | constexpr std::uint64_t title = 0x200000000000ull, copy_at = 0x400000, other_copy = 0x800000, c = 0x1000000; | ||
| 190 | m.add_backing(copy_at, 0x20000); | ||
| 191 | m.add_backing(other_copy, 0x20000); | ||
| 192 | m.add_backing(c, 0x10000); | ||
| 193 | m.add_alias(title, 0x20000, copy_at); | ||
| 194 | m.apply(); | ||
| 195 | for (std::size_t slot = 0; slot < 8; ++slot) m.write(slot, {title + slot * 0x1000, 0x800}); | ||
| 196 | EXPECT(m.copy[3][0] == kArena + copy_at + 0x3000 && m.consistent()); | ||
| 197 | |||
| 198 | // Alias change: the range moves to another copy; every slot through it follows, nothing else is fixed. | ||
| 199 | m.write(100, {c, 0x100}); | ||
| 200 | m.add_alias(title, 0x20000, other_copy); | ||
| 201 | m.apply(); | ||
| 202 | EXPECT(m.touched.size() == 8 && m.copy[3][0] == kArena + other_copy + 0x3000 && m.consistent()); | ||
| 203 | // Removed: they wait (null in the copy); added again: they are fixed when it comes. | ||
| 204 | m.remove_alias(title); | ||
| 205 | m.apply(); | ||
| 206 | EXPECT(m.touched.size() == 8 && m.copy[3][0] == 0 && m.records.waiting_count() == 8 && m.consistent()); | ||
| 207 | m.add_alias(title, 0x20000, copy_at); | ||
| 208 | m.apply(); | ||
| 209 | EXPECT(m.touched.size() == 8 && m.records.waiting_count() == 0 && m.consistent()); | ||
| 210 | |||
| 211 | // A slot overwritten after it was recorded (it names C now), and one zeroed: a release of their old copy does not | ||
| 212 | // touch them; the zeroed one keeps no record. | ||
| 213 | m.write(5, {c + 0x200, 0x100}); | ||
| 214 | m.zero(6); | ||
| 215 | m.release_backing(copy_at); | ||
| 216 | m.apply(); | ||
| 217 | EXPECT(m.touched.size() == 6); // slots 0-4 and 7 | ||
| 218 | for (const std::uint32_t slot : m.touched) EXPECT(slot != 5 && slot != 6 && slot != 100); | ||
| 219 | EXPECT(m.copy[5][0] == kArena + c + 0x200 && m.records.state(6, 0) == ConsoleHeapSlotRecords::none); | ||
| 220 | EXPECT(m.consistent()); | ||
| 221 | |||
| 222 | // Partial overlap: a release that covers only the tail of a slot's range touches it; one that ends right before | ||
| 223 | // its range does not. The two slots naming the same bytes are both fixed. | ||
| 224 | m.add_backing(0x2000000, 0x1000); | ||
| 225 | m.add_backing(0x2001000, 0x3000); | ||
| 226 | m.apply(); | ||
| 227 | m.write(200, {0x2001800, 0x400}); | ||
| 228 | m.write(201, {0x2001800, 0x400}); | ||
| 229 | m.write(202, {0x2000000, 0x1000}); // ends where the second backing starts | ||
| 230 | EXPECT(m.copy[200][0] == kArena + 0x2001800 && m.copy[202][0] == kArena + 0x2000000); | ||
| 231 | m.release_backing(0x2001000); | ||
| 232 | m.apply(); | ||
| 233 | EXPECT(m.touched.size() == 2 && m.touched[0] == 200 && m.touched[1] == 201); | ||
| 234 | EXPECT(m.copy[200][0] == 0 && m.copy[201][0] == 0 && m.copy[202][0] != 0 && m.consistent()); | ||
| 235 | // The buffer comes back: the waiting slots are fixed again by the addition, not by a probe. | ||
| 236 | m.add_backing(0x2001000, 0x3000); | ||
| 237 | m.apply(); | ||
| 238 | EXPECT(m.touched.size() == 2 && m.copy[200][0] == kArena + 0x2001800 && m.copy[201][0] == kArena + 0x2001800); | ||
| 239 | EXPECT(m.consistent()); | ||
| 240 | |||
| 241 | // The counter half on its own, and a refused alias copy: waiting on the copy's address, fixed when it is backed. | ||
| 242 | constexpr std::uint64_t title2 = 0x300000000000ull, unbacked = 0x3000000; | ||
| 243 | m.add_alias(title2, 0x10000, unbacked); | ||
| 244 | m.apply(); | ||
| 245 | m.write(300, {c, 0x40}, {title2 + 0x40, 4}); | ||
| 246 | EXPECT(m.copy[300][0] == kArena + c && m.copy[300][1] == 0 && m.records.state(300, 1) == ConsoleHeapSlotRecords::waiting); | ||
| 247 | m.add_backing(unbacked, 0x10000); | ||
| 248 | m.apply(); | ||
| 249 | EXPECT(m.copy[300][1] == kArena + unbacked + 0x40 && m.consistent()); | ||
| 250 | |||
| 251 | // A large range in a granule before the release: found through its span class. | ||
| 252 | m.add_backing(0x10000000, 0x400000); | ||
| 253 | m.apply(); | ||
| 254 | m.write(400, {0x10000000, 0x400000}); | ||
| 255 | m.release_backing(0x10000000); | ||
| 256 | m.apply(); | ||
| 257 | EXPECT(m.touched.size() == 1 && m.touched[0] == 400 && m.copy[400][0] == 0 && m.consistent()); | ||
| 258 | |||
| 259 | // The heap destroyed (its records with it): a new heap of the same size starts with none. | ||
| 260 | m.records.reset(4096); | ||
| 261 | m.release_backing(c); | ||
| 262 | m.apply(); | ||
| 263 | EXPECT(m.touched.empty() && m.records.recorded() == 0); | ||
| 264 | std::printf("cases: alias moved, removed and added again; overwritten and zeroed slots; partial overlap; two slots " | ||
| 265 | "on one backing; a buffer back; a refused alias copy backed later; a large range; a destroyed heap\n"); | ||
| 266 | return 0; | ||
| 267 | } | ||
| 268 | |||
| 269 | // Random writes, zeroes, releases, additions and alias changes; after each round of changes the copy must equal a full | ||
| 270 | // re-resolution, and the entries looked at must stay near what the changes touch. | ||
| 271 | int differential() { | ||
| 272 | std::mt19937_64 rng(0x5107); | ||
| 273 | constexpr std::size_t kSlots = 3000; | ||
| 274 | Model m(kSlots); | ||
| 275 | constexpr std::uint64_t kGranule = 0x10000; | ||
| 276 | std::vector<std::uint64_t> titles; | ||
| 277 | for (int i = 0; i < 6; ++i) titles.push_back(0x100000000000ull + std::uint64_t(i) * 0x100000); | ||
| 278 | const auto pick = [&](std::uint64_t n) { return std::uint64_t(rng() % n); }; | ||
| 279 | std::uint64_t looked = 0, touched = 0; | ||
| 280 | for (int round = 0; round < 400; ++round) { | ||
| 281 | for (int op = 0; op < 20; ++op) { | ||
| 282 | const auto slot = std::size_t(pick(kSlots)); | ||
| 283 | switch (pick(9)) { | ||
| 284 | case 0: case 1: case 2: { // a V# into an arena offset, one through an alias, or a counter half too | ||
| 285 | const auto span = 1 + pick(pick(4) ? 0x2000 : 0x80000); | ||
| 286 | Model::Words a{pick(2) ? pick(64) * kGranule / 2 + pick(0x800) : titles[pick(6)] + pick(0x80000), span}; | ||
| 287 | Model::Words b{}; | ||
| 288 | if (!pick(4)) b = {pick(64) * kGranule / 2, 4}; | ||
| 289 | m.write(slot, a, b); | ||
| 290 | break; | ||
| 291 | } | ||
| 292 | case 3: m.zero(slot); break; | ||
| 293 | case 4: { | ||
| 294 | const auto at = pick(64) * kGranule / 2; | ||
| 295 | const auto it = m.backings.find(kArena + at); | ||
| 296 | if (it == m.backings.end()) { | ||
| 297 | // Not over another backing. | ||
| 298 | const auto bytes = (1 + pick(8)) * kGranule / 4; | ||
| 299 | bool free = true; | ||
| 300 | for (const auto& [lo, hi] : m.backings) free &= !(lo < kArena + at + bytes && hi > kArena + at); | ||
| 301 | if (free) m.add_backing(at, bytes); | ||
| 302 | } else { | ||
| 303 | m.release_backing(at); | ||
| 304 | } | ||
| 305 | break; | ||
| 306 | } | ||
| 307 | case 5: case 6: { | ||
| 308 | const auto title = titles[pick(6)] + pick(4) * 0x20000; | ||
| 309 | m.add_alias(title, (1 + pick(4)) * 0x8000, pick(64) * kGranule / 2); | ||
| 310 | break; | ||
| 311 | } | ||
| 312 | case 7: | ||
| 313 | if (!m.aliases.empty()) { | ||
| 314 | auto it = m.aliases.begin(); | ||
| 315 | std::advance(it, std::ptrdiff_t(pick(m.aliases.size()))); | ||
| 316 | m.remove_alias(it->first); | ||
| 317 | } | ||
| 318 | break; | ||
| 319 | default: m.fix(slot); break; | ||
| 320 | } | ||
| 321 | } | ||
| 322 | m.apply(); | ||
| 323 | looked += m.looked; | ||
| 324 | touched += m.touched.size(); | ||
| 325 | if (!m.consistent()) { | ||
| 326 | std::fprintf(stderr, "round %d\n", round); | ||
| 327 | return 1; | ||
| 328 | } | ||
| 329 | } | ||
| 330 | EXPECT(m.records.recorded() > 0); | ||
| 331 | // The model's address space is a few MiB, so most changes touch most of it: this case checks results, not cost. | ||
| 332 | std::printf("differential: 400 rounds, copy equal to a full re-resolution after each; %llu entries looked at, " | ||
| 333 | "%llu slots fixed again, %zu halves recorded at the end\n", | ||
| 334 | static_cast<unsigned long long>(looked), static_cast<unsigned long long>(touched), | ||
| 335 | m.records.recorded()); | ||
| 336 | return 0; | ||
| 337 | } | ||
| 338 | |||
| 339 | } // namespace | ||
| 340 | |||
| 341 | int main() { | ||
| 342 | if (release_looks_at_its_slots_only()) return 1; | ||
| 343 | if (cases()) return 1; | ||
| 344 | if (differential()) return 1; | ||
| 345 | std::printf("console_heap_slot_records_test: ok\n"); | ||
| 346 | return 0; | ||
| 347 | } | ||
diff --git a/runtime/test/console_heap_vsharp_slots_test.cpp b/runtime/test/console_heap_vsharp_slots_test.cpp deleted file mode 100644 index ebb74be45..000000000 --- a/runtime/test/console_heap_vsharp_slots_test.cpp +++ /dev/null | |||
| @@ -1,259 +0,0 @@ | |||
| 1 | // Portable CPU-only unit test for leonida::ConsoleHeapVsharpSlots (runtime/src/console_heap_vsharp_slots.h). | ||
| 2 | // Verifies bit-for-bit equivalence with a linear scan of 32-byte descriptor slots, boundary handling, range clears, | ||
| 3 | // callback-time bit clearing (as in refresh_console_heap invalidation passes), and a 5.5 MiB heap stress check. | ||
| 4 | #include "../src/console_heap_vsharp_slots.h" | ||
| 5 | |||
| 6 | #include <array> | ||
| 7 | #include <cstdint> | ||
| 8 | #include <cstdio> | ||
| 9 | #include <cstring> | ||
| 10 | #include <vector> | ||
| 11 | |||
| 12 | #define EXPECT(condition) \ | ||
| 13 | do { \ | ||
| 14 | if (!(condition)) { \ | ||
| 15 | std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ | ||
| 16 | return 1; \ | ||
| 17 | } \ | ||
| 18 | } while (0) | ||
| 19 | |||
| 20 | namespace { | ||
| 21 | |||
| 22 | using leonida::ConsoleHeapVsharpSlots; | ||
| 23 | |||
| 24 | std::vector<std::size_t> collect(const ConsoleHeapVsharpSlots& slots) { | ||
| 25 | std::vector<std::size_t> out; | ||
| 26 | slots.for_each([&](std::size_t slot) { out.push_back(slot); }); | ||
| 27 | return out; | ||
| 28 | } | ||
| 29 | |||
| 30 | int test_predicate_exactness() { | ||
| 31 | // Primary buffer V#: top 2 bits of w[3] are 0, w[2] (num_records) != 0. | ||
| 32 | std::uint32_t primary[8] = {0x1000, 0x20, 64, 0x3fffffffu, 0, 0, 0, 0}; | ||
| 33 | EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(primary)); | ||
| 34 | |||
| 35 | // Counter-only buffer V#: w[2] == 0, w[6] != 0, top 2 bits of w[3] == 0. | ||
| 36 | std::uint32_t counter[8] = {0, 0, 0, 0, 0x2000, 0, 16, 0}; | ||
| 37 | EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(counter)); | ||
| 38 | |||
| 39 | // Empty / zeroed V#: w[2] == 0 and w[6] == 0. | ||
| 40 | std::uint32_t empty[8] = {0x1000, 0, 0, 0x00010000u, 0x2000, 0, 0, 0}; | ||
| 41 | EXPECT(!ConsoleHeapVsharpSlots::is_live_vsharp(empty)); | ||
| 42 | |||
| 43 | // Image T# (w[3] >> 30 != 0): must NOT be treated as a buffer V# even if w[2]/w[6] are non-zero. | ||
| 44 | for (std::uint32_t hi : {1u, 2u, 3u}) { | ||
| 45 | std::uint32_t tsharp[8] = {0x1000, 0, 128, (hi << 30) | 0x55u, 0, 0, 64, 0}; | ||
| 46 | EXPECT(!ConsoleHeapVsharpSlots::is_live_vsharp(tsharp)); | ||
| 47 | } | ||
| 48 | |||
| 49 | // not_tsharp zeroes lower 16 bytes (w[0..3] = 0) while leaving upper 16 bytes (w[4..7]): | ||
| 50 | // if w[6] is non-zero, predicate matches the legacy `!(w[3] >> 30) && (w[2] || w[6])` check. | ||
| 51 | std::uint32_t not_tsharp_with_hi[8] = {0, 0, 0, 0, 0, 0, 1, 0}; | ||
| 52 | EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(not_tsharp_with_hi)); | ||
| 53 | return 0; | ||
| 54 | } | ||
| 55 | |||
| 56 | int test_boundaries_and_ranges() { | ||
| 57 | // Zero-size heap. | ||
| 58 | ConsoleHeapVsharpSlots zero; | ||
| 59 | zero.reset(0); | ||
| 60 | EXPECT(zero.empty() && zero.slot_count() == 0 && zero.live_count() == 0); | ||
| 61 | zero.set(0, true); | ||
| 62 | zero.clear(0); | ||
| 63 | zero.clear_range(0, 10); | ||
| 64 | EXPECT(zero.empty() && !zero.test(0) && collect(zero).empty()); | ||
| 65 | |||
| 66 | // Word boundary sizes: 1, 63, 64, 65, 128, 129, 257. | ||
| 67 | for (std::size_t n : {std::size_t(1), std::size_t(63), std::size_t(64), std::size_t(65), std::size_t(128), | ||
| 68 | std::size_t(129), std::size_t(257)}) { | ||
| 69 | ConsoleHeapVsharpSlots s; | ||
| 70 | s.reset(n); | ||
| 71 | EXPECT(s.slot_count() == n && s.empty()); | ||
| 72 | // Out-of-range writes are ignored. | ||
| 73 | s.set(n, true); | ||
| 74 | s.set(n + 100, true); | ||
| 75 | EXPECT(s.empty() && !s.test(n)); | ||
| 76 | |||
| 77 | // Set every slot, check idempotency and exact ordering. | ||
| 78 | for (std::size_t i = 0; i < n; ++i) s.set(i, true); | ||
| 79 | s.set(0, true); | ||
| 80 | s.set(n - 1, true); | ||
| 81 | EXPECT(s.live_count() == n); | ||
| 82 | const auto all = collect(s); | ||
| 83 | EXPECT(all.size() == n); | ||
| 84 | for (std::size_t i = 0; i < n; ++i) EXPECT(all[i] == i && s.test(i)); | ||
| 85 | |||
| 86 | // Inverted / empty / past-end clear_range is a no-op. | ||
| 87 | s.clear_range(5, 5); | ||
| 88 | s.clear_range(10, 2); | ||
| 89 | s.clear_range(n, n + 64); | ||
| 90 | EXPECT(s.live_count() == n); | ||
| 91 | |||
| 92 | // Partial single-word and multi-word clear_range. | ||
| 93 | if (n >= 129) { | ||
| 94 | s.clear_range(3, 19); // within word 0 | ||
| 95 | s.clear_range(60, 128); // spans word 0 tail + all of word 1 | ||
| 96 | EXPECT(s.live_count() == n - 16 - 68); | ||
| 97 | EXPECT(s.test(2) && !s.test(3) && !s.test(18) && s.test(19)); | ||
| 98 | EXPECT(s.test(59) && !s.test(60) && !s.test(127) && s.test(128)); | ||
| 99 | } | ||
| 100 | |||
| 101 | // Clear past end clamps cleanly. | ||
| 102 | s.clear_range(0, n + 500); | ||
| 103 | EXPECT(s.empty() && s.live_count() == 0 && collect(s).empty()); | ||
| 104 | } | ||
| 105 | return 0; | ||
| 106 | } | ||
| 107 | |||
| 108 | int test_in_place_invalidation_mutation() { | ||
| 109 | // Mirrors refresh_console_heap: for_each visits each live V# slot and calls fix_console_slot, which may clear | ||
| 110 | // that slot's bit when its backing buffer was released. | ||
| 111 | ConsoleHeapVsharpSlots s; | ||
| 112 | s.reset(260); | ||
| 113 | const std::vector<std::size_t> initial = {0, 1, 62, 63, 64, 65, 127, 128, 191, 255, 259}; | ||
| 114 | for (std::size_t slot : initial) s.set(slot, true); | ||
| 115 | EXPECT(s.live_count() == initial.size()); | ||
| 116 | |||
| 117 | std::vector<std::size_t> visited; | ||
| 118 | s.for_each([&](std::size_t slot) { | ||
| 119 | visited.push_back(slot); | ||
| 120 | // Simulate releasing every even-numbered slot during the invalidation pass. | ||
| 121 | if ((slot & 1u) == 0) s.set(slot, false); | ||
| 122 | }); | ||
| 123 | EXPECT(visited == initial); | ||
| 124 | |||
| 125 | std::vector<std::size_t> remaining; | ||
| 126 | for (std::size_t slot : initial) | ||
| 127 | if ((slot & 1u) != 0) remaining.push_back(slot); | ||
| 128 | EXPECT(s.live_count() == remaining.size()); | ||
| 129 | EXPECT(collect(s) == remaining); | ||
| 130 | |||
| 131 | // Clear the remaining slots and confirm empty fast path visits nothing. | ||
| 132 | s.for_each([&](std::size_t slot) { s.clear(slot); }); | ||
| 133 | EXPECT(s.empty() && collect(s).empty()); | ||
| 134 | return 0; | ||
| 135 | } | ||
| 136 | |||
| 137 | int test_differential_equivalence_against_linear_copy() { | ||
| 138 | // Differential model: maintain a synthetic 32-byte-per-slot `heap.copy` buffer alongside ConsoleHeapVsharpSlots | ||
| 139 | // across thousands of random writes, deferred zeroes, page-range zeroes, and invalidation passes. | ||
| 140 | constexpr std::size_t kSlots = 1029; | ||
| 141 | std::vector<std::array<std::uint32_t, 8>> gpu_copy(kSlots); | ||
| 142 | for (auto& slot : gpu_copy) slot.fill(0); | ||
| 143 | |||
| 144 | ConsoleHeapVsharpSlots tracked; | ||
| 145 | tracked.reset(kSlots); | ||
| 146 | |||
| 147 | auto linear_scan = [&] { | ||
| 148 | std::vector<std::size_t> expected; | ||
| 149 | for (std::size_t i = 0; i < kSlots; ++i) | ||
| 150 | if (ConsoleHeapVsharpSlots::is_live_vsharp(gpu_copy[i].data())) expected.push_back(i); | ||
| 151 | return expected; | ||
| 152 | }; | ||
| 153 | |||
| 154 | std::uint64_t rng = 0x9e3779b97f4a7c15ull; | ||
| 155 | auto next_u32 = [&]() -> std::uint32_t { | ||
| 156 | rng ^= rng >> 12; | ||
| 157 | rng ^= rng << 25; | ||
| 158 | rng ^= rng >> 27; | ||
| 159 | return static_cast<std::uint32_t>((rng * 0x2545f4914f6cdd1dull) >> 32); | ||
| 160 | }; | ||
| 161 | |||
| 162 | for (unsigned step = 0; step < 4000; ++step) { | ||
| 163 | const unsigned op = next_u32() % 10; | ||
| 164 | if (op < 6) { | ||
| 165 | // Simulate fix_console_slot writing a descriptor to heap.copy. | ||
| 166 | const std::size_t slot = next_u32() % kSlots; | ||
| 167 | std::array<std::uint32_t, 8> w{}; | ||
| 168 | const unsigned kind = next_u32() % 5; | ||
| 169 | if (kind == 0) { | ||
| 170 | // Live primary V# | ||
| 171 | w[0] = next_u32(); | ||
| 172 | w[2] = (next_u32() % 256) + 1; | ||
| 173 | w[3] = next_u32() & 0x3fffffffu; | ||
| 174 | } else if (kind == 1) { | ||
| 175 | // Live counter V# only | ||
| 176 | w[6] = (next_u32() % 64) + 1; | ||
| 177 | } else if (kind == 2) { | ||
| 178 | // Empty V# (zero records) | ||
| 179 | w[0] = 0; | ||
| 180 | w[2] = 0; | ||
| 181 | w[3] = next_u32() & 0x3fffffffu; | ||
| 182 | w[6] = 0; | ||
| 183 | } else if (kind == 3) { | ||
| 184 | // Image T# | ||
| 185 | w[2] = 128; | ||
| 186 | w[3] = (2u << 30) | (next_u32() & 0x3fffffffu); | ||
| 187 | w[6] = 32; | ||
| 188 | } else { | ||
| 189 | // not_tsharp (lower 16B zeroed, upper 16B arbitrary) | ||
| 190 | w[4] = next_u32(); | ||
| 191 | w[6] = (next_u32() & 1u) ? 7u : 0u; | ||
| 192 | } | ||
| 193 | gpu_copy[slot] = w; | ||
| 194 | tracked.set(slot, ConsoleHeapVsharpSlots::is_live_vsharp(w.data())); | ||
| 195 | } else if (op < 8) { | ||
| 196 | // Simulate fix_console_slots deferred zeroing. | ||
| 197 | const std::size_t slot = next_u32() % kSlots; | ||
| 198 | gpu_copy[slot].fill(0); | ||
| 199 | tracked.clear(slot); | ||
| 200 | } else if (op == 8) { | ||
| 201 | // Simulate for_each_zeroed (both page-aligned 128-slot and arbitrary sub-ranges). | ||
| 202 | const std::size_t first = next_u32() % (kSlots + 16); | ||
| 203 | const std::size_t len = (next_u32() % 200); | ||
| 204 | const std::size_t end = first + len; | ||
| 205 | for (std::size_t i = first; i < end && i < kSlots; ++i) gpu_copy[i].fill(0); | ||
| 206 | tracked.clear_range(first, end); | ||
| 207 | } else { | ||
| 208 | // Simulate refresh_console_heap invalidation pass clearing a subset of visited slots. | ||
| 209 | const std::vector<std::size_t> expected = linear_scan(); | ||
| 210 | std::vector<std::size_t> got; | ||
| 211 | tracked.for_each([&](std::size_t slot) { | ||
| 212 | got.push_back(slot); | ||
| 213 | if ((slot % 3) == 0) { | ||
| 214 | gpu_copy[slot].fill(0); | ||
| 215 | tracked.set(slot, false); | ||
| 216 | } | ||
| 217 | }); | ||
| 218 | EXPECT(got == expected); | ||
| 219 | } | ||
| 220 | |||
| 221 | if ((step & 63) == 63) { | ||
| 222 | const std::vector<std::size_t> expected = linear_scan(); | ||
| 223 | EXPECT(tracked.live_count() == expected.size()); | ||
| 224 | EXPECT(collect(tracked) == expected); | ||
| 225 | } | ||
| 226 | } | ||
| 227 | EXPECT(collect(tracked) == linear_scan()); | ||
| 228 | return 0; | ||
| 229 | } | ||
| 230 | |||
| 231 | int test_retail_sized_heap_sparse_scan() { | ||
| 232 | // 5.5 MiB resource heap = 180,224 32-byte slots (matching retail console descriptor heap). | ||
| 233 | constexpr std::size_t kRetailSlots = (5632u * 1024u) / 32u; | ||
| 234 | ConsoleHeapVsharpSlots tracked; | ||
| 235 | tracked.reset(kRetailSlots); | ||
| 236 | |||
| 237 | const std::vector<std::size_t> hot = {0, 63, 64, 4095, 4096, 65536, 131072, kRetailSlots - 1}; | ||
| 238 | for (std::size_t slot : hot) tracked.set(slot, true); | ||
| 239 | EXPECT(tracked.live_count() == hot.size()); | ||
| 240 | EXPECT(collect(tracked) == hot); | ||
| 241 | |||
| 242 | // Zero a 4 KiB page (128 slots) containing slots 4096..4223. | ||
| 243 | tracked.clear_range(4096, 4096 + 128); | ||
| 244 | EXPECT(!tracked.test(4096) && tracked.test(4095)); | ||
| 245 | EXPECT(tracked.live_count() == hot.size() - 1); | ||
| 246 | return 0; | ||
| 247 | } | ||
| 248 | |||
| 249 | } // namespace | ||
| 250 | |||
| 251 | int main() { | ||
| 252 | if (test_predicate_exactness()) return 1; | ||
| 253 | if (test_boundaries_and_ranges()) return 1; | ||
| 254 | if (test_in_place_invalidation_mutation()) return 1; | ||
| 255 | if (test_differential_equivalence_against_linear_copy()) return 1; | ||
| 256 | if (test_retail_sized_heap_sparse_scan()) return 1; | ||
| 257 | std::printf("console_heap_vsharp_slots_test: ok\n"); | ||
| 258 | return 0; | ||
| 259 | } | ||
diff --git a/runtime/test/cs_group_marker_spv.h b/runtime/test/cs_group_marker_spv.h new file mode 100644 index 000000000..6cd135cfe --- /dev/null +++ b/runtime/test/cs_group_marker_spv.h | |||
| @@ -0,0 +1,43 @@ | |||
| 1 | // Generated with glslangValidator -V --target-env vulkan1.2 -Os --spirv-val cs_group_marker.comp | ||
| 2 | #pragma once | ||
| 3 | #include <cstdint> | ||
| 4 | namespace leonida { | ||
| 5 | inline constexpr std::uint32_t cs_group_marker_spirv[] = { | ||
| 6 | 0x07230203u, 0x00010500u, 0x0008000bu, 0x0000002du, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, | ||
| 7 | 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, | ||
| 8 | 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000bu, | ||
| 9 | 0x0000001du, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000001u, 0x00000001u, 0x00000001u, 0x00030003u, | ||
| 10 | 0x00000002u, 0x000001ccu, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, | ||
| 11 | 0x0065636eu, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00060005u, 0x0000000bu, 0x575f6c67u, | ||
| 12 | 0x476b726fu, 0x70756f72u, 0x00004449u, 0x00040005u, 0x00000019u, 0x61726150u, 0x0000736du, 0x00050006u, | ||
| 13 | 0x00000019u, 0x00000000u, 0x6b72616du, 0x00000073u, 0x00050006u, 0x00000019u, 0x00000001u, 0x756f7267u, | ||
| 14 | 0x00007370u, 0x00040005u, 0x0000001bu, 0x6b72614du, 0x00000073u, 0x00050006u, 0x0000001bu, 0x00000000u, | ||
| 15 | 0x61746164u, 0x00000000u, 0x00030005u, 0x0000001du, 0x00000070u, 0x00040047u, 0x0000000bu, 0x0000000bu, | ||
| 16 | 0x0000001au, 0x00030047u, 0x00000019u, 0x00000002u, 0x00050048u, 0x00000019u, 0x00000000u, 0x00000023u, | ||
| 17 | 0x00000000u, 0x00050048u, 0x00000019u, 0x00000001u, 0x00000023u, 0x00000008u, 0x00040047u, 0x0000001au, | ||
| 18 | 0x00000006u, 0x00000004u, 0x00030047u, 0x0000001bu, 0x00000002u, 0x00050048u, 0x0000001bu, 0x00000000u, | ||
| 19 | 0x00000023u, 0x00000000u, 0x00040047u, 0x0000002cu, 0x0000000bu, 0x00000019u, 0x00020013u, 0x00000002u, | ||
| 20 | 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000000u, 0x00040017u, | ||
| 21 | 0x00000009u, 0x00000006u, 0x00000003u, 0x00040020u, 0x0000000au, 0x00000001u, 0x00000009u, 0x0004003bu, | ||
| 22 | 0x0000000au, 0x0000000bu, 0x00000001u, 0x0004002bu, 0x00000006u, 0x0000000cu, 0x00000000u, 0x00040020u, | ||
| 23 | 0x0000000du, 0x00000001u, 0x00000006u, 0x0004002bu, 0x00000006u, 0x00000010u, 0x00000001u, 0x0004002bu, | ||
| 24 | 0x00000006u, 0x00000014u, 0x00000002u, 0x00030027u, 0x00000018u, 0x000014e5u, 0x0004001eu, 0x00000019u, | ||
| 25 | 0x00000018u, 0x00000006u, 0x0003001du, 0x0000001au, 0x00000006u, 0x0003001eu, 0x0000001bu, 0x0000001au, | ||
| 26 | 0x00040020u, 0x00000018u, 0x000014e5u, 0x0000001bu, 0x00040020u, 0x0000001cu, 0x00000009u, 0x00000019u, | ||
| 27 | 0x0004003bu, 0x0000001cu, 0x0000001du, 0x00000009u, 0x00040015u, 0x0000001eu, 0x00000020u, 0x00000001u, | ||
| 28 | 0x0004002bu, 0x0000001eu, 0x0000001fu, 0x00000000u, 0x00040020u, 0x00000020u, 0x00000009u, 0x00000018u, | ||
| 29 | 0x0004002bu, 0x0000001eu, 0x00000024u, 0x00000001u, 0x00040020u, 0x00000025u, 0x00000009u, 0x00000006u, | ||
| 30 | 0x00040020u, 0x00000029u, 0x000014e5u, 0x00000006u, 0x0006002cu, 0x00000009u, 0x0000002cu, 0x00000010u, | ||
| 31 | 0x00000010u, 0x00000010u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, | ||
| 32 | 0x00000005u, 0x00050041u, 0x0000000du, 0x0000000eu, 0x0000000bu, 0x0000000cu, 0x0004003du, 0x00000006u, | ||
| 33 | 0x0000000fu, 0x0000000eu, 0x00050041u, 0x0000000du, 0x00000011u, 0x0000000bu, 0x00000010u, 0x0004003du, | ||
| 34 | 0x00000006u, 0x00000012u, 0x00000011u, 0x00050080u, 0x00000006u, 0x00000013u, 0x0000000fu, 0x00000012u, | ||
| 35 | 0x00050041u, 0x0000000du, 0x00000015u, 0x0000000bu, 0x00000014u, 0x0004003du, 0x00000006u, 0x00000016u, | ||
| 36 | 0x00000015u, 0x00050080u, 0x00000006u, 0x00000017u, 0x00000013u, 0x00000016u, 0x00050041u, 0x00000020u, | ||
| 37 | 0x00000021u, 0x0000001du, 0x0000001fu, 0x0004003du, 0x00000018u, 0x00000022u, 0x00000021u, 0x00050041u, | ||
| 38 | 0x00000025u, 0x00000026u, 0x0000001du, 0x00000024u, 0x0004003du, 0x00000006u, 0x00000027u, 0x00000026u, | ||
| 39 | 0x0007000cu, 0x00000006u, 0x00000028u, 0x00000001u, 0x00000026u, 0x00000017u, 0x00000027u, 0x00060041u, | ||
| 40 | 0x00000029u, 0x0000002au, 0x00000022u, 0x0000001fu, 0x00000028u, 0x000700eau, 0x00000006u, 0x0000002bu, | ||
| 41 | 0x0000002au, 0x00000010u, 0x0000000cu, 0x00000010u, 0x000100fdu, 0x00010038u, | ||
| 42 | }; | ||
| 43 | } // namespace leonida | ||
diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 7848ac864..48a2ef208 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp | |||
| @@ -1438,6 +1438,141 @@ int check_pending_stream_views(ID3D12Device* device) { | |||
| 1438 | return 0; | 1438 | return 0; |
| 1439 | } | 1439 | } |
| 1440 | 1440 | ||
| 1441 | namespace { | ||
| 1442 | std::atomic<DWORD> g_view_av_thread{0}; | ||
| 1443 | std::atomic<unsigned> g_view_avs{0}; | ||
| 1444 | |||
| 1445 | LONG CALLBACK count_view_av(PEXCEPTION_POINTERS info) { | ||
| 1446 | if (info && info->ExceptionRecord && info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && | ||
| 1447 | GetCurrentThreadId() == g_view_av_thread.load(std::memory_order_relaxed)) { | ||
| 1448 | g_view_avs.fetch_add(1, std::memory_order_relaxed); | ||
| 1449 | } | ||
| 1450 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 1451 | } | ||
| 1452 | } // namespace | ||
| 1453 | |||
| 1454 | // Map changes reported to title_memory_map between submissions must both retire a cached readable answer before a | ||
| 1455 | // synchronous slot-70 view hashes decommitted pages, and wake a pending slot-70 view without waiting for a submission. | ||
| 1456 | int check_placed_view_map_changes(ID3D12Device* device) { | ||
| 1457 | const char* who = "slot-70 view map changes"; | ||
| 1458 | if (!rt::d3d12::bindless_set_layout(device)) return 0; | ||
| 1459 | GpuReader gpu; | ||
| 1460 | EXPECT(!gpu.init(device, 4096)); | ||
| 1461 | auto env_is = [](const char* name, const char* want) { | ||
| 1462 | char buf[16]{}; | ||
| 1463 | const DWORD n = GetEnvironmentVariableA(name, buf, sizeof(buf)); | ||
| 1464 | return n > 0 && n < sizeof(buf) && std::strcmp(buf, want) == 0; | ||
| 1465 | }; | ||
| 1466 | auto index = [&](const leonida::gfx10::ImageWords& descriptor) { | ||
| 1467 | std::uint32_t key[8]; | ||
| 1468 | std::memcpy(key, descriptor.data(), sizeof(key)); | ||
| 1469 | return rt::d3d12::bindless_hash_lookup(device, key); | ||
| 1470 | }; | ||
| 1471 | |||
| 1472 | // 1. Committed >256 KiB texture -> decommit interior 64 KiB + map::changed -> synchronous view takes zero AVs. | ||
| 1473 | { | ||
| 1474 | constexpr SIZE_T bytes = 512 * 1024; | ||
| 1475 | auto* pages = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | ||
| 1476 | EXPECT(pages); | ||
| 1477 | std::memset(pages, 0x5a, bytes); | ||
| 1478 | D3D12_RESOURCE_DESC desc{}; | ||
| 1479 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | ||
| 1480 | desc.Width = 512; | ||
| 1481 | desc.Height = 1024; | ||
| 1482 | desc.DepthOrArraySize = desc.MipLevels = 1; | ||
| 1483 | desc.SampleDesc.Count = 1; | ||
| 1484 | desc.Format = DXGI_FORMAT_R8_UNORM; | ||
| 1485 | desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; | ||
| 1486 | D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; | ||
| 1487 | srv.Format = desc.Format; | ||
| 1488 | srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; | ||
| 1489 | srv.Texture2D.MipLevels = 1; | ||
| 1490 | srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; | ||
| 1491 | leonida::gfx10::ImageWords slot{}; | ||
| 1492 | auto write_view = [&](UINT mapping) { | ||
| 1493 | srv.Shader4ComponentMapping = mapping; | ||
| 1494 | std::array<UINT, 14> resource{}; | ||
| 1495 | std::array<UINT, 16> words{}; | ||
| 1496 | std::memcpy(resource.data(), &desc, sizeof(desc)); | ||
| 1497 | std::memcpy(words.data(), &srv, sizeof(srv)); | ||
| 1498 | return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), | ||
| 1499 | reinterpret_cast<UINT64>(pages), | ||
| 1500 | {reinterpret_cast<SIZE_T>(slot.data())}); | ||
| 1501 | }; | ||
| 1502 | EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING)); | ||
| 1503 | EXPECT(index(slot) != 0); | ||
| 1504 | |||
| 1505 | EXPECT(VirtualFree(pages + 65536, 65536, MEM_DECOMMIT) != FALSE); | ||
| 1506 | leonida::title_memory_map::changed(pages + 65536, 65536); | ||
| 1507 | |||
| 1508 | g_view_avs.store(0, std::memory_order_relaxed); | ||
| 1509 | g_view_av_thread.store(GetCurrentThreadId(), std::memory_order_relaxed); | ||
| 1510 | PVOID veh = AddVectoredExceptionHandler(1, &count_view_av); | ||
| 1511 | EXPECT(veh != nullptr); | ||
| 1512 | const bool wrote_after_unmap = write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0)); | ||
| 1513 | RemoveVectoredExceptionHandler(veh); | ||
| 1514 | g_view_av_thread.store(0, std::memory_order_relaxed); | ||
| 1515 | EXPECT(wrote_after_unmap); | ||
| 1516 | EXPECT(g_view_avs.load(std::memory_order_relaxed) == 0); | ||
| 1517 | |||
| 1518 | EXPECT(VirtualAlloc(pages + 65536, 65536, MEM_COMMIT, PAGE_READWRITE) == pages + 65536); | ||
| 1519 | leonida::title_memory_map::changed(pages + 65536, 65536); | ||
| 1520 | Ref<ID3D12Resource> placement; | ||
| 1521 | desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; | ||
| 1522 | EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&placement.p)), S_OK); | ||
| 1523 | placement.p->Release(); | ||
| 1524 | placement.p = nullptr; | ||
| 1525 | VirtualFree(pages, 0, MEM_RELEASE); | ||
| 1526 | } | ||
| 1527 | |||
| 1528 | // 2. Reserved texture -> commit + map::changed (no texel write note, no submission) -> synchronous view publishes. | ||
| 1529 | { | ||
| 1530 | constexpr SIZE_T bytes = 65536; | ||
| 1531 | void* pages = VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS); | ||
| 1532 | EXPECT(pages); | ||
| 1533 | D3D12_RESOURCE_DESC desc{}; | ||
| 1534 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | ||
| 1535 | desc.Width = 32; | ||
| 1536 | desc.Height = 8; | ||
| 1537 | desc.DepthOrArraySize = desc.MipLevels = 1; | ||
| 1538 | desc.SampleDesc.Count = 1; | ||
| 1539 | desc.Format = DXGI_FORMAT_R8_UNORM; | ||
| 1540 | desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; | ||
| 1541 | D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; | ||
| 1542 | srv.Format = desc.Format; | ||
| 1543 | srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; | ||
| 1544 | srv.Texture2D.MipLevels = 1; | ||
| 1545 | leonida::gfx10::ImageWords first{}, second{}; | ||
| 1546 | auto write_view = [&](UINT mapping, leonida::gfx10::ImageWords& out) { | ||
| 1547 | srv.Shader4ComponentMapping = mapping; | ||
| 1548 | std::array<UINT, 14> resource{}; | ||
| 1549 | std::array<UINT, 16> words{}; | ||
| 1550 | std::memcpy(resource.data(), &desc, sizeof(desc)); | ||
| 1551 | std::memcpy(words.data(), &srv, sizeof(srv)); | ||
| 1552 | return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), | ||
| 1553 | reinterpret_cast<UINT64>(pages), | ||
| 1554 | {reinterpret_cast<SIZE_T>(out.data())}); | ||
| 1555 | }; | ||
| 1556 | EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, first)); | ||
| 1557 | if (!env_is("LEONIDA_TITLE_IMAGE_DEFER", "0")) EXPECT(!index(first)); | ||
| 1558 | |||
| 1559 | EXPECT(VirtualAlloc(pages, bytes, MEM_COMMIT, PAGE_READWRITE) == pages); | ||
| 1560 | std::memset(pages, 0x33, bytes); | ||
| 1561 | leonida::title_memory_map::changed(pages, bytes); | ||
| 1562 | |||
| 1563 | EXPECT(write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0), second)); | ||
| 1564 | if (!env_is("LEONIDA_TITLE_FILL_ASYNC", "1")) EXPECT(index(first) && index(second)); | ||
| 1565 | |||
| 1566 | Ref<ID3D12Resource> placement; | ||
| 1567 | desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; | ||
| 1568 | EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&placement.p)), S_OK); | ||
| 1569 | placement.p->Release(); | ||
| 1570 | placement.p = nullptr; | ||
| 1571 | VirtualFree(pages, 0, MEM_RELEASE); | ||
| 1572 | } | ||
| 1573 | return 0; | ||
| 1574 | } | ||
| 1575 | |||
| 1441 | // A persistent Map can become readable without notifying xmem or calling Map a second time. | 1576 | // A persistent Map can become readable without notifying xmem or calling Map a second time. |
| 1442 | int check_mapped_plane(ID3D12Device* device) { | 1577 | int check_mapped_plane(ID3D12Device* device) { |
| 1443 | const char* who = "persistent slot-133 plane"; | 1578 | const char* who = "persistent slot-133 plane"; |
| @@ -2169,6 +2304,7 @@ int main(int argc, char** argv) { | |||
| 2169 | if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p); | 2304 | if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p); |
| 2170 | if (vk.host_image_copy) { | 2305 | if (vk.host_image_copy) { |
| 2171 | failures += check_pending_stream_views(ours.p); | 2306 | failures += check_pending_stream_views(ours.p); |
| 2307 | failures += check_placed_view_map_changes(ours.p); | ||
| 2172 | failures += check_shared_bc_placements(ours.p); | 2308 | failures += check_shared_bc_placements(ours.p); |
| 2173 | failures += check_mapped_plane(ours.p); | 2309 | failures += check_mapped_plane(ours.p); |
| 2174 | failures += check_mapped_bc_array(ours.p); | 2310 | failures += check_mapped_bc_array(ours.p); |
| @@ -2179,6 +2315,7 @@ int main(int argc, char** argv) { | |||
| 2179 | no_host_copy.host_image_copy = false; | 2315 | no_host_copy.host_image_copy = false; |
| 2180 | Ref<ID3D12Device> staged; | 2316 | Ref<ID3D12Device> staged; |
| 2181 | if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; | 2317 | if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; |
| 2318 | failures += check_placed_view_map_changes(staged.p); | ||
| 2182 | failures += check_mapped_plane(staged.p); | 2319 | failures += check_mapped_plane(staged.p); |
| 2183 | failures += check_mapped_bc_array(staged.p); | 2320 | failures += check_mapped_bc_array(staged.p); |
| 2184 | } | 2321 | } |
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..90eddc66a 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. | ||
| 518 | struct 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. | ||
| 528 | int 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. | ||
| 558 | int 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 | |||
| 635 | int 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 | |||
| 516 | void remove_test_pair(std::uintptr_t gpu, std::uintptr_t cpu) { | 703 | void 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); |
| @@ -978,6 +1165,59 @@ int check_rebound_tables(Context& c, ID3D12RootSignature* narrow, bool mirror, b | |||
| 978 | return 0; | 1165 | return 0; |
| 979 | } | 1166 | } |
| 980 | 1167 | ||
| 1168 | // Two slot-133 shadows over the same title page share one tracker and its sums (LEONIDA_SHADOW_KEEP, src/ | ||
| 1169 | // shadow_keep.h). A is copied with the title's byte at 1; the byte becomes 2 and B is made over the page, so B's first | ||
| 1170 | // copy holds 2; the byte goes back to 1 and a submission refreshes both. Both copies must hold 1, with the flag on or | ||
| 1171 | // off: B's first copy brings its pieces to the sums, or the sums still read 1 and B keeps 2 (found by lixonik). | ||
| 1172 | int check_shadow_keep_refill(Context& c) { | ||
| 1173 | constexpr UINT64 kPage = 4096, kAt = 16; // the byte: page 1 of A, page 0 of B | ||
| 1174 | auto* pages = static_cast<std::uint8_t*>( | ||
| 1175 | VirtualAlloc(nullptr, kPages, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | ||
| 1176 | EXPECT(pages); | ||
| 1177 | pages[kPage + kAt] = 1; | ||
| 1178 | const D3D12_RESOURCE_DESC desc = buffer_desc(2 * kPage); | ||
| 1179 | Ref<ID3D12Resource> a, b, readback; | ||
| 1180 | EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu, | ||
| 1181 | IID_PPV_ARGS(&a.p)))); | ||
| 1182 | EXPECT(rt::d3d12::title_shadow_buffer(a.p)); | ||
| 1183 | pages[kPage + kAt] = 2; | ||
| 1184 | EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, pages + kPage, desc, 0xFFFFFFFFu, | ||
| 1185 | IID_PPV_ARGS(&b.p)))); | ||
| 1186 | EXPECT(rt::d3d12::title_shadow_buffer(b.p)); | ||
| 1187 | pages[kPage + kAt] = 1; | ||
| 1188 | |||
| 1189 | const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; | ||
| 1190 | const auto readback_desc = buffer_desc(2 * kBytes); | ||
| 1191 | EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, | ||
| 1192 | D3D12_RESOURCE_STATE_COPY_DEST, nullptr, | ||
| 1193 | IID_PPV_ARGS(&readback.p)))); | ||
| 1194 | Ref<ID3D12CommandAllocator> allocator; | ||
| 1195 | Ref<ID3D12GraphicsCommandList> list; | ||
| 1196 | EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); | ||
| 1197 | EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, | ||
| 1198 | IID_PPV_ARGS(&list.p)))); | ||
| 1199 | list->CopyBufferRegion(readback.p, 0, a.p, kPage, kBytes); | ||
| 1200 | list->CopyBufferRegion(readback.p, kBytes, b.p, 0, kBytes); | ||
| 1201 | EXPECT(list->Close() == S_OK); | ||
| 1202 | ID3D12CommandList* lists[] = {list.p}; | ||
| 1203 | c.queue->ExecuteCommandLists(1, lists); // the refresh, then the copies | ||
| 1204 | EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); | ||
| 1205 | EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value))); | ||
| 1206 | EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr))); | ||
| 1207 | void* mapped = nullptr; | ||
| 1208 | EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); | ||
| 1209 | const std::uint8_t got_a = static_cast<const std::uint8_t*>(mapped)[kAt]; | ||
| 1210 | const std::uint8_t got_b = static_cast<const std::uint8_t*>(mapped)[kBytes + kAt]; | ||
| 1211 | readback->Unmap(0, nullptr); | ||
| 1212 | std::printf("shadow keep refill: A holds %u, B holds %u (the title's byte is 1)\n", got_a, got_b); | ||
| 1213 | EXPECT(got_a == 1); | ||
| 1214 | EXPECT(got_b == 1); | ||
| 1215 | a.reset(); | ||
| 1216 | b.reset(); | ||
| 1217 | VirtualFree(pages, 0, MEM_RELEASE); | ||
| 1218 | return 0; | ||
| 1219 | } | ||
| 1220 | |||
| 981 | } // namespace | 1221 | } // namespace |
| 982 | 1222 | ||
| 983 | int main(int argc, char** argv) { | 1223 | int main(int argc, char** argv) { |
| @@ -987,6 +1227,9 @@ int main(int argc, char** argv) { | |||
| 987 | const bool api_copy = api_copy_off || (argc == 2 && std::strcmp(argv[1], "--api-descriptor-copy") == 0); | 1227 | 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); | 1228 | 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; | 1229 | const bool window_cap = argc == 2 && std::strcmp(argv[1], "--window-cap") == 0; |
| 1230 | const bool window_write_back = argc == 2 && std::strcmp(argv[1], "--window-writeback") == 0; | ||
| 1231 | const bool placed_write_back = argc == 2 && std::strcmp(argv[1], "--placed-writeback") == 0; | ||
| 1232 | const bool keep_refill = argc == 2 && std::strcmp(argv[1], "--shadow-keep-refill") == 0; | ||
| 990 | if (window_cap) { | 1233 | if (window_cap) { |
| 991 | const char* cap = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); | 1234 | const char* cap = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); |
| 992 | if (!cap || std::strcmp(cap, "0")) { | 1235 | if (!cap || std::strcmp(cap, "0")) { |
| @@ -1101,6 +1344,33 @@ 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"); | 1344 | std::printf("title memory past the window cap: the views were zero-size and the shader read zeros\n"); |
| 1102 | return 0; | 1345 | return 0; |
| 1103 | } | 1346 | } |
| 1347 | if (placed_write_back) { | ||
| 1348 | if (check_placed_write_back(c, geometry)) return 1; | ||
| 1349 | if (d.validation_errors()) { | ||
| 1350 | std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); | ||
| 1351 | return 1; | ||
| 1352 | } | ||
| 1353 | std::printf("title-placed buffer write back: the GPU's writes reached the title's pages\n"); | ||
| 1354 | return 0; | ||
| 1355 | } | ||
| 1356 | if (keep_refill) { | ||
| 1357 | if (check_shadow_keep_refill(c)) return 1; | ||
| 1358 | if (d.validation_errors()) { | ||
| 1359 | std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); | ||
| 1360 | return 1; | ||
| 1361 | } | ||
| 1362 | return 0; | ||
| 1363 | } | ||
| 1364 | if (window_write_back) { | ||
| 1365 | if (check_window_write_back(c, geometry)) return 1; | ||
| 1366 | if (d.validation_errors()) { | ||
| 1367 | std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); | ||
| 1368 | return 1; | ||
| 1369 | } | ||
| 1370 | std::printf("title window write back: the GPU's writes reached the title's pages and the title's own " | ||
| 1371 | "words won\n"); | ||
| 1372 | return 0; | ||
| 1373 | } | ||
| 1104 | if (geometry && check_declined_imports(c)) return 1; | 1374 | if (geometry && check_declined_imports(c)) return 1; |
| 1105 | if (geometry && check_import_over_shadow(c)) return 1; | 1375 | if (geometry && check_import_over_shadow(c)) return 1; |
| 1106 | if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; | 1376 | 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_unmapped_vsharp_test.cpp b/runtime/test/d3d12_unmapped_vsharp_test.cpp index 2e072ce40..1cb0b7c23 100644 --- a/runtime/test/d3d12_unmapped_vsharp_test.cpp +++ b/runtime/test/d3d12_unmapped_vsharp_test.cpp | |||
| @@ -232,8 +232,9 @@ int check_console_heap(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fe | |||
| 232 | EXPECT(!(copy[3][0] | copy[3][1] | copy[3][2] | copy[3][3])); // the data slot's descriptor half is null | 232 | EXPECT(!(copy[3][0] | copy[3][1] | copy[3][2] | copy[3][3])); // the data slot's descriptor half is null |
| 233 | for (int i = 0; i < 4; ++i) EXPECT(!std::memcmp(title + i * kDescriptor, before[i], kDescriptor)); | 233 | for (int i = 0; i < 4; ++i) EXPECT(!std::memcmp(title + i * kDescriptor, before[i], kDescriptor)); |
| 234 | 234 | ||
| 235 | // 128 cold descriptors share one absent range. Publishing its alias leaves the title bytes | 235 | // 128 descriptors wait on one absent range; the title's bytes never change. Publishing its alias fixes every one |
| 236 | // unchanged. Only the bounded round-robin probes should discover it in the first 64 submits. | 236 | // of them at the next submission (the heap's slot records: an addition over a waiting V#), not one round-robin |
| 237 | // probe at a time. | ||
| 237 | Ref<ID3D12CommandAllocator> allocator; | 238 | Ref<ID3D12CommandAllocator> allocator; |
| 238 | Ref<ID3D12GraphicsCommandList> list; | 239 | Ref<ID3D12GraphicsCommandList> list; |
| 239 | EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); | 240 | EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); |
| @@ -241,23 +242,70 @@ int check_console_heap(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fe | |||
| 241 | IID_PPV_ARGS(&list.p)))); | 242 | IID_PPV_ARGS(&list.p)))); |
| 242 | EXPECT(SUCCEEDED(list->Close())); | 243 | EXPECT(SUCCEEDED(list->Close())); |
| 243 | ID3D12CommandList* lists[] = {list.p}; | 244 | ID3D12CommandList* lists[] = {list.p}; |
| 244 | for (unsigned pass = 0; pass < 64; ++pass) { | 245 | const auto submit = [&] { |
| 245 | if (pass == 1) leonida::title_va_aliases().add(unmapped, kViewBytes, b.arena_va); | ||
| 246 | queue->ExecuteCommandLists(1, lists); | 246 | queue->ExecuteCommandLists(1, lists); |
| 247 | EXPECT(SUCCEEDED(queue->Signal(fence, ++fence_value))); | 247 | return SUCCEEDED(queue->Signal(fence, ++fence_value)) && |
| 248 | EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr))); | 248 | SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr)); |
| 249 | } | 249 | }; |
| 250 | const auto count_restored = [&](unsigned& restored) { | ||
| 251 | restored = 0; | ||
| 252 | for (unsigned slot = 0; slot < 131; ++slot) { | ||
| 253 | if (slot > 0 && slot < 4) continue; | ||
| 254 | std::uint32_t words[8]; | ||
| 255 | if (!rt::d3d12::read_arena(device, shader_va + slot * kDescriptor, words, sizeof(words))) return false; | ||
| 256 | if (base_of(words) == b.arena_va && words[2]) ++restored; | ||
| 257 | else if (!zero_size(words)) return false; | ||
| 258 | } | ||
| 259 | return true; | ||
| 260 | }; | ||
| 250 | unsigned restored = 0; | 261 | unsigned restored = 0; |
| 251 | for (unsigned slot = 0; slot < 131; ++slot) { | 262 | EXPECT(submit()); |
| 252 | if (slot > 0 && slot < 4) continue; | 263 | EXPECT(count_restored(restored) && restored == 0); |
| 264 | leonida::title_va_aliases().add(unmapped, kViewBytes, b.arena_va); | ||
| 265 | EXPECT(submit()); | ||
| 266 | EXPECT(count_restored(restored) && restored == 128); | ||
| 267 | std::printf("128 waiting zero descriptors, all restored at the first submission after their alias came\n"); | ||
| 268 | // The alias goes: at the next submission none of them names its copy any more. | ||
| 269 | leonida::title_va_aliases().remove(unmapped, b.arena_va); | ||
| 270 | EXPECT(submit()); | ||
| 271 | EXPECT(count_restored(restored) && restored == 0); | ||
| 272 | |||
| 273 | // A released buffer: the slots that named it are null at the next submission, the others keep their V#s. The | ||
| 274 | // title's bytes stay as written (each slot is rewritten through its page, as the title does, so the heap's write | ||
| 275 | // tracking sees it). | ||
| 276 | { | ||
| 277 | Ref<ID3D12Resource> gone; | ||
| 278 | const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; | ||
| 279 | const auto gone_desc = buffer_desc(64 * 1024); | ||
| 280 | EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &gone_desc, | ||
| 281 | D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&gone.p)))); | ||
| 282 | const std::uint64_t gone_va = gone->GetGPUVirtualAddress(); | ||
| 283 | for (int i = 140; i < 150; ++i) put(i, raw_vsharp(gone_va + std::uint64_t(i - 140) * kViewBytes)); | ||
| 284 | for (int i = 150; i < 160; ++i) put(i, raw_vsharp(b.arena_va)); | ||
| 285 | EXPECT(submit()); | ||
| 253 | std::uint32_t words[8]; | 286 | std::uint32_t words[8]; |
| 254 | EXPECT(rt::d3d12::read_arena(device, shader_va + slot * kDescriptor, words, sizeof(words))); | 287 | for (unsigned slot = 140; slot < 160; ++slot) { |
| 255 | if (base_of(words) == b.arena_va && words[2]) ++restored; | 288 | EXPECT(rt::d3d12::read_arena(device, shader_va + slot * kDescriptor, words, sizeof(words))); |
| 256 | else EXPECT(zero_size(words)); | 289 | EXPECT(words[2] && base_of(words) == (slot < 150 ? gone_va + (slot - 140) * kViewBytes : b.arena_va)); |
| 290 | } | ||
| 291 | gone.reset(); | ||
| 292 | // The arena range goes once the device has retired the buffer: a few submissions at most. | ||
| 293 | bool nulled = false; | ||
| 294 | for (int pass = 0; pass < 8 && !nulled; ++pass) { | ||
| 295 | EXPECT(submit()); | ||
| 296 | nulled = true; | ||
| 297 | for (unsigned slot = 140; slot < 150; ++slot) { | ||
| 298 | EXPECT(rt::d3d12::read_arena(device, shader_va + slot * kDescriptor, words, sizeof(words))); | ||
| 299 | nulled &= zero_size(words); | ||
| 300 | } | ||
| 301 | } | ||
| 302 | EXPECT(nulled); | ||
| 303 | for (unsigned slot = 150; slot < 160; ++slot) { | ||
| 304 | EXPECT(rt::d3d12::read_arena(device, shader_va + slot * kDescriptor, words, sizeof(words))); | ||
| 305 | EXPECT(words[2] && base_of(words) == b.arena_va); | ||
| 306 | } | ||
| 307 | std::printf("released buffer: the 10 slots that named it are null at the next submissions, 10 others kept\n"); | ||
| 257 | } | 308 | } |
| 258 | EXPECT(restored == 16); | ||
| 259 | std::printf("128 settled zero descriptors, %u restored in 64 submissions\n", restored); | ||
| 260 | leonida::title_va_aliases().remove(unmapped, b.arena_va); | ||
| 261 | 309 | ||
| 262 | // The null guard: past the heap's last slot, up to kHeapIndexReach from its start, every byte reads 0. | 310 | // The null guard: past the heap's last slot, up to kHeapIndexReach from its start, every byte reads 0. |
| 263 | constexpr std::uint64_t reach = 64ull << 20; | 311 | constexpr std::uint64_t reach = 64ull << 20; |
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. | ||
| 182 | int 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, ©_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). |
| 178 | int read_back(ID3D12Device* real, ID3D12Resource* buffer, UINT64 size, std::vector<std::uint8_t>& out) { | 254 | int 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/depth24_fragment_test.cpp b/runtime/test/depth24_fragment_test.cpp new file mode 100644 index 000000000..e66e66b4e --- /dev/null +++ b/runtime/test/depth24_fragment_test.cpp | |||
| @@ -0,0 +1,608 @@ | |||
| 1 | // CPU-only SPIR-V validation and execution test for runtime/src/depth24_fragment.h (D24 and Xbox D16S8 fallback). | ||
| 2 | // Verifies structural SPIR-V invariants (bounds, section order, pre-function declarations, interface variables, | ||
| 3 | // execution modes) and interprets the emitted SPIR-V instructions directly across all 65,536 16-bit codes, | ||
| 4 | // half-step ties, IEEE-754 specials, depth bias/slope/clamp, and 24-bit parity. No Vulkan device or game data. | ||
| 5 | #include "../src/depth24_fragment.h" | ||
| 6 | |||
| 7 | #include <algorithm> | ||
| 8 | #include <array> | ||
| 9 | #include <bit> | ||
| 10 | #include <cmath> | ||
| 11 | #include <cstdint> | ||
| 12 | #include <cstdio> | ||
| 13 | #include <cstring> | ||
| 14 | #include <limits> | ||
| 15 | #include <string> | ||
| 16 | #include <unordered_map> | ||
| 17 | #include <unordered_set> | ||
| 18 | #include <vector> | ||
| 19 | |||
| 20 | #define EXPECT(cond) \ | ||
| 21 | do { \ | ||
| 22 | if (!(cond)) { \ | ||
| 23 | std::fprintf(stderr, "depth24_fragment_test: line %d failed: %s\n", __LINE__, #cond); \ | ||
| 24 | return 1; \ | ||
| 25 | } \ | ||
| 26 | } while (0) | ||
| 27 | |||
| 28 | namespace { | ||
| 29 | |||
| 30 | using namespace leonida; | ||
| 31 | using namespace leonida::spirv24; | ||
| 32 | |||
| 33 | std::uint32_t f_bits(float f) { | ||
| 34 | std::uint32_t u = 0; | ||
| 35 | std::memcpy(&u, &f, 4); | ||
| 36 | return u; | ||
| 37 | } | ||
| 38 | |||
| 39 | float u_float(std::uint32_t u) { | ||
| 40 | float f = 0.0f; | ||
| 41 | std::memcpy(&f, &u, 4); | ||
| 42 | return f; | ||
| 43 | } | ||
| 44 | |||
| 45 | double round_half_even(double x) { | ||
| 46 | const double r = std::floor(x + 0.5); | ||
| 47 | return r - x == 0.5 && std::fmod(r, 2.0) != 0.0 ? r - 1.0 : r; | ||
| 48 | } | ||
| 49 | |||
| 50 | std::uint32_t ref_quantize_code(float z, double max_levels, std::uint32_t max_code) { | ||
| 51 | if (!(z > 0.0f)) return 0u; | ||
| 52 | if (z >= 1.0f) return max_code; | ||
| 53 | const float product = z * static_cast<float>(max_levels); | ||
| 54 | return static_cast<std::uint32_t>(round_half_even(double(product))); | ||
| 55 | } | ||
| 56 | |||
| 57 | float ref_quantize_float(float z, double max_levels, std::uint32_t max_code) { | ||
| 58 | const std::uint32_t d = ref_quantize_code(z, max_levels, max_code); | ||
| 59 | return static_cast<float>(double(d) / max_levels); | ||
| 60 | } | ||
| 61 | |||
| 62 | // Synthetic SPIR-V fragment shader that either leaves FragDepth untouched or writes its own FragDepth | ||
| 63 | // (optionally with an extra early OpReturn branch, DepthGreater conservative mode, or EarlyFragmentTests). | ||
| 64 | std::vector<std::uint32_t> make_synthetic_fragment(bool writes_depth, bool early_tests, bool conservative_greater, | ||
| 65 | bool two_returns) { | ||
| 66 | constexpr std::uint32_t op_branch_conditional = 250; | ||
| 67 | constexpr std::uint32_t id_main = 1, id_void = 2, id_fn = 3, id_label0 = 4, id_f32 = 5, id_pf_out = 6, | ||
| 68 | id_frag_depth = 7, id_v4f = 8, id_pv4_in = 9, id_frag_coord = 10, id_bool = 11, | ||
| 69 | id_true = 12, id_label1 = 13, id_label2 = 14, id_c = 15, id_z = 16, bound = 17; | ||
| 70 | std::vector<std::uint32_t> w = {0x07230203u, 0x00010000u, 0, bound, 0}; | ||
| 71 | auto put = [&](Inst i) { w.insert(w.end(), i.begin(), i.end()); }; | ||
| 72 | put(make(op_capability, {1})); | ||
| 73 | put(make(op_memory_model, {0, 1})); | ||
| 74 | Inst ep = make(op_entry_point, {model_fragment, id_main}); | ||
| 75 | append_string(ep, "main"); | ||
| 76 | if (writes_depth) { | ||
| 77 | ep.push_back(id_frag_coord); | ||
| 78 | ep.push_back(id_frag_depth); | ||
| 79 | } | ||
| 80 | fix_length(ep); | ||
| 81 | put(ep); | ||
| 82 | put(make(op_execution_mode, {id_main, mode_origin_upper_left})); | ||
| 83 | if (early_tests) put(make(op_execution_mode, {id_main, mode_early_fragment_tests})); | ||
| 84 | if (conservative_greater) put(make(op_execution_mode, {id_main, mode_depth_greater})); | ||
| 85 | if (writes_depth) { | ||
| 86 | put(make(op_decorate, {id_frag_coord, decoration_builtin, builtin_frag_coord})); | ||
| 87 | put(make(op_decorate, {id_frag_depth, decoration_builtin, builtin_frag_depth})); | ||
| 88 | } | ||
| 89 | put(make(op_type_void, {id_void})); | ||
| 90 | put(make(op_type_function, {id_fn, id_void})); | ||
| 91 | if (writes_depth) { | ||
| 92 | put(make(op_type_float, {id_f32, 32})); | ||
| 93 | put(make(op_type_pointer, {id_pf_out, storage_output, id_f32})); | ||
| 94 | put(make(op_type_vector, {id_v4f, id_f32, 4})); | ||
| 95 | put(make(op_type_pointer, {id_pv4_in, storage_input, id_v4f})); | ||
| 96 | if (two_returns) { | ||
| 97 | put(make(op_type_bool, {id_bool})); | ||
| 98 | put(make(41 /* OpConstantTrue */, {id_bool, id_true})); | ||
| 99 | } | ||
| 100 | put(make(op_variable, {id_pv4_in, id_frag_coord, storage_input})); | ||
| 101 | put(make(op_variable, {id_pf_out, id_frag_depth, storage_output})); | ||
| 102 | } | ||
| 103 | put(make(op_function, {id_void, id_main, 0, id_fn})); | ||
| 104 | put(make(op_label, {id_label0})); | ||
| 105 | if (writes_depth) { | ||
| 106 | put(make(op_load, {id_v4f, id_c, id_frag_coord})); | ||
| 107 | put(make(op_composite_extract, {id_f32, id_z, id_c, 2})); | ||
| 108 | put(make(op_store, {id_frag_depth, id_z})); | ||
| 109 | if (two_returns) { | ||
| 110 | put(make(op_branch_conditional, {id_true, id_label1, id_label2})); | ||
| 111 | put(make(op_label, {id_label1})); | ||
| 112 | put(make(op_return, {})); | ||
| 113 | put(make(op_label, {id_label2})); | ||
| 114 | } | ||
| 115 | } | ||
| 116 | put(make(op_return, {})); | ||
| 117 | put(make(op_function_end, {})); | ||
| 118 | return w; | ||
| 119 | } | ||
| 120 | |||
| 121 | // Structural SPIR-V checker + interpreter for depth24_patch_fragment output. | ||
| 122 | struct SpvProgram { | ||
| 123 | std::uint32_t bound = 0; | ||
| 124 | std::uint32_t glsl_id = 0; | ||
| 125 | std::uint32_t frag_coord_var = 0; | ||
| 126 | std::uint32_t frag_depth_var = 0; | ||
| 127 | bool has_depth_replacing = false; | ||
| 128 | bool has_conservative_depth = false; | ||
| 129 | bool frag_depth_in_interface = false; | ||
| 130 | bool frag_coord_in_interface = false; | ||
| 131 | std::unordered_map<std::uint32_t, std::uint32_t> const_u32; | ||
| 132 | std::unordered_map<std::uint32_t, bool> const_bool; | ||
| 133 | std::vector<Inst> body; | ||
| 134 | |||
| 135 | bool parse_and_validate(const std::vector<std::uint32_t>& words, std::string& err) { | ||
| 136 | if (words.size() < 5 || words[0] != 0x07230203u) { | ||
| 137 | err = "bad magic"; | ||
| 138 | return false; | ||
| 139 | } | ||
| 140 | bound = words[3]; | ||
| 141 | std::vector<Inst> insts; | ||
| 142 | for (std::size_t w = 5; w < words.size();) { | ||
| 143 | const std::uint32_t count = words[w] >> 16; | ||
| 144 | if (count == 0 || w + count > words.size()) { | ||
| 145 | err = "truncated instruction"; | ||
| 146 | return false; | ||
| 147 | } | ||
| 148 | insts.emplace_back(words.begin() + std::ptrdiff_t(w), words.begin() + std::ptrdiff_t(w + count)); | ||
| 149 | w += count; | ||
| 150 | } | ||
| 151 | |||
| 152 | // Section order check: Capability(0) -> ExtInstImport(1) -> MemoryModel(2) -> EntryPoint(3) | ||
| 153 | // -> ExecutionMode(4) -> Decorations(5) -> Globals/Types/Constants/Variables(6) -> Functions(7). | ||
| 154 | int section = 0; | ||
| 155 | std::unordered_set<std::uint32_t> defined_globals; | ||
| 156 | std::unordered_set<std::uint32_t> interface_ids; | ||
| 157 | bool in_fn = false; | ||
| 158 | std::size_t body_start = 0; | ||
| 159 | |||
| 160 | auto check_id = [&](std::uint32_t id) { return id > 0 && id < bound; }; | ||
| 161 | |||
| 162 | for (std::size_t idx = 0; idx < insts.size(); ++idx) { | ||
| 163 | const Inst& i = insts[idx]; | ||
| 164 | const std::uint32_t op = opcode(i); | ||
| 165 | if (!in_fn) { | ||
| 166 | int s = section; | ||
| 167 | if (op == op_capability) s = 0; | ||
| 168 | else if (op == op_ext_inst_import) s = 1; | ||
| 169 | else if (op == op_memory_model) s = 2; | ||
| 170 | else if (op == op_entry_point) s = 3; | ||
| 171 | else if (op == op_execution_mode || op == op_execution_mode_id) s = 4; | ||
| 172 | else if (op == op_decorate) s = 5; | ||
| 173 | else if (is_global_decl(op)) s = 6; | ||
| 174 | else if (op == op_function) s = 7; | ||
| 175 | if (s < section) { | ||
| 176 | err = "out-of-order SPIR-V section"; | ||
| 177 | return false; | ||
| 178 | } | ||
| 179 | section = s; | ||
| 180 | } | ||
| 181 | |||
| 182 | if (op == op_ext_inst_import) { | ||
| 183 | if (i.size() < 3 || !check_id(i[1])) { | ||
| 184 | err = "bad ExtInstImport"; | ||
| 185 | return false; | ||
| 186 | } | ||
| 187 | std::string name((i.size() - 2) * 4, '\0'); | ||
| 188 | std::memcpy(name.data(), &i[2], name.size()); | ||
| 189 | if (std::strcmp(name.c_str(), "GLSL.std.450") == 0) glsl_id = i[1]; | ||
| 190 | defined_globals.insert(i[1]); | ||
| 191 | } else if (op == op_entry_point) { | ||
| 192 | const std::size_t names = 3 + string_words(i, 3); | ||
| 193 | for (std::size_t w = names; w < i.size(); ++w) interface_ids.insert(i[w]); | ||
| 194 | } else if (op == op_execution_mode && i.size() >= 3) { | ||
| 195 | if (i[2] == mode_depth_replacing) has_depth_replacing = true; | ||
| 196 | if (i[2] == mode_depth_greater || i[2] == mode_depth_less || i[2] == mode_depth_unchanged) | ||
| 197 | has_conservative_depth = true; | ||
| 198 | } else if (op == op_decorate && i.size() == 4 && i[2] == decoration_builtin) { | ||
| 199 | if (i[3] == builtin_frag_coord) frag_coord_var = i[1]; | ||
| 200 | if (i[3] == builtin_frag_depth) frag_depth_var = i[1]; | ||
| 201 | } else if (!in_fn && is_global_decl(op)) { | ||
| 202 | std::uint32_t res = 0; | ||
| 203 | if (op == op_constant && i.size() == 4) { | ||
| 204 | res = i[2]; | ||
| 205 | const_u32[res] = i[3]; | ||
| 206 | } else if (op == 41 /* OpConstantTrue */ && i.size() == 3) { | ||
| 207 | res = i[2]; | ||
| 208 | const_bool[res] = true; | ||
| 209 | } else if (op == op_variable && i.size() >= 4) { | ||
| 210 | res = i[2]; | ||
| 211 | } else if (op >= op_type_void && op <= 39 && i.size() >= 2) { | ||
| 212 | res = i[1]; | ||
| 213 | } | ||
| 214 | if (res) { | ||
| 215 | if (!check_id(res) || !defined_globals.insert(res).second) { | ||
| 216 | err = "duplicate or out-of-bounds global id"; | ||
| 217 | return false; | ||
| 218 | } | ||
| 219 | } | ||
| 220 | } else if (op == op_function) { | ||
| 221 | in_fn = true; | ||
| 222 | body_start = idx; | ||
| 223 | body.push_back(i); | ||
| 224 | } else if (in_fn) { | ||
| 225 | body.push_back(i); | ||
| 226 | if (op == op_function_end) in_fn = false; | ||
| 227 | } | ||
| 228 | } | ||
| 229 | if (body_start == 0 || body.empty()) { | ||
| 230 | err = "missing function body"; | ||
| 231 | return false; | ||
| 232 | } | ||
| 233 | frag_depth_in_interface = frag_depth_var && interface_ids.count(frag_depth_var) != 0; | ||
| 234 | frag_coord_in_interface = frag_coord_var && interface_ids.count(frag_coord_var) != 0; | ||
| 235 | |||
| 236 | // Verify every SSA operand in the function body is defined (either globally before OpFunction or earlier in | ||
| 237 | // the body) and every result id is unique and < bound. | ||
| 238 | std::unordered_set<std::uint32_t> defs = defined_globals; | ||
| 239 | for (const Inst& i : body) { | ||
| 240 | const std::uint32_t op = opcode(i); | ||
| 241 | if (op == op_function || op == op_label || op == op_return || op == op_function_end) { | ||
| 242 | if (op == op_label && i.size() == 2) defs.insert(i[1]); | ||
| 243 | continue; | ||
| 244 | } | ||
| 245 | if (op == 250 /* OpBranchConditional */) { | ||
| 246 | if (i.size() != 4 || !defs.count(i[1])) { | ||
| 247 | err = "undefined branch condition"; | ||
| 248 | return false; | ||
| 249 | } | ||
| 250 | continue; | ||
| 251 | } | ||
| 252 | if (op == op_store) { | ||
| 253 | if (i.size() != 3 || !defs.count(i[1]) || !defs.count(i[2])) { | ||
| 254 | err = "undefined operand in OpStore"; | ||
| 255 | return false; | ||
| 256 | } | ||
| 257 | continue; | ||
| 258 | } | ||
| 259 | if (i.size() < 3 || !check_id(i[2])) { | ||
| 260 | err = "bad result id in function body"; | ||
| 261 | return false; | ||
| 262 | } | ||
| 263 | if (!defs.count(i[1])) { | ||
| 264 | err = "undefined result type id"; | ||
| 265 | return false; | ||
| 266 | } | ||
| 267 | const std::size_t first_arg = op == op_ext_inst ? 5 : 3; | ||
| 268 | if (op == op_ext_inst && (i.size() < 5 || i[3] != glsl_id)) { | ||
| 269 | err = "bad ExtInst import id"; | ||
| 270 | return false; | ||
| 271 | } | ||
| 272 | for (std::size_t a = first_arg; a < i.size(); ++a) { | ||
| 273 | if (op == op_composite_extract && a > 3) continue; // literal component index | ||
| 274 | if (!defs.count(i[a])) { | ||
| 275 | err = "undefined operand id in function body (missing from prime_quantise?)"; | ||
| 276 | return false; | ||
| 277 | } | ||
| 278 | } | ||
| 279 | if (!defs.insert(i[2]).second) { | ||
| 280 | err = "duplicate result id in function body"; | ||
| 281 | return false; | ||
| 282 | } | ||
| 283 | } | ||
| 284 | return true; | ||
| 285 | } | ||
| 286 | |||
| 287 | // Executes the entry function for a given FragCoord.z and screen-space slopes (dz_dx, dz_dy). | ||
| 288 | bool eval(float z_in, float dz_dx, float dz_dy, float& z_out, std::string& err) const { | ||
| 289 | std::unordered_map<std::uint32_t, std::uint32_t> u32_val = const_u32; | ||
| 290 | std::unordered_map<std::uint32_t, bool> bool_val = const_bool; | ||
| 291 | std::unordered_map<std::uint32_t, std::array<float, 4>> vec4_val; | ||
| 292 | float frag_depth = std::numeric_limits<float>::quiet_NaN(); | ||
| 293 | bool wrote_depth = false; | ||
| 294 | |||
| 295 | std::unordered_map<std::uint32_t, std::size_t> labels; | ||
| 296 | for (std::size_t k = 0; k < body.size(); ++k) | ||
| 297 | if (opcode(body[k]) == op_label && body[k].size() == 2) labels[body[k][1]] = k; | ||
| 298 | |||
| 299 | for (std::size_t pc = 0; pc < body.size(); ++pc) { | ||
| 300 | const Inst& i = body[pc]; | ||
| 301 | const std::uint32_t op = opcode(i); | ||
| 302 | switch (op) { | ||
| 303 | case op_function: | ||
| 304 | case op_label: | ||
| 305 | break; | ||
| 306 | case op_return: | ||
| 307 | if (!wrote_depth) { | ||
| 308 | err = "shader returned without writing FragDepth"; | ||
| 309 | return false; | ||
| 310 | } | ||
| 311 | z_out = frag_depth; | ||
| 312 | return true; | ||
| 313 | case op_function_end: | ||
| 314 | err = "fell off end of function"; | ||
| 315 | return false; | ||
| 316 | case 250: { // OpBranchConditional | ||
| 317 | const std::uint32_t target = bool_val.at(i[1]) ? i[2] : i[3]; | ||
| 318 | pc = labels.at(target); | ||
| 319 | break; | ||
| 320 | } | ||
| 321 | case op_load: | ||
| 322 | if (i[3] == frag_coord_var) { | ||
| 323 | vec4_val[i[2]] = {0.5f, 0.5f, z_in, 1.0f}; | ||
| 324 | } else if (i[3] == frag_depth_var) { | ||
| 325 | u32_val[i[2]] = f_bits(frag_depth); | ||
| 326 | } else { | ||
| 327 | err = "unexpected OpLoad variable"; | ||
| 328 | return false; | ||
| 329 | } | ||
| 330 | break; | ||
| 331 | case op_store: | ||
| 332 | if (i[1] != frag_depth_var) { | ||
| 333 | err = "unexpected OpStore variable"; | ||
| 334 | return false; | ||
| 335 | } | ||
| 336 | frag_depth = u_float(u32_val.at(i[2])); | ||
| 337 | wrote_depth = true; | ||
| 338 | break; | ||
| 339 | case op_composite_extract: | ||
| 340 | u32_val[i[2]] = f_bits(vec4_val.at(i[3])[i[4]]); | ||
| 341 | break; | ||
| 342 | case op_bitcast: | ||
| 343 | u32_val[i[2]] = u32_val.at(i[3]); | ||
| 344 | break; | ||
| 345 | case op_f_add: | ||
| 346 | u32_val[i[2]] = f_bits(u_float(u32_val.at(i[3])) + u_float(u32_val.at(i[4]))); | ||
| 347 | break; | ||
| 348 | case op_f_mul: | ||
| 349 | u32_val[i[2]] = f_bits(u_float(u32_val.at(i[3])) * u_float(u32_val.at(i[4]))); | ||
| 350 | break; | ||
| 351 | case op_dpdx: | ||
| 352 | u32_val[i[2]] = f_bits(dz_dx); | ||
| 353 | break; | ||
| 354 | case op_dpdy: | ||
| 355 | u32_val[i[2]] = f_bits(dz_dy); | ||
| 356 | break; | ||
| 357 | case op_convert_f_to_u: { | ||
| 358 | const float v = u_float(u32_val.at(i[3])); | ||
| 359 | if (!(v >= 0.0f) || v > 4294967295.0f) { | ||
| 360 | err = "OpConvertFToU received out-of-range or NaN float"; | ||
| 361 | return false; | ||
| 362 | } | ||
| 363 | u32_val[i[2]] = static_cast<std::uint32_t>(v); | ||
| 364 | break; | ||
| 365 | } | ||
| 366 | case op_convert_u_to_f: | ||
| 367 | u32_val[i[2]] = f_bits(static_cast<float>(u32_val.at(i[3]))); | ||
| 368 | break; | ||
| 369 | case op_i_add: | ||
| 370 | u32_val[i[2]] = u32_val.at(i[3]) + u32_val.at(i[4]); | ||
| 371 | break; | ||
| 372 | case op_i_sub: | ||
| 373 | u32_val[i[2]] = u32_val.at(i[3]) - u32_val.at(i[4]); | ||
| 374 | break; | ||
| 375 | case op_shift_left_logical: { | ||
| 376 | const std::uint32_t sh = u32_val.at(i[4]); | ||
| 377 | if (sh >= 32u) { | ||
| 378 | err = "OpShiftLeftLogical with shift >= 32 (UB in SPIR-V)"; | ||
| 379 | return false; | ||
| 380 | } | ||
| 381 | u32_val[i[2]] = u32_val.at(i[3]) << sh; | ||
| 382 | break; | ||
| 383 | } | ||
| 384 | case 194u: { // OpShiftRightLogical | ||
| 385 | const std::uint32_t sh = u32_val.at(i[4]); | ||
| 386 | if (sh >= 32u) { | ||
| 387 | err = "OpShiftRightLogical with shift >= 32 (UB in SPIR-V)"; | ||
| 388 | return false; | ||
| 389 | } | ||
| 390 | u32_val[i[2]] = u32_val.at(i[3]) >> sh; | ||
| 391 | break; | ||
| 392 | } | ||
| 393 | case op_i_equal: | ||
| 394 | bool_val[i[2]] = u32_val.at(i[3]) == u32_val.at(i[4]); | ||
| 395 | break; | ||
| 396 | case op_u_greater_than: | ||
| 397 | bool_val[i[2]] = u32_val.at(i[3]) > u32_val.at(i[4]); | ||
| 398 | break; | ||
| 399 | case op_u_greater_than_equal: | ||
| 400 | bool_val[i[2]] = u32_val.at(i[3]) >= u32_val.at(i[4]); | ||
| 401 | break; | ||
| 402 | case op_select: | ||
| 403 | u32_val[i[2]] = bool_val.at(i[3]) ? u32_val.at(i[4]) : u32_val.at(i[5]); | ||
| 404 | break; | ||
| 405 | case op_ext_inst: { | ||
| 406 | const std::uint32_t ext_op = i[4]; | ||
| 407 | if (ext_op == glsl_round_even) { | ||
| 408 | const float x = u_float(u32_val.at(i[5])); | ||
| 409 | const float r = std::isfinite(x) ? static_cast<float>(round_half_even(double(x))) : x; | ||
| 410 | u32_val[i[2]] = f_bits(r); | ||
| 411 | } else if (ext_op == glsl_fabs) { | ||
| 412 | u32_val[i[2]] = f_bits(std::fabs(u_float(u32_val.at(i[5])))); | ||
| 413 | } else if (ext_op == glsl_fmin) { | ||
| 414 | // GLSL.std.450 FMin: if one operand is NaN, the other is returned. | ||
| 415 | const float a = u_float(u32_val.at(i[5])), b = u_float(u32_val.at(i[6])); | ||
| 416 | u32_val[i[2]] = f_bits(std::isnan(a) ? b : std::isnan(b) ? a : (a < b ? a : b)); | ||
| 417 | } else if (ext_op == glsl_fmax) { | ||
| 418 | const float a = u_float(u32_val.at(i[5])), b = u_float(u32_val.at(i[6])); | ||
| 419 | u32_val[i[2]] = f_bits(std::isnan(a) ? b : std::isnan(b) ? a : (a > b ? a : b)); | ||
| 420 | } else if (ext_op == glsl_find_umsb) { | ||
| 421 | const std::uint32_t v = u32_val.at(i[5]); | ||
| 422 | u32_val[i[2]] = v == 0u ? 0xffffffffu : static_cast<std::uint32_t>(31 - std::countl_zero(v)); | ||
| 423 | } else { | ||
| 424 | err = "unexpected GLSL.std.450 instruction"; | ||
| 425 | return false; | ||
| 426 | } | ||
| 427 | break; | ||
| 428 | } | ||
| 429 | default: | ||
| 430 | err = "unexpected SPIR-V opcode"; | ||
| 431 | return false; | ||
| 432 | } | ||
| 433 | } | ||
| 434 | err = "no return reached"; | ||
| 435 | return false; | ||
| 436 | } | ||
| 437 | }; | ||
| 438 | |||
| 439 | int test_d16_exhaustive() { | ||
| 440 | const Depth24Bias d16_bias{0, 0.0f, 0.0f, 65535.0f}; | ||
| 441 | const std::vector<std::uint32_t> depth_only = depth24_depth_only_fragment(d16_bias); | ||
| 442 | EXPECT(!depth_only.empty()); | ||
| 443 | |||
| 444 | std::string why, err; | ||
| 445 | const std::vector<std::uint32_t> ps_plain = | ||
| 446 | depth24_patch_fragment(make_synthetic_fragment(false, false, true, false), d16_bias, why); | ||
| 447 | EXPECT(!ps_plain.empty()); | ||
| 448 | const std::vector<std::uint32_t> ps_write = | ||
| 449 | depth24_patch_fragment(make_synthetic_fragment(true, false, true, true), d16_bias, why); | ||
| 450 | EXPECT(!ps_write.empty()); | ||
| 451 | |||
| 452 | for (const auto& spv : {depth_only, ps_plain, ps_write}) { | ||
| 453 | SpvProgram prog; | ||
| 454 | if (!prog.parse_and_validate(spv, err)) { | ||
| 455 | std::fprintf(stderr, "D16 validate failed: %s\n", err.c_str()); | ||
| 456 | return 1; | ||
| 457 | } | ||
| 458 | EXPECT(prog.has_depth_replacing); | ||
| 459 | EXPECT(!prog.has_conservative_depth); | ||
| 460 | EXPECT(prog.frag_depth_in_interface); | ||
| 461 | EXPECT(prog.frag_coord_in_interface); | ||
| 462 | |||
| 463 | // Exhaustive check of all 65,536 16-bit UNORM codes (round-trip bit-for-bit exact). | ||
| 464 | for (std::uint32_t d = 0; d <= 65535u; ++d) { | ||
| 465 | const float z = static_cast<float>(double(d) / 65535.0); | ||
| 466 | float out = 0.0f; | ||
| 467 | if (!prog.eval(z, 0.0f, 0.0f, out, err)) { | ||
| 468 | std::fprintf(stderr, "D16 eval failed at d=%u: %s\n", d, err.c_str()); | ||
| 469 | return 1; | ||
| 470 | } | ||
| 471 | if (f_bits(out) != f_bits(z)) { | ||
| 472 | std::fprintf(stderr, "D16 mismatch at d=%u: got %08x (%.9g), want %08x (%.9g)\n", | ||
| 473 | d, f_bits(out), out, f_bits(z), z); | ||
| 474 | return 1; | ||
| 475 | } | ||
| 476 | } | ||
| 477 | |||
| 478 | // Half-step ties and neighbors across the full 16-bit range. | ||
| 479 | for (std::uint32_t d = 0; d < 65535u; d += 17u) { | ||
| 480 | const float mid = static_cast<float>((double(d) + 0.5) / 65535.0); | ||
| 481 | for (float z : {std::nextafter(mid, 0.0f), mid, std::nextafter(mid, 1.0f)}) { | ||
| 482 | float out = 0.0f; | ||
| 483 | EXPECT(prog.eval(z, 0.0f, 0.0f, out, err)); | ||
| 484 | const float want = ref_quantize_float(z, 65535.0, 0xffffu); | ||
| 485 | EXPECT(f_bits(out) == f_bits(want)); | ||
| 486 | } | ||
| 487 | } | ||
| 488 | |||
| 489 | // IEEE-754 specials: zeros, subnormals, negatives, infinities, NaNs, >1.0. | ||
| 490 | const std::uint32_t specials[] = { | ||
| 491 | 0x00000000u, 0x80000000u, 0x00000001u, 0x007fffffu, 0x00800000u, 0xbf800000u, | ||
| 492 | 0xff800000u, 0x7f800000u, 0x7fc00000u, 0x7fa00001u, 0xffc00000u, 0x3f7fffffu, | ||
| 493 | 0x3f800000u, 0x3f800001u, 0x40000000u, 0x7f7fffffu, | ||
| 494 | }; | ||
| 495 | for (std::uint32_t bits : specials) { | ||
| 496 | const float z = u_float(bits); | ||
| 497 | float out = 0.0f; | ||
| 498 | if (!prog.eval(z, 0.0f, 0.0f, out, err)) { | ||
| 499 | std::fprintf(stderr, "D16 special %08x eval failed: %s\n", bits, err.c_str()); | ||
| 500 | return 1; | ||
| 501 | } | ||
| 502 | const float want = ref_quantize_float(z, 65535.0, 0xffffu); | ||
| 503 | if (f_bits(out) != f_bits(want)) { | ||
| 504 | std::fprintf(stderr, "D16 special %08x mismatch: got %08x want %08x\n", | ||
| 505 | bits, f_bits(out), f_bits(want)); | ||
| 506 | return 1; | ||
| 507 | } | ||
| 508 | } | ||
| 509 | } | ||
| 510 | return 0; | ||
| 511 | } | ||
| 512 | |||
| 513 | int test_d16_and_d24_bias_and_clamp() { | ||
| 514 | struct Case { | ||
| 515 | float levels; | ||
| 516 | std::uint32_t max_code; | ||
| 517 | int constant; | ||
| 518 | float slope; | ||
| 519 | float clamp; | ||
| 520 | float z; | ||
| 521 | float dx; | ||
| 522 | float dy; | ||
| 523 | }; | ||
| 524 | const Case cases[] = { | ||
| 525 | {65535.0f, 0xffffu, 1, 0.0f, 0.0f, 0.25f, 0.0f, 0.0f}, | ||
| 526 | {65535.0f, 0xffffu, -3, 2.0f, 0.0f, 0.5f, -0.002f, 0.004f}, | ||
| 527 | {65535.0f, 0xffffu, 5, 4.0f, 0.01f, 0.5f, 0.01f, 0.0f}, // positive clamp caps bias | ||
| 528 | {65535.0f, 0xffffu, -5, -4.0f, -0.01f, 0.5f, 0.01f, 0.0f}, // negative clamp floors bias | ||
| 529 | {16777215.0f, 0xffffffu, 1, 0.0f, 0.0f, 0.15625f, 0.0f, 0.0f}, | ||
| 530 | {16777215.0f, 0xffffffu, 1000, 1.5f, 0.004f, 0.5f, 0.003f, -0.005f}, | ||
| 531 | {16777215.0f, 0xffffffu, -5, -2.0f, -0.01f, 0.7f, 0.008f, 0.002f}, | ||
| 532 | }; | ||
| 533 | for (const Case& c : cases) { | ||
| 534 | const Depth24Bias bias{c.constant, c.slope, c.clamp, c.levels}; | ||
| 535 | const std::vector<std::uint32_t> spv = depth24_depth_only_fragment(bias); | ||
| 536 | EXPECT(!spv.empty()); | ||
| 537 | SpvProgram prog; | ||
| 538 | std::string err; | ||
| 539 | EXPECT(prog.parse_and_validate(spv, err)); | ||
| 540 | float out = 0.0f; | ||
| 541 | EXPECT(prog.eval(c.z, c.dx, c.dy, out, err)); | ||
| 542 | float amount = c.slope * std::fmax(std::fabs(c.dx), std::fabs(c.dy)) + | ||
| 543 | depth24_bias_constant(c.constant, c.levels); | ||
| 544 | if (c.clamp > 0.0f) amount = std::fmin(amount, c.clamp); | ||
| 545 | if (c.clamp < 0.0f) amount = std::fmax(amount, c.clamp); | ||
| 546 | const float want = ref_quantize_float(c.z + amount, double(c.levels), c.max_code); | ||
| 547 | EXPECT(f_bits(out) == f_bits(want)); | ||
| 548 | |||
| 549 | // Shader-written SV_Depth must be quantised WITHOUT rasterizer bias. | ||
| 550 | std::string why; | ||
| 551 | const std::vector<std::uint32_t> sw = | ||
| 552 | depth24_patch_fragment(make_synthetic_fragment(true, false, false, false), bias, why); | ||
| 553 | EXPECT(!sw.empty()); | ||
| 554 | SpvProgram sw_prog; | ||
| 555 | EXPECT(sw_prog.parse_and_validate(sw, err)); | ||
| 556 | float sw_out = 0.0f; | ||
| 557 | EXPECT(sw_prog.eval(c.z, c.dx, c.dy, sw_out, err)); | ||
| 558 | const float sw_want = ref_quantize_float(c.z, double(c.levels), c.max_code); | ||
| 559 | EXPECT(f_bits(sw_out) == f_bits(sw_want)); | ||
| 560 | } | ||
| 561 | return 0; | ||
| 562 | } | ||
| 563 | |||
| 564 | int test_d24_boundary_codes() { | ||
| 565 | const Depth24Bias d24_bias{}; | ||
| 566 | const std::vector<std::uint32_t> spv = depth24_depth_only_fragment(d24_bias); | ||
| 567 | EXPECT(!spv.empty()); | ||
| 568 | SpvProgram prog; | ||
| 569 | std::string err; | ||
| 570 | EXPECT(prog.parse_and_validate(spv, err)); | ||
| 571 | |||
| 572 | const std::uint32_t sample_codes[] = { | ||
| 573 | 0u, 1u, 2u, 3u, 127u, 128u, 255u, 256u, 65535u, 65536u, | ||
| 574 | 5033000u, 0x7fffffu, 0x800000u, 0xfffffeu, 0xffffffu, | ||
| 575 | }; | ||
| 576 | for (std::uint32_t d : sample_codes) { | ||
| 577 | const float z = static_cast<float>(double(d) / 16777215.0); | ||
| 578 | float out = 0.0f; | ||
| 579 | EXPECT(prog.eval(z, 0.0f, 0.0f, out, err)); | ||
| 580 | EXPECT(f_bits(out) == f_bits(z)); | ||
| 581 | } | ||
| 582 | return 0; | ||
| 583 | } | ||
| 584 | |||
| 585 | int test_rejections() { | ||
| 586 | std::string why; | ||
| 587 | const auto base = make_synthetic_fragment(false, false, false, false); | ||
| 588 | for (float bad : {0.0f, -1.0f, 255.0f, 65536.0f, std::numeric_limits<float>::quiet_NaN()}) { | ||
| 589 | const Depth24Bias bias{0, 0.0f, 0.0f, bad}; | ||
| 590 | why.clear(); | ||
| 591 | EXPECT(depth24_patch_fragment(base, bias, why).empty() && !why.empty()); | ||
| 592 | EXPECT(depth24_depth_only_fragment(bias).empty()); | ||
| 593 | } | ||
| 594 | why.clear(); | ||
| 595 | EXPECT(depth24_patch_fragment(make_synthetic_fragment(false, true, false, false), {}, why).empty() && !why.empty()); | ||
| 596 | return 0; | ||
| 597 | } | ||
| 598 | |||
| 599 | } // namespace | ||
| 600 | |||
| 601 | int main() { | ||
| 602 | if (test_d16_exhaustive() != 0) return 1; | ||
| 603 | if (test_d16_and_d24_bias_and_clamp() != 0) return 1; | ||
| 604 | if (test_d24_boundary_codes() != 0) return 1; | ||
| 605 | if (test_rejections() != 0) return 1; | ||
| 606 | std::printf("depth24_fragment_test: ok (all 65536 D16 codes, ties, specials, bias/clamp, D24 parity)\n"); | ||
| 607 | return 0; | ||
| 608 | } | ||
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. | ||
| 1621 | void 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 | ||
| 1618 | int main() { | 1872 | int 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/fixtures/tiny_atexit.cpp b/runtime/test/fixtures/tiny_atexit.cpp index fbe071e7f..2719f98f4 100644 --- a/runtime/test/fixtures/tiny_atexit.cpp +++ b/runtime/test/fixtures/tiny_atexit.cpp | |||
| @@ -9,6 +9,10 @@ | |||
| 9 | // cexit _cexit() runs every handler and returns; main then returns 11 | 9 | // cexit _cexit() runs every handler and returns; main then returns 11 |
| 10 | // c_exit _c_exit() runs none and returns; main then returns 12, and exit runs them all | 10 | // c_exit _c_exit() runs none and returns; main then returns 12, and exit runs them all |
| 11 | // concurrent_exit a second thread calls _exit(7) while exit(7) runs a handler: it waits for them all | 11 | // concurrent_exit a second thread calls _exit(7) while exit(7) runs a handler: it waits for them all |
| 12 | // thread_local_exit a thread_local object of the main thread, then exit(13): it ends first, then the handlers | ||
| 13 | // thread_local_cexit the same object, then _cexit(): the same order, and main then returns 14 | ||
| 14 | // The thread_local destructor reaches the CRT through _register_thread_local_exe_atexit_callback, which the EXE's | ||
| 15 | // startup calls only when the image has one (this program has one in every mode, constructed only in the last two). | ||
| 12 | // One handler registers another while the handlers run: it must still run, next. | 16 | // One handler registers another while the handlers run: it must still run, next. |
| 13 | #include <windows.h> | 17 | #include <windows.h> |
| 14 | #include <process.h> // _cexit, _c_exit | 18 | #include <process.h> // _cexit, _c_exit |
| @@ -74,6 +78,15 @@ int main(int argc, char** argv) { | |||
| 74 | CloseHandle(CreateThread(nullptr, 0, quick_exit_thread, nullptr, 0, nullptr)); | 78 | CloseHandle(CreateThread(nullptr, 0, quick_exit_thread, nullptr, 0, nullptr)); |
| 75 | std::exit(7); | 79 | std::exit(7); |
| 76 | } | 80 | } |
| 81 | if (!std::strncmp(mode, "thread_local_", 13)) { | ||
| 82 | thread_local Tracer main_thread_local("thread_local"); // constructed here, on the main thread only | ||
| 83 | if (!std::strcmp(mode, "thread_local_exit")) std::exit(13); | ||
| 84 | if (!std::strcmp(mode, "thread_local_cexit")) { | ||
| 85 | _cexit(); | ||
| 86 | say("after _cexit"); | ||
| 87 | return 14; | ||
| 88 | } | ||
| 89 | } | ||
| 77 | if (!std::strcmp(mode, "exit")) std::exit(7); | 90 | if (!std::strcmp(mode, "exit")) std::exit(7); |
| 78 | if (!std::strcmp(mode, "_exit")) _exit(8); | 91 | if (!std::strcmp(mode, "_exit")) _exit(8); |
| 79 | if (!std::strcmp(mode, "quick_exit")) std::quick_exit(9); | 92 | if (!std::strcmp(mode, "quick_exit")) std::quick_exit(9); |
diff --git a/runtime/test/gameinput_no_sdl_test.cpp b/runtime/test/gameinput_no_sdl_test.cpp index a131dc7c9..7b165922a 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 | ||
| 100 | int scripted_pad(CreateFn create) { | 100 | int scripted_pad(CreateFn create) { |
| 101 | // Four presses (two overlapping A presses, Menu, a right-stick throw) and three rejected entries. | 101 | // Six presses (two overlapping A presses, Menu, B held 0.8 s, a right-stick throw, a Y press the title never reads |
| 102 | SetEnvironmentVariableA("LEONIDA_INPUT_SCRIPT", "a@1, START@2.5 ,a@1.2,rsup@4,bogus@1,a@-1,"); | 102 | // while it is down) and seven rejected entries (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,y@10,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,27 +203,48 @@ 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"); |
| 207 | check(read_at(input, device, 4.5).right_y == 0, "script: the stick is back at rest at 4.5 s"); | 213 | check(read_at(input, device, 4.5).right_y == 0, "script: the stick is back at rest at 4.5 s"); |
| 214 | // The title reads at 4.5 s and next at 60 s: y@10 starts and ends in between, and is still in the history. | ||
| 208 | check(read_at(input, device, 60).buttons == 0, "script: nothing is held after the script ends"); | 215 | check(read_at(input, device, 60).buttons == 0, "script: nothing is held after the script ends"); |
| 209 | 216 | ||
| 210 | // The history: the reading before the current one is the stick throw, and the one after that throw is the rest. | 217 | // The history, newest first: the rest after Y (10.3 s), the Y press (10.0 s), the rest after the stick throw |
| 218 | // (4.3 s), the stick throw. Each reading carries the script's time of the change, not the time of the read. | ||
| 211 | IGameInputReading* now = nullptr; | 219 | IGameInputReading* now = nullptr; |
| 212 | IGameInputReading* before = nullptr; | ||
| 213 | IGameInputReading* after = nullptr; | ||
| 214 | check(input->GetCurrentReading(GameInputKindUnknown, nullptr, &now) == S_OK && now, "script: a current reading"); | 220 | check(input->GetCurrentReading(GameInputKindUnknown, nullptr, &now) == S_OK && now, "script: a current reading"); |
| 215 | if (now) { | 221 | if (now) { |
| 222 | check(now->GetTimestamp() == 7'000'000 + 10'300'000, "script: the current reading is Y's release at 10.3 s"); | ||
| 223 | IGameInputReading* y = nullptr; | ||
| 224 | IGameInputReading* rest = nullptr; | ||
| 225 | IGameInputReading* stick = nullptr; | ||
| 226 | IGameInputReading* after = nullptr; | ||
| 216 | GameInputGamepadState s{}; | 227 | GameInputGamepadState s{}; |
| 217 | check(input->GetPreviousReading(now, GameInputKindGamepad, device, &before) == S_OK && before && | 228 | check(input->GetPreviousReading(now, GameInputKindGamepad, device, &y) == S_OK && y && |
| 218 | before->GetGamepadState(&s) && s.rightThumbstickY == 1.0f, | 229 | y->GetGamepadState(&s) && s.buttons == GameInputGamepadY && |
| 219 | "script: GetPreviousReading steps back to the stick throw"); | 230 | y->GetTimestamp() == 7'000'000 + 10'000'000, |
| 220 | if (before) { | 231 | "script: a press between two reads of the title is in the history, at its own time"); |
| 221 | check(input->GetNextReading(before, GameInputKindGamepad, nullptr, &after) == S_OK && after == now, | 232 | if (y) { |
| 222 | "script: GetNextReading steps forward to the current reading"); | 233 | check(input->GetPreviousReading(y, GameInputKindGamepad, device, &rest) == S_OK && rest && |
| 223 | before->Release(); | 234 | rest->GetGamepadState(&s) && s.buttons == 0 && s.rightThumbstickY == 0 && |
| 235 | rest->GetTimestamp() == 7'000'000 + 4'300'000, | ||
| 236 | "script: before Y, the stick's return at 4.3 s"); | ||
| 237 | check(input->GetNextReading(y, GameInputKindGamepad, nullptr, &after) == S_OK && after == now, | ||
| 238 | "script: GetNextReading steps forward from Y to the current reading"); | ||
| 239 | y->Release(); | ||
| 224 | } | 240 | } |
| 241 | if (rest) { | ||
| 242 | check(input->GetPreviousReading(rest, GameInputKindGamepad, device, &stick) == S_OK && stick && | ||
| 243 | stick->GetGamepadState(&s) && s.rightThumbstickY == 1.0f, | ||
| 244 | "script: GetPreviousReading steps back to the stick throw"); | ||
| 245 | rest->Release(); | ||
| 246 | } | ||
| 247 | if (stick) stick->Release(); | ||
| 225 | if (after) after->Release(); | 248 | if (after) after->Release(); |
| 226 | IGameInputReading* none = nullptr; | 249 | IGameInputReading* none = nullptr; |
| 227 | check(input->GetNextReading(now, GameInputKindUnknown, nullptr, &none) == GAMEINPUT_E_READING_NOT_FOUND && | 250 | check(input->GetNextReading(now, GameInputKindUnknown, nullptr, &none) == GAMEINPUT_E_READING_NOT_FOUND && |
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..37a1bd391 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, 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 | } |
| 66 | VKAPI_ATTR VkResult VKAPI_CALL bind(VkDevice, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize) { | 69 | VKAPI_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; |
| @@ -465,12 +468,17 @@ int main() { | |||
| 465 | const std::uint64_t own = fly.execute_begin(); | 468 | const std::uint64_t own = fly.execute_begin(); |
| 466 | leonida::TitleVaAliases aliases; | 469 | leonida::TitleVaAliases aliases; |
| 467 | aliases.record_removals(true); | 470 | aliases.record_removals(true); |
| 468 | std::uint64_t cursor = 0; | 471 | // What the console heaps' slot records are told (TitleVaAliases::add_listener). |
| 469 | { | 472 | struct Heard { |
| 470 | leonida::DescriptorRanges skip; | 473 | bool removed; |
| 471 | aliases.changed_ranges(cursor, skip); | 474 | std::uint64_t title_va, bytes, shader_va; |
| 472 | } | 475 | }; |
| 473 | const std::uint64_t invalidations = aliases.invalidations(); | 476 | std::vector<Heard> heard; |
| 477 | aliases.add_listener(&heard, [](void* to, leonida::TitleVaAliases::Change change, std::uint64_t va, | ||
| 478 | std::uint64_t bytes, std::uint64_t shader_va) { | ||
| 479 | static_cast<std::vector<Heard>*>(to)->push_back( | ||
| 480 | {change == leonida::TitleVaAliases::Change::removed, va, bytes, shader_va}); | ||
| 481 | }); | ||
| 474 | leonida::geometry_writes::note_released(flybase, flybase + kView); | 482 | leonida::geometry_writes::note_released(flybase, flybase + kView); |
| 475 | fly.drain_released(device, rt::d3d12::GeometryViews::kAfterExecutes, submitted, | 483 | fly.drain_released(device, rt::d3d12::GeometryViews::kAfterExecutes, submitted, |
| 476 | [&](std::uintptr_t source, std::size_t size, VkDeviceSize va) { | 484 | [&](std::uintptr_t source, std::size_t size, VkDeviceSize va) { |
| @@ -480,13 +488,12 @@ int main() { | |||
| 480 | fly.bytes() == kView && g_gone_blocks == gone, | 488 | fly.bytes() == kView && g_gone_blocks == gone, |
| 481 | "a view retired in before_execute_ is not reaped there, though the GPU is idle"); | 489 | "a view retired in before_execute_ is not reaped there, though the GPU is idle"); |
| 482 | 490 | ||
| 483 | leonida::DescriptorRanges changed; | ||
| 484 | const bool read = aliases.changed_ranges(cursor, changed); | ||
| 485 | changed.merge(); | ||
| 486 | std::vector<std::pair<std::uint64_t, std::uint64_t>> removed; | 491 | std::vector<std::pair<std::uint64_t, std::uint64_t>> removed; |
| 487 | aliases.take_removed(removed); | 492 | aliases.take_removed(removed); |
| 488 | check(read && aliases.invalidations() != invalidations && changed.overlaps(flybase, kView) && | 493 | aliases.remove_listener(&heard); |
| 489 | removed.size() == 1 && removed[0].first == va_f && removed[0].second == kView, | 494 | check(heard.size() == 1 && heard[0].removed && heard[0].title_va == flybase && heard[0].bytes == kView && |
| 495 | heard[0].shader_va == va_f && removed.size() == 1 && removed[0].first == va_f && | ||
| 496 | removed[0].second == kView, | ||
| 490 | "the retirement invalidates the heap slots and key answers made through the view without an alias"); | 497 | "the retirement invalidates the heap slots and key answers made through the view without an alias"); |
| 491 | 498 | ||
| 492 | submitted = 8; // this replay's submission | 499 | submitted = 8; // this replay's submission |
| @@ -510,6 +517,109 @@ int main() { | |||
| 510 | } | 517 | } |
| 511 | VirtualFree(fly_title, 0, MEM_RELEASE); | 518 | VirtualFree(fly_title, 0, MEM_RELEASE); |
| 512 | 519 | ||
| 520 | // 14. LEONIDA_GEOMETRY_HOST: the copies' memory type. A discrete GPU's types: 0 VRAM, 1 VRAM through the BAR, | ||
| 521 | // 2 system memory write-combined, 3 system memory write-back. 1 takes type 3 (write-back preferred), 2 type 2, | ||
| 522 | // unset any host-visible type with device-local preferred (the BAR); a device whose host-visible types are all | ||
| 523 | // device-local (an integrated GPU) keeps them all. | ||
| 524 | { | ||
| 525 | struct TypedDevice : FakeDevice { | ||
| 526 | VkPhysicalDeviceMemoryProperties memory{}; | ||
| 527 | std::uint32_t bits = 0; | ||
| 528 | VkMemoryPropertyFlags preferred = 0; | ||
| 529 | VkDeviceMemory allocate(const VkMemoryRequirements& r, VkMemoryPropertyFlags required, | ||
| 530 | VkMemoryPropertyFlags wanted, VkMemoryPropertyFlags* chosen, bool address) { | ||
| 531 | bits = r.memoryTypeBits; | ||
| 532 | preferred = wanted; | ||
| 533 | return FakeDevice::allocate(r, required, wanted, chosen, address); | ||
| 534 | } | ||
| 535 | }; | ||
| 536 | constexpr VkMemoryPropertyFlags kLocal = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, | ||
| 537 | kHost = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | | ||
| 538 | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, | ||
| 539 | kCached = VK_MEMORY_PROPERTY_HOST_CACHED_BIT; | ||
| 540 | TypedDevice discrete; | ||
| 541 | discrete.memory.memoryTypeCount = 4; | ||
| 542 | const VkMemoryPropertyFlags discrete_types[4] = {kLocal, kLocal | kHost, kHost, kHost | kCached}; | ||
| 543 | for (int i = 0; i < 4; ++i) discrete.memory.memoryTypes[i].propertyFlags = discrete_types[i]; | ||
| 544 | TypedDevice integrated; | ||
| 545 | integrated.memory.memoryTypeCount = 2; | ||
| 546 | integrated.memory.memoryTypes[0].propertyFlags = kLocal; | ||
| 547 | integrated.memory.memoryTypes[1].propertyFlags = kLocal | kHost | kCached; | ||
| 548 | auto* host_title = | ||
| 549 | static_cast<std::uint8_t*>(VirtualAlloc(nullptr, kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); | ||
| 550 | if (!host_title) return 1; | ||
| 551 | const auto hbase = reinterpret_cast<std::uintptr_t>(host_title); | ||
| 552 | const auto made_with = [&](TypedDevice& dev, const char* setting) { | ||
| 553 | _putenv_s("LEONIDA_GEOMETRY_HOST", setting); | ||
| 554 | dev.bits = ~0u; | ||
| 555 | dev.preferred = 0; | ||
| 556 | rt::d3d12::GeometryViews v; | ||
| 557 | const bool made = v.resolve(dev, hbase, kView, copy) != 0; | ||
| 558 | const int kind = v.system_memory(); | ||
| 559 | v.release(dev); | ||
| 560 | return made ? kind : -1; | ||
| 561 | }; | ||
| 562 | check(made_with(discrete, "1") == rt::d3d12::TitleBufferWindows::kSystemCached && discrete.bits == 1u << 3 && | ||
| 563 | discrete.preferred == kCached, | ||
| 564 | "LEONIDA_GEOMETRY_HOST=1 puts the copies in write-back system memory, never the BAR"); | ||
| 565 | check(made_with(discrete, "2") == rt::d3d12::TitleBufferWindows::kSystemUncached && discrete.bits == 1u << 2 && | ||
| 566 | discrete.preferred == 0, | ||
| 567 | "LEONIDA_GEOMETRY_HOST=2 puts them in write-combined system memory"); | ||
| 568 | check(made_with(discrete, "") == rt::d3d12::TitleBufferWindows::kDeviceLocal && discrete.bits == 0xfu && | ||
| 569 | discrete.preferred == kLocal, | ||
| 570 | "unset, every type the buffer allows is tried, device-local first"); | ||
| 571 | check(made_with(integrated, "1") == rt::d3d12::TitleBufferWindows::kSystemCached && integrated.bits == 0xfu, | ||
| 572 | "on a device with no host type outside device-local memory, the types are left as they are"); | ||
| 573 | _putenv_s("LEONIDA_GEOMETRY_HOST", ""); | ||
| 574 | check(g_live_buffers == 0, "the memory-type views free their blocks"); | ||
| 575 | |||
| 576 | // 15. A retired view is copied once more from the title's pages when they are readable (they hold new bytes), | ||
| 577 | // and keeps what it held when they are not (decommitted or unmapped). | ||
| 578 | rt::d3d12::GeometryViews last; | ||
| 579 | std::memset(host_title, 0x11, kView); | ||
| 580 | const std::uint64_t va_l = last.resolve(device, hbase, kView, copy); | ||
| 581 | std::uint64_t host_l = 0, bytes_l = 0; | ||
| 582 | check(va_l && last.lookup(device.arena.address + va_l, host_l, bytes_l), "a view to retire"); | ||
| 583 | auto* held = reinterpret_cast<const std::uint8_t*>(host_l); | ||
| 584 | // The pages' new bytes: the watched tiles are opened first (no fault handler here). | ||
| 585 | leonida::geometry_writes::notify(hbase, hbase + kView, leonida::geometry_writes::Event::open); | ||
| 586 | std::memset(host_title, 0x22, kView); | ||
| 587 | g_copies.clear(); | ||
| 588 | check(last.retire_range(hbase, hbase + kView, 1, [](std::uintptr_t, std::size_t, VkDeviceSize) {}, copy) == 1 && | ||
| 589 | held[0] == 0x22 && held[kView - 1] == 0x22 && last.final_copies() == 1 && g_copies.size() == 1, | ||
| 590 | "a retired view whose pages are readable is copied from them once more"); | ||
| 591 | const std::uint64_t va_l2 = last.resolve(device, hbase, kView, copy); | ||
| 592 | std::uint64_t host_l2 = 0; | ||
| 593 | check(va_l2 && last.lookup(device.arena.address + va_l2, host_l2, bytes_l), "and made again"); | ||
| 594 | auto* held2 = reinterpret_cast<const std::uint8_t*>(host_l2); | ||
| 595 | leonida::geometry_writes::notify(hbase, hbase + kView, leonida::geometry_writes::Event::open); | ||
| 596 | std::memset(host_title, 0x33, kView); | ||
| 597 | const auto unreadable = [](std::uint8_t*, const std::uint8_t*, std::size_t) { | ||
| 598 | return rt::d3d12::GeometryCopy::unreadable; | ||
| 599 | }; | ||
| 600 | check(last.retire_range(hbase, hbase + kView, 2, [](std::uintptr_t, std::size_t, VkDeviceSize) {}, | ||
| 601 | unreadable) == 1 && | ||
| 602 | held2[0] == 0x22 && last.final_copies() == 1, | ||
| 603 | "one whose pages are not readable keeps what it held"); | ||
| 604 | check(last.reap(device, 2) == 2 && last.bytes() == 0, "both are freed at their tickets"); | ||
| 605 | last.release(device); | ||
| 606 | |||
| 607 | // 16. A full release queue first joins ranges that touch (unmaps report page runs): 65536 neighbouring ranges | ||
| 608 | // and one apart from them are two ranges, not one covering everything between them. | ||
| 609 | rt::d3d12::GeometryViews coalesce; | ||
| 610 | check(coalesce.resolve(device, hbase, kView, copy) != 0, "a view to watch the pages"); | ||
| 611 | for (std::size_t i = 0; i < 65536; ++i) | ||
| 612 | leonida::geometry_writes::note_released(hbase + i * 8, hbase + i * 8 + 8); | ||
| 613 | leonida::geometry_writes::note_released(hbase + kView - 4096, hbase + kView); | ||
| 614 | std::vector<std::pair<std::uintptr_t, std::uintptr_t>> joined; | ||
| 615 | leonida::geometry_writes::take_released(coalesce.release_queue(), joined); | ||
| 616 | check(joined.size() == 2 && joined[0] == std::make_pair(hbase, hbase + 65536 * 8) && | ||
| 617 | joined[1] == std::make_pair(hbase + kView - 4096, hbase + kView), | ||
| 618 | "65536 touching ranges become one, and a range apart from them stays apart"); | ||
| 619 | coalesce.release(device); | ||
| 620 | VirtualFree(host_title, 0, MEM_RELEASE); | ||
| 621 | } | ||
| 622 | |||
| 513 | std::printf("%d checks, %d failures\n", g_checks, g_failures); | 623 | std::printf("%d checks, %d failures\n", g_checks, g_failures); |
| 514 | return g_failures ? 1 : 0; | 624 | return g_failures ? 1 : 0; |
| 515 | } | 625 | } |
diff --git a/runtime/test/glsl/cs_bindless_dimensions.comp b/runtime/test/glsl/cs_bindless_dimensions.comp new file mode 100644 index 000000000..4a26fe276 --- /dev/null +++ b/runtime/test/glsl/cs_bindless_dimensions.comp | |||
| @@ -0,0 +1,30 @@ | |||
| 1 | #version 460 | ||
| 2 | // Reads one texel of each of many images through the bindless set 0 (src/vulkan_bindless.h), for | ||
| 3 | // vk_bindless_dimensions_test: thread i reads the image at index indices[i] of the sampled array of one dimension | ||
| 4 | // (pc.dimension: 0 1D, 1 2D array, 2 3D; bindings 5, 3 and 6, as tools/rdna2spirv.py declares them) and writes the | ||
| 5 | // texel's red channel, as bits, to result[i]. One thread per workgroup, so each index is dynamically uniform and | ||
| 6 | // the test needs no non-uniform indexing feature. | ||
| 7 | #extension GL_EXT_nonuniform_qualifier : require | ||
| 8 | #extension GL_EXT_samplerless_texture_functions : require | ||
| 9 | |||
| 10 | layout(local_size_x = 1) in; // one image per workgroup: the index is uniform there | ||
| 11 | |||
| 12 | layout(push_constant) uniform Pass { uint dimension; uint count; } pc; | ||
| 13 | |||
| 14 | layout(set = 0, binding = 3) uniform texture2DArray layers[]; | ||
| 15 | layout(set = 0, binding = 5) uniform texture1D lines[]; | ||
| 16 | layout(set = 0, binding = 6) uniform texture3D volumes[]; | ||
| 17 | |||
| 18 | layout(set = 1, binding = 0, std430) writeonly buffer Result { uint result[]; }; | ||
| 19 | layout(set = 1, binding = 1, std430) readonly buffer Indices { uint indices[]; }; | ||
| 20 | |||
| 21 | void main() { | ||
| 22 | const uint i = gl_GlobalInvocationID.x; | ||
| 23 | if (i >= pc.count) return; | ||
| 24 | const uint index = indices[i]; | ||
| 25 | float red; | ||
| 26 | if (pc.dimension == 0) red = texelFetch(lines[index], 0, 0).r; | ||
| 27 | else if (pc.dimension == 1) red = texelFetch(layers[index], ivec3(0), 0).r; | ||
| 28 | else red = texelFetch(volumes[index], ivec3(0), 0).r; | ||
| 29 | result[i] = floatBitsToUint(red); | ||
| 30 | } | ||
diff --git a/runtime/test/glsl/cs_group_marker.comp b/runtime/test/glsl/cs_group_marker.comp new file mode 100644 index 000000000..f98d089aa --- /dev/null +++ b/runtime/test/glsl/cs_group_marker.comp | |||
| @@ -0,0 +1,16 @@ | |||
| 1 | // indirect_clamp_test's marker: every workgroup adds 1 to its own word, so a dispatch whose groups all ran exactly | ||
| 2 | // once leaves 1 in each of its words. Only one dimension of a test dispatch is larger than 1, so x + y + z names the | ||
| 3 | // group; a group past `groups` (which the dispatch should never run) counts in the word after them. | ||
| 4 | // SPIR-V: runtime/test/cs_group_marker_spv.h (glslangValidator -V --target-env vulkan1.2 -Os). | ||
| 5 | #version 460 | ||
| 6 | #extension GL_EXT_buffer_reference : require | ||
| 7 | layout(local_size_x = 1) in; | ||
| 8 | layout(buffer_reference, std430, buffer_reference_align = 4) buffer Marks { uint data[]; }; | ||
| 9 | layout(push_constant) uniform Params { | ||
| 10 | Marks marks; | ||
| 11 | uint groups; | ||
| 12 | } p; | ||
| 13 | void main() { | ||
| 14 | const uint group = gl_WorkGroupID.x + gl_WorkGroupID.y + gl_WorkGroupID.z; | ||
| 15 | atomicAdd(p.marks.data[min(group, p.groups)], 1u); | ||
| 16 | } | ||
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 | |||
| 15 | namespace heavy = leonida::heavy_pipeline_cache; | ||
| 16 | |||
| 17 | static 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 | |||
| 32 | static 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 | |||
| 72 | static 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 | |||
| 103 | int 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/indirect_clamp_test.cpp b/runtime/test/indirect_clamp_test.cpp index 3f34d4c43..3a119b952 100644 --- a/runtime/test/indirect_clamp_test.cpp +++ b/runtime/test/indirect_clamp_test.cpp | |||
| @@ -2,11 +2,15 @@ | |||
| 2 | // | 2 | // |
| 3 | // - in-range records of every kind (draw, draw indexed, dispatch, mesh dispatch) come back bit-identical, and the | 3 | // - in-range records of every kind (draw, draw indexed, dispatch, mesh dispatch) come back bit-identical, and the |
| 4 | // pass counts nothing as clamped; | 4 | // pass counts nothing as clamped; |
| 5 | // - a garbage record is bounded (2^24 vertices, 2^26 vertex instances, 65 535 groups per dimension, 2^20 groups per | 5 | // - a garbage record is bounded (2^26 vertex instances, 65 535 groups per dimension, 2^20 groups per dispatch) |
| 6 | // dispatch) instead of asking for billions of groups; | 6 | // instead of asking for billions of groups, and a draw record of 2^23 vertices or more runs empty and free; |
| 7 | // - a counted batch clamps the count to max_command_count and empties the records past it; | 7 | // - a counted batch clamps the count to max_command_count and empties the records past it; |
| 8 | // - a batch whose records fit but whose total work passes the 2^27 budget runs all but the records that no longer | 8 | // - a batch whose records fit but whose total work passes the 2^27 budget runs all but the records that no longer |
| 9 | // fit, so thousands of garbage records cannot run for seconds. | 9 | // fit, so thousands of garbage records cannot run for seconds; |
| 10 | // - a dispatch is bounded by the device's own maxComputeWorkGroupCount, not by Vulkan's minimum of 65 535: a real | ||
| 11 | // indirect dispatch of 70 000 x 1 x 1 groups (and of 65 535 in x or y, the old limit) through the clamped scratch | ||
| 12 | // runs every group exactly once (cs_group_marker.comp marks each one). The idea is from codec-d/cool_fox | ||
| 13 | // docs/findings.md ("blocky patches: indirect dispatches cut at 65,535 groups"); no code of theirs is used. | ||
| 10 | // | 14 | // |
| 11 | // A record that asks for billions of groups or vertices would run until the host resets the driver, so this test is | 15 | // A record that asks for billions of groups or vertices would run until the host resets the driver, so this test is |
| 12 | // about the values the pass writes, never about running such a dispatch here: every case ends in a copy of the | 16 | // about the values the pass writes, never about running such a dispatch here: every case ends in a copy of the |
| @@ -17,6 +21,7 @@ | |||
| 17 | #include "vk_test_device.h" | 21 | #include "vk_test_device.h" |
| 18 | 22 | ||
| 19 | #include "../src/vulkan_indirect_clamp.h" | 23 | #include "../src/vulkan_indirect_clamp.h" |
| 24 | #include "cs_group_marker_spv.h" | ||
| 20 | 25 | ||
| 21 | #include <algorithm> | 26 | #include <algorithm> |
| 22 | #include <cstdint> | 27 | #include <cstdint> |
| @@ -98,6 +103,10 @@ struct Env { | |||
| 98 | out.counters.records_clamped = after.records_clamped - before.records_clamped; | 103 | out.counters.records_clamped = after.records_clamped - before.records_clamped; |
| 99 | out.counters.counts_clamped = after.counts_clamped - before.counts_clamped; | 104 | out.counters.counts_clamped = after.counts_clamped - before.counts_clamped; |
| 100 | out.counters.over_budget = after.over_budget - before.over_budget; | 105 | out.counters.over_budget = after.over_budget - before.over_budget; |
| 106 | out.counters.dispatch_records = after.dispatch_records - before.dispatch_records; | ||
| 107 | out.counters.dispatch_wide = after.dispatch_wide - before.dispatch_wide; | ||
| 108 | out.counters.dispatch_widest = after.dispatch_widest; // the largest so far: cases go from narrow to wide | ||
| 109 | out.counters.dispatch_cut = after.dispatch_cut - before.dispatch_cut; | ||
| 101 | // The scratch is idle once the queue is; hand it back for the next case like a completed submission does. | 110 | // The scratch is idle once the queue is; hand it back for the next case like a completed submission does. |
| 102 | clamp.retire(VK_NULL_HANDLE, 0); | 111 | clamp.retire(VK_NULL_HANDLE, 0); |
| 103 | clamp.collect(); | 112 | clamp.collect(); |
| @@ -167,17 +176,42 @@ int main() { | |||
| 167 | CHECK(out.counters.records_clamped == 0 && out.counters.counts_clamped == 0); | 176 | CHECK(out.counters.records_clamped == 0 && out.counters.counts_clamped == 0); |
| 168 | } | 177 | } |
| 169 | 178 | ||
| 170 | // 2. A draw that asks for four billion vertices in four billion instances is cut to 2^24 vertices, and the | 179 | // 2. A draw that asks for four billion vertices in four billion instances is an unfilled slot: it runs empty, |
| 171 | // instances to what keeps count * instances within 2^26. | 180 | // keeping its locations, and charges nothing. |
| 172 | { | 181 | { |
| 173 | const std::uint32_t values[4] = {0xFFFFFFF0u, 0xFFFFFFFFu, 4, 6}; | 182 | const std::uint32_t values[4] = {0xFFFFFFF0u, 0xFFFFFFFFu, 4, 6}; |
| 174 | Clamped out{}; | 183 | Clamped out{}; |
| 175 | CHECK(env.run(leonida::indirect_clamp_draw, 16, 1, 4, values, nullptr, out)); | 184 | CHECK(env.run(leonida::indirect_clamp_draw, 16, 1, 4, values, nullptr, out)); |
| 176 | const auto words = record(out, 0, 4); | 185 | const auto words = record(out, 0, 4); |
| 177 | CHECK(words[0] == leonida::indirect_clamp_max_vertices); | 186 | CHECK(words[0] == 0 && words[1] == 0); |
| 178 | CHECK(words[1] == leonida::indirect_clamp_max_vertex_instances / leonida::indirect_clamp_max_vertices); | ||
| 179 | CHECK(words[2] == 4 && words[3] == 6); | 187 | CHECK(words[2] == 4 && words[3] == 6); |
| 180 | CHECK(out.counters.records_clamped == 1); | 188 | CHECK(out.counters.records_clamped == 1 && out.counters.over_budget == 0); |
| 189 | } | ||
| 190 | |||
| 191 | // 2b. Just under the unfilled count a draw is a draw: its vertices stay, and its instances are cut to what keeps | ||
| 192 | // count * instances within 2^26. At the unfilled count it runs empty. | ||
| 193 | { | ||
| 194 | const std::uint32_t most = leonida::indirect_clamp_unfilled_draw - 1; | ||
| 195 | const std::uint32_t values[4 * 2] = {most, 100, 0, 0, leonida::indirect_clamp_unfilled_draw, 1, 0, 0}; | ||
| 196 | Clamped out{}; | ||
| 197 | CHECK(env.run(leonida::indirect_clamp_draw, 16, 2, 4, values, nullptr, out)); | ||
| 198 | const auto under = record(out, 0, 4); | ||
| 199 | CHECK(under[0] == most && under[1] == leonida::indirect_clamp_max_vertex_instances / most); | ||
| 200 | CHECK(record(out, 1, 4)[0] == 0 && record(out, 1, 4)[1] == 0); | ||
| 201 | CHECK(out.counters.records_clamped == 2); | ||
| 202 | } | ||
| 203 | |||
| 204 | // 2c. Garbage counts ahead of a real draw in one list: before, each was cut to 2^24 vertices and charged them, so | ||
| 205 | // eight used up the 2^27 budget and every later draw ran empty. Now they are free and the real draw runs. | ||
| 206 | { | ||
| 207 | std::vector<std::uint32_t> values; | ||
| 208 | for (std::uint32_t r = 0; r < 16; ++r) values.insert(values.end(), {0x01000000u + r, 1, 0, 0}); | ||
| 209 | const std::uint32_t valid[] = {300, 2, 3, 4}; | ||
| 210 | values.insert(values.end(), valid, valid + 4); | ||
| 211 | Clamped out{}; | ||
| 212 | CHECK(env.run(leonida::indirect_clamp_draw, 16, 17, 4, values.data(), nullptr, out)); | ||
| 213 | CHECK(out.counters.over_budget == 0 && out.counters.records_clamped == 16); | ||
| 214 | CHECK(record(out, 16, 4) == std::vector<std::uint32_t>(valid, valid + 4)); | ||
| 181 | } | 215 | } |
| 182 | 216 | ||
| 183 | // 3. A counted draw: the count is clamped to max_command_count, and the records past min(count, max) are empty. | 217 | // 3. A counted draw: the count is clamped to max_command_count, and the records past min(count, max) are empty. |
| @@ -210,14 +244,23 @@ int main() { | |||
| 210 | CHECK(out.counters.counts_clamped == 1); | 244 | CHECK(out.counters.counts_clamped == 1); |
| 211 | } | 245 | } |
| 212 | 246 | ||
| 213 | // 4. An indexed draw keeps its two locations and its first instance, and bounds its index count. | 247 | // 4. An indexed draw keeps its two locations and its first instance: an unfilled index count runs empty, and a |
| 248 | // real one keeps its indices with the instances bounded. | ||
| 214 | { | 249 | { |
| 215 | const std::uint32_t values[5] = {0xFFFFFFFFu, 0xFFFFFFFFu, 10, 20, 30}; | 250 | const std::uint32_t values[5] = {0xFFFFFFFFu, 0xFFFFFFFFu, 10, 20, 30}; |
| 216 | Clamped out{}; | 251 | Clamped out{}; |
| 217 | CHECK(env.run(leonida::indirect_clamp_draw_indexed, 20, 1, 5, values, nullptr, out)); | 252 | CHECK(env.run(leonida::indirect_clamp_draw_indexed, 20, 1, 5, values, nullptr, out)); |
| 218 | const auto words = record(out, 0, 5); | 253 | const auto words = record(out, 0, 5); |
| 219 | CHECK(words[0] == leonida::indirect_clamp_max_vertices); | 254 | CHECK(words[0] == 0 && words[1] == 0); |
| 220 | CHECK(words[1] == leonida::indirect_clamp_max_vertex_instances / leonida::indirect_clamp_max_vertices); | 255 | CHECK(words[2] == 10 && words[3] == 20 && words[4] == 30); |
| 256 | CHECK(out.counters.records_clamped == 1); | ||
| 257 | } | ||
| 258 | { | ||
| 259 | const std::uint32_t values[5] = {3000, 0xFFFFFFFFu, 10, 20, 30}; | ||
| 260 | Clamped out{}; | ||
| 261 | CHECK(env.run(leonida::indirect_clamp_draw_indexed, 20, 1, 5, values, nullptr, out)); | ||
| 262 | const auto words = record(out, 0, 5); | ||
| 263 | CHECK(words[0] == 3000 && words[1] == leonida::indirect_clamp_max_vertex_instances / 3000); | ||
| 221 | CHECK(words[2] == 10 && words[3] == 20 && words[4] == 30); | 264 | CHECK(words[2] == 10 && words[3] == 20 && words[4] == 30); |
| 222 | CHECK(out.counters.records_clamped == 1); | 265 | CHECK(out.counters.records_clamped == 1); |
| 223 | } | 266 | } |
| @@ -241,16 +284,40 @@ int main() { | |||
| 241 | CHECK(out.counters.records_clamped == 1); | 284 | CHECK(out.counters.records_clamped == 1); |
| 242 | } | 285 | } |
| 243 | 286 | ||
| 244 | // 6b. A dispatch over the per-dimension limit is cut there, and one over 2^20 groups in all runs empty. | 287 | // 6b. A dispatch over the device's per-dimension limit is cut there (y here; a device whose y limit is above 2^20 |
| 288 | // runs it empty instead, as more than 2^20 groups), and one over 2^20 groups in all runs empty. | ||
| 245 | { | 289 | { |
| 246 | const std::uint32_t values[3 * 2] = {0x10000000u, 1, 1, 65535, 65535, 1}; | 290 | const std::uint32_t max_y = leonida::indirect_clamp_dispatch_limit(properties.limits, 1); |
| 291 | const std::uint32_t values[3 * 2] = {1, 0x10000000u, 1, 65535, 65535, 1}; | ||
| 247 | Clamped out{}; | 292 | Clamped out{}; |
| 248 | CHECK(env.run(leonida::indirect_clamp_dispatch, 12, 2, 3, values, nullptr, out)); | 293 | CHECK(env.run(leonida::indirect_clamp_dispatch, 12, 2, 3, values, nullptr, out)); |
| 249 | const auto per_dimension = record(out, 0, 3); | 294 | const auto per_dimension = record(out, 0, 3); |
| 250 | CHECK(per_dimension[0] == leonida::indirect_clamp_max_group_dimension && per_dimension[1] == 1 && | 295 | if (max_y <= leonida::indirect_clamp_max_groups) |
| 251 | per_dimension[2] == 1); | 296 | CHECK(per_dimension[0] == 1 && per_dimension[1] == max_y && per_dimension[2] == 1); |
| 297 | else | ||
| 298 | CHECK(all_zero(per_dimension)); | ||
| 252 | CHECK(all_zero(record(out, 1, 3))); | 299 | CHECK(all_zero(record(out, 1, 3))); |
| 253 | CHECK(out.counters.records_clamped == 2); | 300 | CHECK(out.counters.records_clamped == 2); |
| 301 | // The dispatch counters: both records, neither wider than 65 535 in x, and the first cut at the device's | ||
| 302 | // limit where it still runs. | ||
| 303 | CHECK(out.counters.dispatch_records == 2 && out.counters.dispatch_wide == 0); | ||
| 304 | CHECK(out.counters.dispatch_cut == (max_y <= leonida::indirect_clamp_max_groups ? 1u : 0u)); | ||
| 305 | } | ||
| 306 | |||
| 307 | // 6c. x within the device's limit is not cut at 65 535: 70 000 groups (fewer than 2^20) come back as asked on a | ||
| 308 | // device that runs them, and are cut at its limit on one that does not. | ||
| 309 | { | ||
| 310 | const std::uint32_t max_x = leonida::indirect_clamp_dispatch_limit(properties.limits, 0); | ||
| 311 | const std::uint32_t values[3] = {70000, 1, 1}; | ||
| 312 | Clamped out{}; | ||
| 313 | CHECK(env.run(leonida::indirect_clamp_dispatch, 12, 1, 3, values, nullptr, out)); | ||
| 314 | const auto words = record(out, 0, 3); | ||
| 315 | CHECK(words[0] == std::min<std::uint32_t>(70000, max_x) && words[1] == 1 && words[2] == 1); | ||
| 316 | CHECK(out.counters.records_clamped == (max_x >= 70000 ? 0u : 1u)); | ||
| 317 | // Counted as wider than 65 535 where it runs so, and as cut at the device's limit where it is cut. | ||
| 318 | CHECK(out.counters.dispatch_records == 1 && out.counters.dispatch_wide == (max_x >= 70000 ? 1u : 0u)); | ||
| 319 | CHECK(out.counters.dispatch_widest == std::min<std::uint32_t>(70000, max_x)); | ||
| 320 | CHECK(out.counters.dispatch_cut == (max_x >= 70000 ? 0u : 1u)); | ||
| 254 | } | 321 | } |
| 255 | 322 | ||
| 256 | // 7. A console mesh dispatch uses only x. | 323 | // 7. A console mesh dispatch uses only x. |
| @@ -300,7 +367,7 @@ int main() { | |||
| 300 | 367 | ||
| 301 | // Three calls on one list consume two full draw allowances. A fresh list starts at zero. | 368 | // Three calls on one list consume two full draw allowances. A fresh list starts at zero. |
| 302 | { | 369 | { |
| 303 | const std::uint32_t args[] = {1u << 24, 4, 0, 0}; | 370 | const std::uint32_t args[] = {1u << 22, 16, 0, 0}; // 2^26 units: half the list budget, a real draw |
| 304 | std::memcpy(env.arguments_map, args, sizeof(args)); | 371 | std::memcpy(env.arguments_map, args, sizeof(args)); |
| 305 | auto batch = clamp.batch(); | 372 | auto batch = clamp.batch(); |
| 306 | leonida::ClampedIndirect jobs[4]{}; | 373 | leonida::ClampedIndirect jobs[4]{}; |
| @@ -331,7 +398,7 @@ int main() { | |||
| 331 | // clamped, none falls back to the application's buffer; the calls past the slots only lose their counters. | 398 | // clamped, none falls back to the application's buffer; the calls past the slots only lose their counters. |
| 332 | { | 399 | { |
| 333 | std::memset(env.arguments_map, 0, size_t(env.argument_bytes)); | 400 | std::memset(env.arguments_map, 0, size_t(env.argument_bytes)); |
| 334 | const std::uint32_t huge[4] = {0xFFFFFFF0u, 0xFFFFFFFFu, 4, 6}; | 401 | const std::uint32_t huge[4] = {0x00400000u, 0xFFFFFFFFu, 4, 6}; // 2^22 vertices: a draw, its instances cut |
| 335 | std::memcpy(env.arguments_map, huge, sizeof huge); | 402 | std::memcpy(env.arguments_map, huge, sizeof huge); |
| 336 | std::memset(env.readback_map, 0xcd, size_t(env.readback_bytes)); | 403 | std::memset(env.readback_map, 0xcd, size_t(env.readback_bytes)); |
| 337 | const auto before = clamp.counters(); | 404 | const auto before = clamp.counters(); |
| @@ -362,12 +429,112 @@ int main() { | |||
| 362 | }); | 429 | }); |
| 363 | CHECK(ok); | 430 | CHECK(ok); |
| 364 | const auto* words = static_cast<const std::uint32_t*>(env.readback_map); | 431 | const auto* words = static_cast<const std::uint32_t*>(env.readback_map); |
| 365 | CHECK(words[0] == leonida::indirect_clamp_max_vertices && words[2] == 4 && words[3] == 6); | 432 | CHECK(words[0] == 0x00400000u && |
| 433 | words[1] == leonida::indirect_clamp_max_vertex_instances / 0x00400000u && words[2] == 4 && | ||
| 434 | words[3] == 6); | ||
| 366 | } | 435 | } |
| 367 | clamp.retire(VK_NULL_HANDLE, 0); | 436 | clamp.retire(VK_NULL_HANDLE, 0); |
| 368 | clamp.collect(); | 437 | clamp.collect(); |
| 369 | } | 438 | } |
| 370 | 439 | ||
| 440 | // 10. Real indirect dispatches through the clamped scratch: every group runs exactly once. 70 000 x 1 x 1 is past | ||
| 441 | // the old fixed 65 535 (the groups past it never ran, leaving their output stale); 65 535 in x and in y are | ||
| 442 | // exactly at it. A size past this device's own limit is skipped: the clamp cuts it there by design. | ||
| 443 | { | ||
| 444 | const auto vkfn = [&](const char* name) { return device.device_proc(device.device, name); }; | ||
| 445 | VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | ||
| 446 | module_info.codeSize = sizeof(leonida::cs_group_marker_spirv); | ||
| 447 | module_info.pCode = leonida::cs_group_marker_spirv; | ||
| 448 | VkShaderModule module = VK_NULL_HANDLE; | ||
| 449 | CHECK(reinterpret_cast<PFN_vkCreateShaderModule>(vkfn("vkCreateShaderModule"))(device.device, &module_info, | ||
| 450 | nullptr, &module) == VK_SUCCESS); | ||
| 451 | struct MarkerPush { | ||
| 452 | VkDeviceAddress marks; | ||
| 453 | std::uint32_t groups; | ||
| 454 | std::uint32_t pad; | ||
| 455 | }; | ||
| 456 | const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(MarkerPush)}; | ||
| 457 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; | ||
| 458 | layout_info.pushConstantRangeCount = 1; | ||
| 459 | layout_info.pPushConstantRanges = ⦥ | ||
| 460 | VkPipelineLayout layout = VK_NULL_HANDLE; | ||
| 461 | CHECK(reinterpret_cast<PFN_vkCreatePipelineLayout>(vkfn("vkCreatePipelineLayout"))( | ||
| 462 | device.device, &layout_info, nullptr, &layout) == VK_SUCCESS); | ||
| 463 | VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | ||
| 464 | pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | ||
| 465 | pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; | ||
| 466 | pipeline_info.stage.module = module; | ||
| 467 | pipeline_info.stage.pName = "main"; | ||
| 468 | pipeline_info.layout = layout; | ||
| 469 | VkPipeline pipeline = VK_NULL_HANDLE; | ||
| 470 | CHECK(reinterpret_cast<PFN_vkCreateComputePipelines>(vkfn("vkCreateComputePipelines"))( | ||
| 471 | device.device, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline) == VK_SUCCESS); | ||
| 472 | |||
| 473 | constexpr std::uint32_t kMostGroups = 70000; | ||
| 474 | void* marks_map = nullptr; | ||
| 475 | const VkBuffer marks = device.buffer(VkDeviceSize(kMostGroups + 1) * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, | ||
| 476 | &marks_map); | ||
| 477 | CHECK(marks && marks_map && pipeline); | ||
| 478 | struct Case { | ||
| 479 | std::uint32_t x, y, z; | ||
| 480 | }; | ||
| 481 | const Case cases[] = {{70000, 1, 1}, {65535, 1, 1}, {1, 65535, 1}}; | ||
| 482 | for (const Case& c : cases) { | ||
| 483 | if (!marks || !pipeline) break; | ||
| 484 | const std::uint32_t groups = c.x * c.y * c.z; | ||
| 485 | if (c.x > leonida::indirect_clamp_dispatch_limit(properties.limits, 0) || | ||
| 486 | c.y > leonida::indirect_clamp_dispatch_limit(properties.limits, 1) || | ||
| 487 | c.z > leonida::indirect_clamp_dispatch_limit(properties.limits, 2)) { | ||
| 488 | std::printf("indirect_clamp_test: %u x %u x %u is past this device's maxComputeWorkGroupCount; " | ||
| 489 | "skipped\n", c.x, c.y, c.z); | ||
| 490 | continue; | ||
| 491 | } | ||
| 492 | const std::uint32_t args[3] = {c.x, c.y, c.z}; | ||
| 493 | std::memset(env.arguments_map, 0, size_t(env.argument_bytes)); | ||
| 494 | std::memcpy(env.arguments_map, args, sizeof args); | ||
| 495 | std::memset(marks_map, 0, size_t(kMostGroups + 1) * 4); | ||
| 496 | { | ||
| 497 | auto batch = clamp.batch(); | ||
| 498 | leonida::ClampedIndirect job{}; | ||
| 499 | CHECK(batch->prepare(env.arguments, 0, VK_NULL_HANDLE, 0, leonida::indirect_clamp_dispatch, 12, 1, | ||
| 500 | job)); | ||
| 501 | const MarkerPush push{device.device_address(marks), groups, 0}; | ||
| 502 | CHECK(device.run([&](VkCommandBuffer cb) { | ||
| 503 | clamp.emit(cb, job); // its last barrier orders the records before the indirect read | ||
| 504 | reinterpret_cast<PFN_vkCmdBindPipeline>(vkfn("vkCmdBindPipeline"))( | ||
| 505 | cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); | ||
| 506 | reinterpret_cast<PFN_vkCmdPushConstants>(vkfn("vkCmdPushConstants"))( | ||
| 507 | cb, layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof push, &push); | ||
| 508 | reinterpret_cast<PFN_vkCmdDispatchIndirect>(vkfn("vkCmdDispatchIndirect"))(cb, job.buffer, | ||
| 509 | job.offset); | ||
| 510 | VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 511 | host.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; | ||
| 512 | host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; | ||
| 513 | device.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")( | ||
| 514 | cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, | ||
| 515 | 0, nullptr); | ||
| 516 | return true; | ||
| 517 | })); | ||
| 518 | } | ||
| 519 | clamp.retire(VK_NULL_HANDLE, 0); | ||
| 520 | clamp.collect(); | ||
| 521 | const auto* m = static_cast<const std::uint32_t*>(marks_map); | ||
| 522 | std::uint32_t once = 0, never = 0, twice = 0; | ||
| 523 | for (std::uint32_t g = 0; g < groups; ++g) { | ||
| 524 | if (m[g] == 1) ++once; | ||
| 525 | else if (m[g] == 0) ++never; | ||
| 526 | else ++twice; | ||
| 527 | } | ||
| 528 | if (once != groups || m[groups] != 0) | ||
| 529 | std::fprintf(stderr, "indirect_clamp_test: %u x %u x %u: %u group(s) ran once, %u never, %u more than " | ||
| 530 | "once, %u past the end\n", c.x, c.y, c.z, once, never, twice, m[groups]); | ||
| 531 | CHECK(once == groups && never == 0 && twice == 0 && m[groups] == 0); | ||
| 532 | } | ||
| 533 | reinterpret_cast<PFN_vkDestroyPipeline>(vkfn("vkDestroyPipeline"))(device.device, pipeline, nullptr); | ||
| 534 | reinterpret_cast<PFN_vkDestroyPipelineLayout>(vkfn("vkDestroyPipelineLayout"))(device.device, layout, nullptr); | ||
| 535 | reinterpret_cast<PFN_vkDestroyShaderModule>(vkfn("vkDestroyShaderModule"))(device.device, module, nullptr); | ||
| 536 | } | ||
| 537 | |||
| 371 | // Every case above ran under validation when LEONIDA_VK_VALIDATION=1. | 538 | // Every case above ran under validation when LEONIDA_VK_VALIDATION=1. |
| 372 | CHECK(device.validation_errors() == device.known_validation_errors()); | 539 | CHECK(device.validation_errors() == device.known_validation_errors()); |
| 373 | 540 | ||
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 | |||
| 18 | namespace { | ||
| 19 | |||
| 20 | constexpr 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 | |||
| 38 | int 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/memory_breakdown_test.cpp b/runtime/test/memory_breakdown_test.cpp new file mode 100644 index 000000000..d27a1166d --- /dev/null +++ b/runtime/test/memory_breakdown_test.cpp | |||
| @@ -0,0 +1,118 @@ | |||
| 1 | // leonida::memory_breakdown (src/memory_breakdown.h): the mem probe's breakdown line. The tally of synthetic | ||
| 2 | // allocations by consumer adds up to the allocated total, an Owner scope names the allocations made under it and | ||
| 3 | // nests, an image's usage picks its kind, and the text names every part. No GPU, no device. | ||
| 4 | #include "../src/memory_breakdown.h" | ||
| 5 | |||
| 6 | #include <cstdint> | ||
| 7 | #include <cstdio> | ||
| 8 | #include <string> | ||
| 9 | #include <thread> | ||
| 10 | |||
| 11 | #define EXPECT(condition) do { \ | ||
| 12 | if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ | ||
| 13 | } while (0) | ||
| 14 | |||
| 15 | namespace { | ||
| 16 | |||
| 17 | namespace mb = leonida::memory_breakdown; | ||
| 18 | constexpr std::uint64_t kMiB = 1 << 20; | ||
| 19 | |||
| 20 | bool contains(const std::string& text, const char* part) { return text.find(part) != std::string::npos; } | ||
| 21 | |||
| 22 | // The parts add up to the total, imported memory stays out of it, and an unknown consumer counts as other. | ||
| 23 | int tally() { | ||
| 24 | mb::Tally t; | ||
| 25 | t.add(mb::Consumer::arena, 4095 * kMiB, false); | ||
| 26 | t.add(mb::Consumer::geometry, 4 * kMiB, false); | ||
| 27 | t.add(mb::Consumer::geometry, 4 * kMiB, false); | ||
| 28 | t.add(mb::Consumer::sampled, 3 * kMiB, false); | ||
| 29 | t.add(mb::Consumer::render_target, 8 * kMiB, false); | ||
| 30 | t.add(mb::Consumer::other, 1 * kMiB, false); | ||
| 31 | t.add(mb::Consumer::count, 2 * kMiB, false); // out of range: other | ||
| 32 | t.add(mb::Consumer::windows, 6 * kMiB, true); // imported: not allocated by us | ||
| 33 | EXPECT(t.total() == (4095 + 8 + 3 + 8 + 1 + 2) * kMiB); | ||
| 34 | EXPECT(t.bytes[std::size_t(mb::Consumer::geometry)] == 8 * kMiB); | ||
| 35 | EXPECT(t.count[std::size_t(mb::Consumer::geometry)] == 2); | ||
| 36 | EXPECT(t.bytes[std::size_t(mb::Consumer::other)] == 3 * kMiB); | ||
| 37 | EXPECT(t.count[std::size_t(mb::Consumer::other)] == 2); | ||
| 38 | EXPECT(t.bytes[std::size_t(mb::Consumer::windows)] == 0); | ||
| 39 | EXPECT(t.imported_bytes == 6 * kMiB && t.imported_count == 1); | ||
| 40 | std::uint64_t sum = 0; | ||
| 41 | for (std::size_t i = 0; i < mb::kConsumers; ++i) sum += t.bytes[i]; | ||
| 42 | EXPECT(sum == t.total()); | ||
| 43 | return 0; | ||
| 44 | } | ||
| 45 | |||
| 46 | // An Owner scope names this thread's allocations, nests, restores the outer name, and does not leak to other threads. | ||
| 47 | int owner_scopes() { | ||
| 48 | EXPECT(mb::current_owner() == mb::Consumer::other); | ||
| 49 | { | ||
| 50 | mb::Owner outer(mb::Consumer::geometry); | ||
| 51 | EXPECT(mb::current_owner() == mb::Consumer::geometry); | ||
| 52 | { | ||
| 53 | mb::Owner inner(mb::Consumer::staging); | ||
| 54 | EXPECT(mb::current_owner() == mb::Consumer::staging); | ||
| 55 | mb::Consumer seen = mb::Consumer::count; | ||
| 56 | std::thread([&] { seen = mb::current_owner(); }).join(); | ||
| 57 | EXPECT(seen == mb::Consumer::other); | ||
| 58 | } | ||
| 59 | EXPECT(mb::current_owner() == mb::Consumer::geometry); | ||
| 60 | } | ||
| 61 | EXPECT(mb::current_owner() == mb::Consumer::other); | ||
| 62 | return 0; | ||
| 63 | } | ||
| 64 | |||
| 65 | // Colour and depth/stencil attachments are render targets; anything else bound alone is a sampled texture. | ||
| 66 | int image_kinds() { | ||
| 67 | const std::uint32_t sampled = 0x4, transfer_dst = 0x2, storage = 0x8; | ||
| 68 | EXPECT(mb::image_consumer(sampled | transfer_dst) == mb::Consumer::sampled); | ||
| 69 | EXPECT(mb::image_consumer(storage) == mb::Consumer::sampled); | ||
| 70 | EXPECT(mb::image_consumer(sampled | mb::kColorAttachment) == mb::Consumer::render_target); | ||
| 71 | EXPECT(mb::image_consumer(mb::kDepthStencilAttachment) == mb::Consumer::render_target); | ||
| 72 | return 0; | ||
| 73 | } | ||
| 74 | |||
| 75 | // The text: the total first, every consumer with its MiB and count, the arena's reserved/bound/in-use bytes, other | ||
| 76 | // last, and what lies outside the total. | ||
| 77 | int text() { | ||
| 78 | mb::Tally t; | ||
| 79 | t.add(mb::Consumer::arena, 4095 * kMiB, false); | ||
| 80 | t.add(mb::Consumer::geometry, 3867 * kMiB, false); | ||
| 81 | t.add(mb::Consumer::render_target, 1180 * kMiB, false); | ||
| 82 | t.add(mb::Consumer::other, 819 * kMiB, false); | ||
| 83 | t.add(mb::Consumer::other, 206 * kMiB, true); | ||
| 84 | mb::DeviceShare share; | ||
| 85 | share.arena = true; | ||
| 86 | share.arena_reserved = share.arena_bound = 4095 * kMiB; | ||
| 87 | share.arena_in_use = 757 * kMiB; | ||
| 88 | share.arena_use = {500 * kMiB, 171 * kMiB, 80 * kMiB, 6 * kMiB}; | ||
| 89 | share.bindless_table_bytes = 2 * kMiB; | ||
| 90 | const std::string line = mb::format(t, share, 12 * kMiB); | ||
| 91 | std::fprintf(stderr, "%s\n", line.c_str()); | ||
| 92 | EXPECT(line.rfind("allocated 9961 MiB = arena 4095 (1) [reserved 4095, bound 4095, in use 757: buffers 500, " | ||
| 93 | "descriptor heaps 171, shader code 80, heaps 6]", | ||
| 94 | 0) == 0); | ||
| 95 | EXPECT(contains(line, " + geometry copies 3867 (1)")); | ||
| 96 | EXPECT(contains(line, " + title windows and shadows 0 (0)")); | ||
| 97 | EXPECT(contains(line, " + upload heaps 0 (0) + staging 0 (0) + texture blocks 0 (0) + sampled textures 0 (0)")); | ||
| 98 | EXPECT(contains(line, " + render targets and depth 1180 (1) + other 819 (1);")); | ||
| 99 | EXPECT(contains(line, "imported 206 MiB (1)")); | ||
| 100 | EXPECT(contains(line, "bindless tables 2 MiB")); | ||
| 101 | EXPECT(contains(line, "shader modules 12 MiB SPIR-V")); | ||
| 102 | // Without an arena the bracket is left out. | ||
| 103 | const std::string bare = mb::format(t, mb::DeviceShare{}, 0); | ||
| 104 | EXPECT(!contains(bare, "reserved")); | ||
| 105 | EXPECT(contains(bare, "arena 4095 (1) + geometry copies")); | ||
| 106 | return 0; | ||
| 107 | } | ||
| 108 | |||
| 109 | } // namespace | ||
| 110 | |||
| 111 | int main() { | ||
| 112 | if (int r = tally()) return r; | ||
| 113 | if (int r = owner_scopes()) return r; | ||
| 114 | if (int r = image_kinds()) return r; | ||
| 115 | if (int r = text()) return r; | ||
| 116 | std::fprintf(stderr, "memory_breakdown: ok\n"); | ||
| 117 | return 0; | ||
| 118 | } | ||
diff --git a/runtime/test/pipeline_cache_store_test.cpp b/runtime/test/pipeline_cache_store_test.cpp index dbf174768..7af94bca6 100644 --- a/runtime/test/pipeline_cache_store_test.cpp +++ b/runtime/test/pipeline_cache_store_test.cpp | |||
| @@ -40,6 +40,14 @@ static int test_limit() { | |||
| 40 | CHECK(!limit.valid); | 40 | CHECK(!limit.valid); |
| 41 | CHECK(limit.bytes == default_save_limit); | 41 | CHECK(limit.bytes == default_save_limit); |
| 42 | } | 42 | } |
| 43 | // The limit counts what a session adds to an offline seed, not the seed the driver hands back with it. | ||
| 44 | constexpr std::size_t gib = std::size_t{1} << 30; | ||
| 45 | CHECK(!store::over_save_limit(3 * gib, 0, 4 * gib)); | ||
| 46 | CHECK(store::over_save_limit(5 * gib, 0, 4 * gib)); | ||
| 47 | CHECK(!store::over_save_limit(10 * gib, 9 * gib, 4 * gib)); // a 9 GB seed plus 1 GB of new builds is saved | ||
| 48 | CHECK(store::over_save_limit(14 * gib, 9 * gib, 4 * gib)); // 5 GB added is over 4 | ||
| 49 | CHECK(!store::over_save_limit(4 * gib, 9 * gib, 1)); // smaller than the seed: nothing added | ||
| 50 | CHECK(!store::over_save_limit(4 * gib + 1, 1, 4 * gib)); // exactly at the limit once the seed is taken off | ||
| 43 | return 0; | 51 | return 0; |
| 44 | } | 52 | } |
| 45 | 53 | ||
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 39a3179a4..987a4eb53 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py | |||
| @@ -128,7 +128,9 @@ CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), | |||
| 128 | ("cs_dpp_bank", [0xffffffff, 0xfffffffe, 0xfffffffd, 0xfffffffc, 7, 7, 7, 7]), | 128 | ("cs_dpp_bank", [0xffffffff, 0xfffffffe, 0xfffffffd, 0xfffffffc, 7, 7, 7, 7]), |
| 129 | ("cs_dpp_fi", [1, 2, 3, 0x7777, 5, 6, 7, 0x7777]), | 129 | ("cs_dpp_fi", [1, 2, 3, 0x7777, 5, 6, 7, 0x7777]), |
| 130 | # a VOPC compare with a DPP src0: 1 for the pair compare, 2 for the dpp8 one (cs_dpp_cmp.asm header) | 130 | # a VOPC compare with a DPP src0: 1 for the pair compare, 2 for the dpp8 one (cs_dpp_cmp.asm header) |
| 131 | ("cs_dpp_cmp", [3, 2, 3, 2, 1, 0, 1, 0])] | 131 | ("cs_dpp_cmp", [3, 2, 3, 2, 1, 0, 1, 0]), |
| 132 | # v_cmpx with a DPP src0: 1 where the plain compare keeps the lane, 2 for the negated one (cs_dpp_cmpx.asm) | ||
| 133 | ("cs_dpp_cmpx", [1, 1, 0, 0, 3, 3, 2, 2])] | ||
| 132 | WAVE32_DUMPS += tuple(n for n, _ in CS_DPP) | 134 | WAVE32_DUMPS += tuple(n for n, _ in CS_DPP) |
| 133 | WAVE32_LANE_DUMPS += tuple(n for n, _ in CS_DPP) | 135 | WAVE32_LANE_DUMPS += tuple(n for n, _ in CS_DPP) |
| 134 | CS_DUMPS = [*CS_DPP, ("cs_smem_vcc_base", CS_SMEM_VCC), ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), | 136 | CS_DUMPS = [*CS_DPP, ("cs_smem_vcc_base", CS_SMEM_VCC), ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), |
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 | ||
| 24 | v_mov_b32_e32 v0, 0x90000 | ||
| 25 | v_mov_b32_e32 v1, 0 | ||
| 26 | global_load_dword v2, v[0:1], off | ||
| 27 | v_mov_b32_e32 v0, 0xa0000 | ||
| 28 | global_load_dword v3, v[0:1], off | ||
| 29 | v_mov_b32_e32 v4, 0x5707 | ||
| 30 | global_store_dword v[0:1], v4, off offset:4 | ||
| 31 | v_mov_b32_e32 v5, 1 | ||
| 32 | global_atomic_add v5, v[0:1], v5, off offset:8 glc | ||
| 33 | v_mov_b32_e32 v0, 0x90ffc | ||
| 34 | global_load_dwordx2 v[6:7], v[0:1], off | ||
| 35 | s_mov_b32 s4, 0xa0000 | ||
| 36 | s_mov_b32 s5, 0 | ||
| 37 | s_mov_b32 s6, 0x100 | ||
| 38 | s_mov_b32 s7, 0x31016fac | ||
| 39 | v_mov_b32_e32 v8, 0 | ||
| 40 | buffer_load_dword v8, v8, s[4:7], 0 offen | ||
| 41 | s_mov_b32 s8, 0x90000 | ||
| 42 | s_mov_b32 s9, 0 | ||
| 43 | s_load_dword s10, s[8:9], 0x4 | ||
| 44 | s_load_dword s11, s[4:5], 0x0 | ||
| 45 | s_waitcnt vmcnt(0) lgkmcnt(0) | ||
| 46 | v_mov_b32_e32 v9, 0 | ||
| 47 | buffer_store_dword v2, v9, s[0:3], 0 offen | ||
| 48 | buffer_store_dword v3, v9, s[0:3], 0 offen offset:4 | ||
| 49 | buffer_store_dword v5, v9, s[0:3], 0 offen offset:8 | ||
| 50 | buffer_store_dword v6, v9, s[0:3], 0 offen offset:12 | ||
| 51 | buffer_store_dword v7, v9, s[0:3], 0 offen offset:16 | ||
| 52 | buffer_store_dword v8, v9, s[0:3], 0 offen offset:20 | ||
| 53 | v_mov_b32_e32 v10, s10 | ||
| 54 | buffer_store_dword v10, v9, s[0:3], 0 offen offset:24 | ||
| 55 | v_mov_b32_e32 v11, s11 | ||
| 56 | buffer_store_dword v11, v9, s[0:3], 0 offen offset:28 | ||
| 57 | s_endpgm | ||
diff --git a/runtime/test/shaders/cs_dpp_cmpx.asm b/runtime/test/shaders/cs_dpp_cmpx.asm new file mode 100644 index 000000000..85f18c93f --- /dev/null +++ b/runtime/test/shaders/cs_dpp_cmpx.asm | |||
| @@ -0,0 +1,24 @@ | |||
| 1 | ; v_cmpx in DPP form (SHADER-VOPCX-DPP): src0 is read from the permuted lane, src1 from the lane itself, and the result | ||
| 2 | ; goes to EXEC. v1 = float(lane - 4). Both compares take src0 from the other half of each quad (quad_perm [2,3,0,1], | ||
| 3 | ; with bound_ctrl:1 and fi:1, the form the game's pixel shaders use). The first keeps a lane where | ||
| 4 | ; "neighbour > self": lanes 0, 1, 4, 5 of each 8. The second negates src1 ("neighbour > -self"): lanes 4-7 of the first | ||
| 5 | ; 8 and every lane after. out = (first keeps the lane ? 1 : 0) + (second keeps it ? 2 : 0), EXEC restored in between. | ||
| 6 | ; Run: vk_compute_test cs_dpp_cmpx.spv 1 dump -> out[0..7] = 1 1 0 0 3 3 2 2 | ||
| 7 | ; llvm-mc assembles neither compare for gfx1013 ("dpp variant of this instruction is not supported"), so the GPU | ||
| 8 | ; test takes this file's text as its listing; tools/shader_disasm.py prints the same lines for the encoded words. | ||
| 9 | ; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here | ||
| 10 | ; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm | ||
| 11 | v_mbcnt_lo_u32_b32 v0, -1, 0 | ||
| 12 | v_add_nc_u32 v7, -4, v0 | ||
| 13 | v_cvt_f32_i32 v1, v7 | ||
| 14 | v_mov_b32 v6, 0 | ||
| 15 | s_mov_b32 s10, exec_lo | ||
| 16 | v_cmpx_gt_f32_dpp v1, v1 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1 fi:1 | ||
| 17 | v_mov_b32 v6, 1 | ||
| 18 | s_mov_b32 exec_lo, s10 | ||
| 19 | v_cmpx_gt_f32_dpp v1, -v1 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1 fi:1 | ||
| 20 | v_add_nc_u32 v6, 2, v6 | ||
| 21 | s_mov_b32 exec_lo, s10 | ||
| 22 | v_lshlrev_b32 v2, 2, v0 | ||
| 23 | buffer_store_dword v6, v2, s[0:3], 0 offen | ||
| 24 | s_endpgm | ||
diff --git a/runtime/test/shadow_keep_test.cpp b/runtime/test/shadow_keep_test.cpp new file mode 100644 index 000000000..87960c0a2 --- /dev/null +++ b/runtime/test/shadow_keep_test.cpp | |||
| @@ -0,0 +1,141 @@ | |||
| 1 | // src/shadow_keep.h: a shadow copy keeps a GPU write until the title's bytes under it change. No Windows headers, no | ||
| 2 | // GPU, no game data: the "title" and its "copy" are arrays here, and the values are made up. | ||
| 3 | #include "../src/shadow_keep.h" | ||
| 4 | |||
| 5 | #include <cstdint> | ||
| 6 | #include <cstdio> | ||
| 7 | #include <cstring> | ||
| 8 | #include <utility> | ||
| 9 | #include <vector> | ||
| 10 | |||
| 11 | namespace { | ||
| 12 | |||
| 13 | int failures = 0; | ||
| 14 | #define EXPECT(condition) \ | ||
| 15 | do { \ | ||
| 16 | if (!(condition)) { \ | ||
| 17 | std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ | ||
| 18 | ++failures; \ | ||
| 19 | } \ | ||
| 20 | } while (0) | ||
| 21 | |||
| 22 | using leonida::shadow_keep::kPiece; | ||
| 23 | |||
| 24 | // A title range and its copy, as ShadowPages has them: the copy of the title byte at address a is copy[a - base]. | ||
| 25 | struct Pages { | ||
| 26 | static constexpr std::uintptr_t base = 0x10000; // kPiece-aligned, like a tracker's first page | ||
| 27 | std::vector<std::uint8_t> title, copy; | ||
| 28 | std::vector<std::uint64_t> sums; | ||
| 29 | std::vector<std::pair<std::uintptr_t, std::uintptr_t>> copied; // the ranges the last refresh copied | ||
| 30 | |||
| 31 | explicit Pages(std::size_t bytes) : title(bytes), copy(bytes), sums(bytes / kPiece) { | ||
| 32 | for (std::size_t i = 0; i < bytes; ++i) title[i] = std::uint8_t(i * 7 + 3); | ||
| 33 | } | ||
| 34 | // A refresh of [va, va + n): what ShadowPages::copy_changed does for one page. | ||
| 35 | std::size_t refresh(std::uintptr_t va, std::size_t n) { | ||
| 36 | copied.clear(); | ||
| 37 | std::size_t bytes = 0; | ||
| 38 | leonida::shadow_keep::copy_changed( | ||
| 39 | title.data() + (va - base), va, n, sums.data(), base, | ||
| 40 | [&](std::uintptr_t from, std::uintptr_t to, const std::uint8_t* source) { | ||
| 41 | std::memcpy(copy.data() + (from - base), source, to - from); | ||
| 42 | copied.emplace_back(from, to); | ||
| 43 | bytes += to - from; | ||
| 44 | }); | ||
| 45 | return bytes; | ||
| 46 | } | ||
| 47 | std::size_t refresh() { return refresh(base, title.size()); } | ||
| 48 | bool same(std::size_t from, std::size_t to) const { | ||
| 49 | return !std::memcmp(title.data() + from, copy.data() + from, to - from); | ||
| 50 | } | ||
| 51 | }; | ||
| 52 | |||
| 53 | void unchanged_title_keeps_gpu_write() { | ||
| 54 | Pages p(4096); | ||
| 55 | EXPECT(p.refresh() == 4096); // nothing known yet: all of it | ||
| 56 | EXPECT(p.same(0, 4096)); | ||
| 57 | EXPECT(p.refresh() == 0); // nothing changed | ||
| 58 | // A shader stores 16 bytes in the copy; the title's bytes there stay as they were. | ||
| 59 | const std::uint8_t gpu[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; | ||
| 60 | std::memcpy(p.copy.data() + 0x340, gpu, sizeof(gpu)); | ||
| 61 | EXPECT(p.refresh() == 0); | ||
| 62 | EXPECT(!std::memcmp(p.copy.data() + 0x340, gpu, sizeof(gpu))); // kept: the old code overwrote it here | ||
| 63 | EXPECT(p.same(0, 0x340) && p.same(0x350, 4096)); | ||
| 64 | } | ||
| 65 | |||
| 66 | void changed_title_piece_is_copied() { | ||
| 67 | Pages p(4096); | ||
| 68 | p.refresh(); | ||
| 69 | const std::uint8_t gpu[16] = {0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, | ||
| 70 | 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}; | ||
| 71 | std::memcpy(p.copy.data() + 0x340, gpu, sizeof(gpu)); // GPU write in piece 3 | ||
| 72 | std::memcpy(p.copy.data() + 0x800, gpu, sizeof(gpu)); // and in piece 8 | ||
| 73 | p.title[0x810] ^= 0x5A; // the title writes piece 8 | ||
| 74 | EXPECT(p.refresh() == kPiece); | ||
| 75 | EXPECT(p.copied.size() == 1 && p.copied[0].first == Pages::base + 0x800 && | ||
| 76 | p.copied[0].second == Pages::base + 0x900); | ||
| 77 | EXPECT(p.same(0x800, 0x900)); // the title's new bytes win there | ||
| 78 | EXPECT(!std::memcmp(p.copy.data() + 0x340, gpu, sizeof(gpu))); // the other GPU write stays | ||
| 79 | EXPECT(p.refresh() == 0); | ||
| 80 | } | ||
| 81 | |||
| 82 | void partial_first_and_last_pieces() { | ||
| 83 | Pages p(4096); | ||
| 84 | // A target that starts and ends inside pieces: [base + 100, base + 1000). | ||
| 85 | const std::uintptr_t va = Pages::base + 100; | ||
| 86 | const std::size_t n = 900; | ||
| 87 | EXPECT(p.refresh(va, n) == n); | ||
| 88 | EXPECT(p.copied.size() == 4); | ||
| 89 | EXPECT(p.copied.front().first == va && p.copied.front().second == Pages::base + kPiece); | ||
| 90 | EXPECT(p.copied.back().first == Pages::base + 3 * kPiece && p.copied.back().second == va + n); | ||
| 91 | EXPECT(p.same(100, 1000)); | ||
| 92 | EXPECT(p.copy[99] == 0 && p.copy[1000] == 0); // nothing outside the range | ||
| 93 | EXPECT(p.refresh(va, n) == 0); | ||
| 94 | p.title[999] ^= 1; // last byte of the last, partial piece | ||
| 95 | EXPECT(p.refresh(va, n) == 1000 - 3 * kPiece); | ||
| 96 | p.title[100] ^= 1; // first byte of the first, partial piece | ||
| 97 | EXPECT(p.refresh(va, n) == kPiece - 100); | ||
| 98 | EXPECT(p.same(100, 1000)); | ||
| 99 | } | ||
| 100 | |||
| 101 | void forgotten_sums_copy_once() { | ||
| 102 | Pages p(4096); | ||
| 103 | p.refresh(); | ||
| 104 | // The pages were not committed for a refresh: the copies were zeroed and their sums forgotten. | ||
| 105 | std::memset(p.copy.data() + 0x400, 0, 0x200); | ||
| 106 | leonida::shadow_keep::forget(p.sums.data(), Pages::base, Pages::base + 0x400, Pages::base + 0x600); | ||
| 107 | EXPECT(p.refresh() == 0x200); // the same title bytes back: copied once all the same | ||
| 108 | EXPECT(p.same(0, 4096)); | ||
| 109 | EXPECT(p.refresh() == 0); | ||
| 110 | // A partial range forgets every piece it touches. | ||
| 111 | leonida::shadow_keep::forget(p.sums.data(), Pages::base, Pages::base + 0x410, Pages::base + 0x501); | ||
| 112 | EXPECT(p.refresh() == 0x200); | ||
| 113 | } | ||
| 114 | |||
| 115 | void sums_tell_bytes_apart() { | ||
| 116 | std::uint8_t a[kPiece] = {}, b[kPiece] = {}; | ||
| 117 | EXPECT(leonida::shadow_keep::sum_of(a, kPiece) != 0); | ||
| 118 | EXPECT(leonida::shadow_keep::sum_of(a, kPiece) == leonida::shadow_keep::sum_of(b, kPiece)); | ||
| 119 | for (std::size_t i = 0; i < kPiece; ++i) { | ||
| 120 | b[i] = 1; | ||
| 121 | EXPECT(leonida::shadow_keep::sum_of(a, kPiece) != leonida::shadow_keep::sum_of(b, kPiece)); | ||
| 122 | b[i] = 0; | ||
| 123 | } | ||
| 124 | EXPECT(leonida::shadow_keep::sum_of(a, 16) != leonida::shadow_keep::sum_of(a, 17)); // the length counts | ||
| 125 | } | ||
| 126 | |||
| 127 | } // namespace | ||
| 128 | |||
| 129 | int main() { | ||
| 130 | unchanged_title_keeps_gpu_write(); | ||
| 131 | changed_title_piece_is_copied(); | ||
| 132 | partial_first_and_last_pieces(); | ||
| 133 | forgotten_sums_copy_once(); | ||
| 134 | sums_tell_bytes_apart(); | ||
| 135 | if (failures) { | ||
| 136 | std::fprintf(stderr, "shadow_keep: %d check(s) failed\n", failures); | ||
| 137 | return 1; | ||
| 138 | } | ||
| 139 | std::puts("shadow_keep: OK"); | ||
| 140 | return 0; | ||
| 141 | } | ||
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/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index f2f869391..6eadb4bea 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp | |||
| @@ -85,29 +85,44 @@ int main() { | |||
| 85 | a.remove(title, arena); | 85 | a.remove(title, arena); |
| 86 | a.remove(title + 0x40000, 0x7000000); | 86 | a.remove(title + 0x40000, 0x7000000); |
| 87 | EXPECT(a.size() == 0); | 87 | EXPECT(a.size() == 0); |
| 88 | // Replacing part of an alias removes the entire old interval. Other heaps read independently. | 88 | // Every listener is told each change as it happens (the console heaps' slot records): an add, the whole old |
| 89 | std::uint64_t cursor = 0; | 89 | // interval when part of it is replaced, a removal, a copy forgotten and title memory added. None is dropped, however |
| 90 | leonida::DescriptorRanges past; | 90 | // many come (the 4,096-entry ring this replaced fell back to a full sweep), and a removed listener hears nothing. |
| 91 | EXPECT(a.changed_ranges(cursor, past)); | 91 | struct Heard { |
| 92 | auto second = cursor; | 92 | leonida::TitleVaAliases::Change change; |
| 93 | std::uint64_t title_va, bytes, shader_va; | ||
| 94 | }; | ||
| 95 | std::vector<Heard> first, second; | ||
| 96 | const auto hear = [](void* to, leonida::TitleVaAliases::Change change, std::uint64_t va, std::uint64_t bytes, | ||
| 97 | std::uint64_t shader_va) { | ||
| 98 | static_cast<std::vector<Heard>*>(to)->push_back({change, va, bytes, shader_va}); | ||
| 99 | }; | ||
| 100 | using Change = leonida::TitleVaAliases::Change; | ||
| 101 | a.add_listener(&first, hear); | ||
| 102 | a.add_listener(&second, hear); | ||
| 93 | EXPECT(a.add(title, size, arena)); | 103 | EXPECT(a.add(title, size, arena)); |
| 94 | EXPECT(a.add(title+16, 32, arena+4096)); | 104 | EXPECT(a.add(title + 16, 32, arena + 4096)); |
| 95 | for (auto* reader : {&cursor, &second}) { | 105 | for (const auto* heard : {&first, &second}) { |
| 96 | leonida::DescriptorRanges delta; | 106 | EXPECT(heard->size() == 3); |
| 97 | EXPECT(a.changed_ranges(*reader, delta)); | 107 | EXPECT((*heard)[0].change == Change::added && (*heard)[0].title_va == title && (*heard)[0].bytes == size); |
| 98 | delta.merge(); | 108 | EXPECT((*heard)[1].change == Change::removed && (*heard)[1].title_va == title && (*heard)[1].bytes == size && |
| 99 | EXPECT(delta.overlaps(title+size-1, 1) && delta.overlaps(title-16, 17)); | 109 | (*heard)[1].shader_va == arena); |
| 100 | EXPECT(!delta.overlaps(title+size, 1) && !delta.overlaps(title-16, 16)); | 110 | EXPECT((*heard)[2].change == Change::added && (*heard)[2].title_va == title + 16 && |
| 111 | (*heard)[2].bytes == 32 && (*heard)[2].shader_va == arena + 4096); | ||
| 101 | } | 112 | } |
| 102 | leonida::DescriptorRangeChanges backing; | 113 | a.remove_listener(&second); |
| 103 | for (unsigned i = 0; i < 4097; ++i) backing.record(UINT64_MAX-3, 4); | 114 | a.remove(title + 16, arena + 4096); |
| 104 | cursor = 0; | 115 | a.forget_copy(title + 0x1000, 0x100, 0x5000000); |
| 105 | EXPECT(!backing.read(cursor, past)); | 116 | a.add_title_memory(0x30000000000ull, 0x2000); |
| 106 | backing.record(UINT64_MAX-3, 4); | 117 | EXPECT(second.size() == 3 && first.size() == 6); |
| 107 | leonida::DescriptorRanges last; | 118 | EXPECT(first[3].change == Change::removed && first[3].title_va == title + 16 && first[3].shader_va == arena + 4096); |
| 108 | EXPECT(backing.read(cursor,last)); | 119 | EXPECT(first[4].change == Change::removed && first[4].title_va == title + 0x1000 && first[4].bytes == 0x100 && |
| 109 | last.merge(); | 120 | first[4].shader_va == 0x5000000); |
| 110 | EXPECT(last.overlaps(UINT64_MAX,1) && !last.overlaps(0,1)); | 121 | EXPECT(first[5].change == Change::memory_added && first[5].title_va == 0x30000000000ull && first[5].bytes == 0x2000); |
| 122 | a.remove_title_memory(0x30000000000ull); | ||
| 123 | for (unsigned i = 0; i < 5000; ++i) a.forget_copy(title, 4, arena); | ||
| 124 | EXPECT(first.size() == 5006); | ||
| 125 | a.remove_listener(&first); | ||
| 111 | // shader_side: whether an address is one the layer wrote for the title (inside some range's copy), so a scan that | 126 | // shader_side: whether an address is one the layer wrote for the title (inside some range's copy), so a scan that |
| 112 | // sees an already rewritten V# again leaves it alone rather than taking it for an unmapped address. | 127 | // sees an already rewritten V# again leaves it alone rather than taking it for an unmapped address. |
| 113 | EXPECT(!a.shader_side(arena)); | 128 | EXPECT(!a.shader_side(arena)); |
diff --git a/runtime/test/vk_bindless_dimensions_test.cpp b/runtime/test/vk_bindless_dimensions_test.cpp new file mode 100644 index 000000000..3da8370d6 --- /dev/null +++ b/runtime/test/vk_bindless_dimensions_test.cpp | |||
| @@ -0,0 +1,421 @@ | |||
| 1 | // More live images of each sampled dimension than 4096, through the bindless set 0 (src/vulkan_bindless.h), at the | ||
| 2 | // Vulkan level, and the index allocator behind them. | ||
| 3 | // | ||
| 4 | // An image keeps its index in its dimension's array for as long as it lives, so the array of a dimension must hold | ||
| 5 | // every live image of it a title has. A world run kept 4090 live 1D textures and filled the 4096 1D indices the set | ||
| 6 | // once stopped at (bindless::size_bindings capped 1D and 3D at 4096 whatever the device held); every later 1D T# then | ||
| 7 | // read the fallback's zeros. For 1D, 2D-array and 3D images alike this test sizes the set from the device's limits | ||
| 8 | // as the D3D12 device does, gives 5000 distinct images (one texel each, holding its own number) an index each, | ||
| 9 | // and has test/glsl/cs_bindless_dimensions.comp read every one of them through its index: each must read its own | ||
| 10 | // number. Then, on the same set: | ||
| 11 | // - the rest of the array is filled: the index after the last is refused, and image_refusal says the array of | ||
| 12 | // that dimension is full (the D3D12 device's "unbound T#s by reason" line names that reason); | ||
| 13 | // - an image removed while the table has no changes the GPU lacks gives its index back at once, and one removed | ||
| 14 | // while it has (an erased key) gives it back at the next flush, not before. | ||
| 15 | // Exit 77 without a Vulkan device with the bindless features or without the shader (no glslangValidator), and for | ||
| 16 | // a dimension whose device limits hold fewer than 5000 images (the test says so). | ||
| 17 | // LEONIDA_VK_VALIDATION=1 runs under VK_LAYER_KHRONOS_validation; a validation error fails the test. | ||
| 18 | #ifndef VK_NO_PROTOTYPES | ||
| 19 | #define VK_NO_PROTOTYPES | ||
| 20 | #endif | ||
| 21 | #include "vk_test_device.h" | ||
| 22 | #include "shader_fixture_path.h" | ||
| 23 | #include "../src/vulkan_bindless.h" | ||
| 24 | |||
| 25 | #include <algorithm> | ||
| 26 | #include <cstdio> | ||
| 27 | #include <cstring> | ||
| 28 | #include <fstream> | ||
| 29 | #include <iterator> | ||
| 30 | #include <vector> | ||
| 31 | |||
| 32 | #define EXPECT(condition) \ | ||
| 33 | do { \ | ||
| 34 | if (!(condition)) { \ | ||
| 35 | std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ | ||
| 36 | return 1; \ | ||
| 37 | } \ | ||
| 38 | } while (0) | ||
| 39 | |||
| 40 | namespace { | ||
| 41 | |||
| 42 | using namespace leonida; | ||
| 43 | |||
| 44 | constexpr std::uint32_t live_images = 5000; // more than the 4096 1D and 3D indices of the old sizes | ||
| 45 | |||
| 46 | std::vector<std::uint32_t> load_spirv(const char* path) { | ||
| 47 | std::ifstream file(vktest::shader_fixture_path(path), std::ios::binary); | ||
| 48 | const std::vector<char> bytes{std::istreambuf_iterator<char>(file), {}}; | ||
| 49 | std::vector<std::uint32_t> words(bytes.size() / 4); | ||
| 50 | if (!words.empty()) std::memcpy(words.data(), bytes.data(), words.size() * 4); | ||
| 51 | return words; | ||
| 52 | } | ||
| 53 | |||
| 54 | const char* name(ImageDimension dimension) { | ||
| 55 | return dimension == ImageDimension::dim_1d ? "1D" : dimension == ImageDimension::dim_2d_array ? "2D array" : "3D"; | ||
| 56 | } | ||
| 57 | |||
| 58 | // The images of one dimension, `count` texels in all, each in its own image (3D) or array layer (1D, 2D array), and a | ||
| 59 | // view of each: what the test reads through the set. Destroys what it made. | ||
| 60 | struct Images { | ||
| 61 | vktest::Device& d; | ||
| 62 | std::vector<VkImage> images; | ||
| 63 | std::vector<VkDeviceMemory> memory; | ||
| 64 | std::vector<VkImageView> views; | ||
| 65 | struct Texel { | ||
| 66 | VkImage image; | ||
| 67 | std::uint32_t layer; | ||
| 68 | }; | ||
| 69 | std::vector<Texel> texels; | ||
| 70 | |||
| 71 | explicit Images(vktest::Device& device) : d(device) {} | ||
| 72 | Images(const Images&) = delete; | ||
| 73 | Images& operator=(const Images&) = delete; | ||
| 74 | ~Images() { | ||
| 75 | for (const VkImageView view : views) d.fn<PFN_vkDestroyImageView>("vkDestroyImageView")(d.device, view, nullptr); | ||
| 76 | for (const VkImage image : images) d.fn<PFN_vkDestroyImage>("vkDestroyImage")(d.device, image, nullptr); | ||
| 77 | for (const VkDeviceMemory m : memory) d.fn<PFN_vkFreeMemory>("vkFreeMemory")(d.device, m, nullptr); | ||
| 78 | } | ||
| 79 | |||
| 80 | bool make(ImageDimension dimension, std::uint32_t count, std::uint32_t max_layers, | ||
| 81 | const VkPhysicalDeviceMemoryProperties& properties) { | ||
| 82 | const bool volume = dimension == ImageDimension::dim_3d; | ||
| 83 | const std::uint32_t per_image = volume ? 1 : std::min(max_layers, count); | ||
| 84 | // Images in groups that share one allocation (each a few MiB at most). | ||
| 85 | constexpr std::uint32_t group = 512; | ||
| 86 | for (std::uint32_t first = 0; first < count;) { | ||
| 87 | std::vector<VkImage> made; | ||
| 88 | std::uint32_t in_group = 0; | ||
| 89 | for (; in_group < group && first < count; ++in_group) { | ||
| 90 | VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; | ||
| 91 | info.imageType = volume ? VK_IMAGE_TYPE_3D | ||
| 92 | : dimension == ImageDimension::dim_1d ? VK_IMAGE_TYPE_1D : VK_IMAGE_TYPE_2D; | ||
| 93 | info.format = VK_FORMAT_R32_SFLOAT; | ||
| 94 | info.extent = {1, 1, 1}; | ||
| 95 | info.mipLevels = 1; | ||
| 96 | info.arrayLayers = std::min(per_image, count - first); | ||
| 97 | info.samples = VK_SAMPLE_COUNT_1_BIT; | ||
| 98 | info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; | ||
| 99 | VkImage image = VK_NULL_HANDLE; | ||
| 100 | if (d.fn<PFN_vkCreateImage>("vkCreateImage")(d.device, &info, nullptr, &image) != VK_SUCCESS) | ||
| 101 | return false; | ||
| 102 | images.push_back(image); | ||
| 103 | made.push_back(image); | ||
| 104 | for (std::uint32_t layer = 0; layer < info.arrayLayers; ++layer) texels.push_back({image, layer}); | ||
| 105 | first += info.arrayLayers; | ||
| 106 | } | ||
| 107 | VkMemoryRequirements requirements{}; | ||
| 108 | d.fn<PFN_vkGetImageMemoryRequirements>("vkGetImageMemoryRequirements")(d.device, made[0], &requirements); | ||
| 109 | const VkDeviceSize stride = | ||
| 110 | (requirements.size + requirements.alignment - 1) / requirements.alignment * requirements.alignment; | ||
| 111 | VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; | ||
| 112 | allocation.allocationSize = stride * made.size(); | ||
| 113 | allocation.memoryTypeIndex = 0xffffffffu; | ||
| 114 | for (std::uint32_t t = 0; t < properties.memoryTypeCount; ++t) | ||
| 115 | if (requirements.memoryTypeBits & (1u << t)) { | ||
| 116 | allocation.memoryTypeIndex = t; | ||
| 117 | break; | ||
| 118 | } | ||
| 119 | VkDeviceMemory block = VK_NULL_HANDLE; | ||
| 120 | if (allocation.memoryTypeIndex == 0xffffffffu || | ||
| 121 | d.fn<PFN_vkAllocateMemory>("vkAllocateMemory")(d.device, &allocation, nullptr, &block) != VK_SUCCESS) | ||
| 122 | return false; | ||
| 123 | memory.push_back(block); | ||
| 124 | for (std::size_t k = 0; k < made.size(); ++k) { | ||
| 125 | VkMemoryRequirements each{}; | ||
| 126 | d.fn<PFN_vkGetImageMemoryRequirements>("vkGetImageMemoryRequirements")(d.device, made[k], &each); | ||
| 127 | if (each.size > stride || !(each.memoryTypeBits & (1u << allocation.memoryTypeIndex)) || | ||
| 128 | d.fn<PFN_vkBindImageMemory>("vkBindImageMemory")(d.device, made[k], block, stride * k) != | ||
| 129 | VK_SUCCESS) | ||
| 130 | return false; | ||
| 131 | } | ||
| 132 | } | ||
| 133 | for (const Texel& texel : texels) { | ||
| 134 | VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; | ||
| 135 | info.image = texel.image; | ||
| 136 | info.viewType = volume ? VK_IMAGE_VIEW_TYPE_3D | ||
| 137 | : dimension == ImageDimension::dim_1d ? VK_IMAGE_VIEW_TYPE_1D : VK_IMAGE_VIEW_TYPE_2D_ARRAY; | ||
| 138 | info.format = VK_FORMAT_R32_SFLOAT; | ||
| 139 | info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, texel.layer, 1}; | ||
| 140 | VkImageView view = VK_NULL_HANDLE; | ||
| 141 | if (d.fn<PFN_vkCreateImageView>("vkCreateImageView")(d.device, &info, nullptr, &view) != VK_SUCCESS) | ||
| 142 | return false; | ||
| 143 | views.push_back(view); | ||
| 144 | } | ||
| 145 | return true; | ||
| 146 | } | ||
| 147 | |||
| 148 | // Texel i holds i + 1, in GENERAL (the layout the set's descriptors name). | ||
| 149 | void record_fill(VkCommandBuffer cb) const { | ||
| 150 | std::vector<VkImageMemoryBarrier> barriers; | ||
| 151 | for (const VkImage image : images) { | ||
| 152 | VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; | ||
| 153 | barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; | ||
| 154 | barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; | ||
| 155 | barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; | ||
| 156 | barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | ||
| 157 | barrier.image = image; | ||
| 158 | barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, VK_REMAINING_ARRAY_LAYERS}; | ||
| 159 | barriers.push_back(barrier); | ||
| 160 | } | ||
| 161 | d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, | ||
| 162 | VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, | ||
| 163 | nullptr, std::uint32_t(barriers.size()), barriers.data()); | ||
| 164 | for (std::size_t i = 0; i < texels.size(); ++i) { | ||
| 165 | VkClearColorValue value{}; | ||
| 166 | value.float32[0] = float(i + 1); | ||
| 167 | const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, texels[i].layer, 1}; | ||
| 168 | d.fn<PFN_vkCmdClearColorImage>("vkCmdClearColorImage")(cb, texels[i].image, VK_IMAGE_LAYOUT_GENERAL, | ||
| 169 | &value, 1, &range); | ||
| 170 | } | ||
| 171 | VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 172 | filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; | ||
| 173 | filled.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; | ||
| 174 | d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, | ||
| 175 | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &filled, 0, | ||
| 176 | nullptr, 0, nullptr); | ||
| 177 | } | ||
| 178 | }; | ||
| 179 | |||
| 180 | // The compute pipeline over set 0 (the bindless set's layout) and set 1 (result and indices). | ||
| 181 | struct Reader { | ||
| 182 | vktest::Device& d; | ||
| 183 | VkShaderModule module = VK_NULL_HANDLE; | ||
| 184 | VkDescriptorSetLayout set1_layout = VK_NULL_HANDLE; | ||
| 185 | VkDescriptorPool pool = VK_NULL_HANDLE; | ||
| 186 | VkDescriptorSet set1 = VK_NULL_HANDLE; | ||
| 187 | VkPipelineLayout layout = VK_NULL_HANDLE; | ||
| 188 | VkPipeline pipeline = VK_NULL_HANDLE; | ||
| 189 | void* result_map = nullptr; | ||
| 190 | void* index_map = nullptr; | ||
| 191 | |||
| 192 | explicit Reader(vktest::Device& device) : d(device) {} | ||
| 193 | Reader(const Reader&) = delete; | ||
| 194 | Reader& operator=(const Reader&) = delete; | ||
| 195 | ~Reader() { | ||
| 196 | const VkDevice dev = d.device; | ||
| 197 | if (pipeline) d.fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(dev, pipeline, nullptr); | ||
| 198 | if (layout) d.fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(dev, layout, nullptr); | ||
| 199 | if (pool) d.fn<PFN_vkDestroyDescriptorPool>("vkDestroyDescriptorPool")(dev, pool, nullptr); | ||
| 200 | if (set1_layout) d.fn<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(dev, set1_layout, nullptr); | ||
| 201 | if (module) d.fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(dev, module, nullptr); | ||
| 202 | } | ||
| 203 | |||
| 204 | bool make(VkDescriptorSetLayout set0_layout, const std::vector<std::uint32_t>& code) { | ||
| 205 | const VkDevice dev = d.device; | ||
| 206 | VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | ||
| 207 | module_info.codeSize = code.size() * 4; | ||
| 208 | module_info.pCode = code.data(); | ||
| 209 | if (d.fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(dev, &module_info, nullptr, &module) != VK_SUCCESS) | ||
| 210 | return false; | ||
| 211 | const VkBuffer result = d.buffer(live_images * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &result_map); | ||
| 212 | const VkBuffer indices = d.buffer(live_images * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &index_map); | ||
| 213 | if (!result || !indices) return false; | ||
| 214 | const VkDescriptorSetLayoutBinding bindings[2] = { | ||
| 215 | {0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}, | ||
| 216 | {1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}}; | ||
| 217 | VkDescriptorSetLayoutCreateInfo set1_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; | ||
| 218 | set1_info.bindingCount = 2; | ||
| 219 | set1_info.pBindings = bindings; | ||
| 220 | if (d.fn<PFN_vkCreateDescriptorSetLayout>("vkCreateDescriptorSetLayout")(dev, &set1_info, nullptr, | ||
| 221 | &set1_layout) != VK_SUCCESS) | ||
| 222 | return false; | ||
| 223 | const VkDescriptorPoolSize pool_size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2}; | ||
| 224 | VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; | ||
| 225 | pool_info.maxSets = 1; | ||
| 226 | pool_info.poolSizeCount = 1; | ||
| 227 | pool_info.pPoolSizes = &pool_size; | ||
| 228 | if (d.fn<PFN_vkCreateDescriptorPool>("vkCreateDescriptorPool")(dev, &pool_info, nullptr, &pool) != VK_SUCCESS) | ||
| 229 | return false; | ||
| 230 | VkDescriptorSetAllocateInfo allocate{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; | ||
| 231 | allocate.descriptorPool = pool; | ||
| 232 | allocate.descriptorSetCount = 1; | ||
| 233 | allocate.pSetLayouts = &set1_layout; | ||
| 234 | if (d.fn<PFN_vkAllocateDescriptorSets>("vkAllocateDescriptorSets")(dev, &allocate, &set1) != VK_SUCCESS) | ||
| 235 | return false; | ||
| 236 | const VkDescriptorBufferInfo infos[2] = {{result, 0, VK_WHOLE_SIZE}, {indices, 0, VK_WHOLE_SIZE}}; | ||
| 237 | VkWriteDescriptorSet writes[2]{}; | ||
| 238 | for (std::uint32_t b = 0; b < 2; ++b) { | ||
| 239 | writes[b] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; | ||
| 240 | writes[b].dstSet = set1; | ||
| 241 | writes[b].dstBinding = b; | ||
| 242 | writes[b].descriptorCount = 1; | ||
| 243 | writes[b].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; | ||
| 244 | writes[b].pBufferInfo = &infos[b]; | ||
| 245 | } | ||
| 246 | d.fn<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(dev, 2, writes, 0, nullptr); | ||
| 247 | const VkDescriptorSetLayout layouts[2] = {set0_layout, set1_layout}; | ||
| 248 | const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 8}; | ||
| 249 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; | ||
| 250 | layout_info.setLayoutCount = 2; | ||
| 251 | layout_info.pSetLayouts = layouts; | ||
| 252 | layout_info.pushConstantRangeCount = 1; | ||
| 253 | layout_info.pPushConstantRanges = &push; | ||
| 254 | if (d.fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(dev, &layout_info, nullptr, &layout) != | ||
| 255 | VK_SUCCESS) | ||
| 256 | return false; | ||
| 257 | VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | ||
| 258 | pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | ||
| 259 | pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; | ||
| 260 | pipeline_info.stage.module = module; | ||
| 261 | pipeline_info.stage.pName = "main"; | ||
| 262 | pipeline_info.layout = layout; | ||
| 263 | return d.fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(dev, VK_NULL_HANDLE, 1, &pipeline_info, | ||
| 264 | nullptr, &pipeline) == VK_SUCCESS; | ||
| 265 | } | ||
| 266 | |||
| 267 | void record(VkCommandBuffer cb, VkDescriptorSet set0, std::uint32_t dimension, std::uint32_t count) const { | ||
| 268 | d.fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); | ||
| 269 | const VkDescriptorSet sets[2] = {set0, set1}; | ||
| 270 | d.fn<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout, 0, 2, | ||
| 271 | sets, 0, nullptr); | ||
| 272 | const std::uint32_t pass[2] = {dimension, count}; | ||
| 273 | d.fn<PFN_vkCmdPushConstants>("vkCmdPushConstants")(cb, layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, 8, pass); | ||
| 274 | d.fn<PFN_vkCmdDispatch>("vkCmdDispatch")(cb, count, 1, 1); | ||
| 275 | VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 276 | host.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; | ||
| 277 | host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; | ||
| 278 | d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, | ||
| 279 | VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, 0, | ||
| 280 | nullptr); | ||
| 281 | } | ||
| 282 | }; | ||
| 283 | |||
| 284 | int run(vktest::Device& d, const VkPhysicalDeviceMemoryProperties& memory, const BindlessFeatures& features, | ||
| 285 | std::uint32_t max_layers, const std::vector<std::uint32_t>& code, ImageDimension dimension) { | ||
| 286 | BindlessSet set(d.device_proc, d.device, memory, features); | ||
| 287 | EXPECT(set.ok()); | ||
| 288 | const std::uint32_t capacity = set.image_capacity(dimension); | ||
| 289 | std::printf("%s: %u indices in the set\n", name(dimension), capacity); | ||
| 290 | // Every live image needs an index, and index 0 is the fallback. | ||
| 291 | EXPECT(capacity > live_images); | ||
| 292 | |||
| 293 | Images images(d); | ||
| 294 | EXPECT(images.make(dimension, live_images, max_layers, memory)); | ||
| 295 | std::vector<std::uint32_t> indices; | ||
| 296 | for (const VkImageView view : images.views) { | ||
| 297 | const std::uint32_t index = set.add_image(dimension, view, VK_IMAGE_LAYOUT_GENERAL); | ||
| 298 | EXPECT(index != 0); | ||
| 299 | indices.push_back(index); | ||
| 300 | } | ||
| 301 | Reader reader(d); | ||
| 302 | EXPECT(reader.make(set.layout(), code)); | ||
| 303 | std::memcpy(reader.index_map, indices.data(), indices.size() * 4); | ||
| 304 | std::memset(reader.result_map, 0xcd, live_images * 4); | ||
| 305 | const std::uint32_t pass = dimension == ImageDimension::dim_1d ? 0 : dimension == ImageDimension::dim_2d_array ? 1 : 2; | ||
| 306 | bool flushed = false; | ||
| 307 | const bool ran = d.run([&](VkCommandBuffer cb) { | ||
| 308 | set.record_fallback_init(cb); | ||
| 309 | flushed = set.flush(cb, 0, [] { return std::uint64_t(0); }); | ||
| 310 | images.record_fill(cb); | ||
| 311 | reader.record(cb, set.set(), pass, live_images); | ||
| 312 | return true; | ||
| 313 | }); | ||
| 314 | set.table_upload_result(ran); | ||
| 315 | EXPECT(ran && flushed); | ||
| 316 | std::vector<std::uint32_t> result(live_images); | ||
| 317 | std::memcpy(result.data(), reader.result_map, live_images * 4); | ||
| 318 | std::uint32_t wrong = 0; | ||
| 319 | for (std::uint32_t i = 0; i < live_images; ++i) { | ||
| 320 | float red = 0; | ||
| 321 | std::memcpy(&red, &result[i], 4); | ||
| 322 | if (red != float(i + 1) && wrong++ < 4) | ||
| 323 | std::fprintf(stderr, "%s image %u at index %u read %g, expected %u\n", name(dimension), i, indices[i], | ||
| 324 | double(red), i + 1); | ||
| 325 | } | ||
| 326 | EXPECT(wrong == 0); | ||
| 327 | std::printf("%s: %u live images, each read its own texel through its index (the last at %u)\n", name(dimension), | ||
| 328 | live_images, indices.back()); | ||
| 329 | |||
| 330 | // The rest of the array (the same view again: an index each, as distinct T#s of one texture get), then one | ||
| 331 | // more, refused for the reason that the array of its dimension is full. | ||
| 332 | std::uint32_t more = 0; | ||
| 333 | while (set.add_image(dimension, images.views[0], VK_IMAGE_LAYOUT_GENERAL)) ++more; | ||
| 334 | EXPECT(live_images + more == capacity - 1 && set.free_images(dimension) == 0); | ||
| 335 | EXPECT(set.image_refusal(dimension, false) == BindlessSet::ImageRefusal::array_full); | ||
| 336 | // Freed with nothing pending in the table: the index is free again at once. | ||
| 337 | set.remove_image(dimension, indices[7]); | ||
| 338 | EXPECT(set.free_images(dimension) == 1); | ||
| 339 | EXPECT(set.add_image(dimension, images.views[7], VK_IMAGE_LAYOUT_GENERAL) == indices[7]); | ||
| 340 | // Freed after its key is erased (the GPU's table may still name it): held until a flush brings the table up to | ||
| 341 | // date, then free. | ||
| 342 | const DescriptorKey key{0x1234u, 0, 0, 8u << 28, 0, 0, 0, 0}; | ||
| 343 | set.insert_key(key, indices[9], dimension); | ||
| 344 | set.erase_key(key); | ||
| 345 | set.remove_image(dimension, indices[9]); | ||
| 346 | EXPECT(set.free_images(dimension) == 0 && set.add_image(dimension, images.views[9], VK_IMAGE_LAYOUT_GENERAL) == 0); | ||
| 347 | EXPECT(set.image_refusal(dimension, false) == BindlessSet::ImageRefusal::array_full); | ||
| 348 | const bool reflushed = d.run([&](VkCommandBuffer cb) { return set.flush(cb, 1, [] { return std::uint64_t(1); }); }); | ||
| 349 | set.table_upload_result(reflushed); | ||
| 350 | EXPECT(reflushed && set.free_images(dimension) == 1); | ||
| 351 | EXPECT(set.add_image(dimension, images.views[9], VK_IMAGE_LAYOUT_GENERAL) == indices[9]); | ||
| 352 | std::printf("%s: %u more filled the array; the next was refused as full, and removed indices came back\n", | ||
| 353 | name(dimension), more); | ||
| 354 | |||
| 355 | d.fn<PFN_vkDeviceWaitIdle>("vkDeviceWaitIdle")(d.device); | ||
| 356 | set.release_retired(); | ||
| 357 | return 0; | ||
| 358 | } | ||
| 359 | |||
| 360 | } // namespace | ||
| 361 | |||
| 362 | int main() { | ||
| 363 | #ifndef LEONIDA_TEST_BINDLESS_DIMENSIONS_SPV | ||
| 364 | std::printf("unsupported: the test shader was not built (no glslangValidator)\n"); | ||
| 365 | return 77; | ||
| 366 | #else | ||
| 367 | vktest::Device d; | ||
| 368 | if (const auto status = d.initialize(); status != vktest::DeviceStatus::ready) | ||
| 369 | return status == vktest::DeviceStatus::unavailable ? 77 : 1; | ||
| 370 | if (!d.bindless) { | ||
| 371 | std::printf("unsupported: the device lacks the bindless set's descriptor-indexing features\n"); | ||
| 372 | return 77; | ||
| 373 | } | ||
| 374 | VkPhysicalDeviceMemoryProperties memory{}; | ||
| 375 | d.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory); | ||
| 376 | VkPhysicalDeviceVulkan12Properties v12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; | ||
| 377 | VkPhysicalDeviceVulkan11Properties v11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES, &v12}; | ||
| 378 | VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &v11}; | ||
| 379 | d.instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(d.physical, &properties); | ||
| 380 | std::printf("device: %s\n", properties.properties.deviceName); | ||
| 381 | |||
| 382 | // Sized as the D3D12 device sizes it (d3d12_vulkan_device.cpp): from the update-after-bind limits, past | ||
| 383 | // maxPerSetDescriptors where vkGetDescriptorSetLayoutSupport accepts the layout. | ||
| 384 | BindlessFeatures features; | ||
| 385 | features.update_after_bind = true; | ||
| 386 | features.partially_bound = d.partially_bound; | ||
| 387 | const auto layout_support = | ||
| 388 | d.fn<PFN_vkGetDescriptorSetLayoutSupport>("vkGetDescriptorSetLayoutSupport"); | ||
| 389 | const auto layout_supported = [&](const BindlessFeatures& candidate) { | ||
| 390 | if (!layout_support) return false; | ||
| 391 | const bindless::SetLayout layout(candidate); | ||
| 392 | VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}; | ||
| 393 | layout_support(d.device, &layout.info, &support); | ||
| 394 | return support.supported == VK_TRUE; | ||
| 395 | }; | ||
| 396 | bindless::size_bindings(features, properties.properties.limits, v11, v12, layout_supported); | ||
| 397 | const std::uint32_t sampled_limit = std::min(v12.maxPerStageDescriptorUpdateAfterBindSampledImages, | ||
| 398 | v12.maxDescriptorSetUpdateAfterBindSampledImages); | ||
| 399 | // Room for 5000 images in each of the four sampled arrays besides 2D's: below that, the device itself holds | ||
| 400 | // fewer, and the test has nothing to say. | ||
| 401 | if (sampled_limit < bindless::max_images + 3 * (live_images + 1) + 2 * bindless::growth_headroom) { | ||
| 402 | std::printf("unsupported: the device holds %u sampled images in a set, too few for %u of each dimension\n", | ||
| 403 | sampled_limit, live_images); | ||
| 404 | return 77; | ||
| 405 | } | ||
| 406 | |||
| 407 | const std::vector<std::uint32_t> code = load_spirv(LEONIDA_TEST_BINDLESS_DIMENSIONS_SPV); | ||
| 408 | EXPECT(!code.empty()); | ||
| 409 | const std::uint32_t max_layers = properties.properties.limits.maxImageArrayLayers; | ||
| 410 | for (const ImageDimension dimension : | ||
| 411 | {ImageDimension::dim_1d, ImageDimension::dim_2d_array, ImageDimension::dim_3d}) | ||
| 412 | EXPECT(run(d, memory, features, max_layers, code, dimension) == 0); | ||
| 413 | |||
| 414 | if (d.validation_errors()) { | ||
| 415 | std::printf("%u validation errors\n", d.validation_errors()); | ||
| 416 | return 1; | ||
| 417 | } | ||
| 418 | std::printf("vk_bindless_dimensions: ok\n"); | ||
| 419 | return 0; | ||
| 420 | #endif | ||
| 421 | } | ||
diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp index dc33e7d91..e81181849 100644 --- a/runtime/test/vk_bindless_test.cpp +++ b/runtime/test/vk_bindless_test.cpp | |||
| @@ -967,7 +967,14 @@ int main(int argc, char** argv) { | |||
| 967 | std::vector<std::uint32_t> filled; | 967 | std::vector<std::uint32_t> filled; |
| 968 | for (std::uint32_t i = 1; i < set.image_capacity(ImageDimension::dim_1d); ++i) | 968 | for (std::uint32_t i = 1; i < set.image_capacity(ImageDimension::dim_1d); ++i) |
| 969 | filled.push_back(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL)); | 969 | filled.push_back(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL)); |
| 970 | EXPECT(filled.front() == 1 && filled.back() == set.image_capacity(ImageDimension::dim_1d) - 1); | 970 | // Images without storage views take the indices above the storage arrays first, then the ones below: every |
| 971 | // index but the fallback's, once each. | ||
| 972 | std::vector<std::uint32_t> sorted = filled; | ||
| 973 | std::sort(sorted.begin(), sorted.end()); | ||
| 974 | EXPECT(sorted.front() == 1 && sorted.back() == set.image_capacity(ImageDimension::dim_1d) - 1 && | ||
| 975 | std::adjacent_find(sorted.begin(), sorted.end()) == sorted.end()); | ||
| 976 | const std::uint32_t storage_end = set.storage_capacity(ImageDimension::dim_1d); | ||
| 977 | EXPECT(filled.front() == (storage_end < set.image_capacity(ImageDimension::dim_1d) ? storage_end : 1u)); | ||
| 971 | EXPECT(set.free_images(ImageDimension::dim_1d) == 0); | 978 | EXPECT(set.free_images(ImageDimension::dim_1d) == 0); |
| 972 | EXPECT(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) == 0); | 979 | EXPECT(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) == 0); |
| 973 | set.remove_image(ImageDimension::dim_1d, 7); | 980 | set.remove_image(ImageDimension::dim_1d, 7); |
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/vk_xdxr_build_test.cpp b/runtime/test/vk_xdxr_build_test.cpp index a0b3f8b6a..380d4bfad 100644 --- a/runtime/test/vk_xdxr_build_test.cpp +++ b/runtime/test/vk_xdxr_build_test.cpp | |||
| @@ -105,6 +105,7 @@ struct Geometry { | |||
| 105 | bool transform = false; | 105 | bool transform = false; |
| 106 | float m[12] = {}; | 106 | float m[12] = {}; |
| 107 | std::uint32_t triangle_count = 0; | 107 | std::uint32_t triangle_count = 0; |
| 108 | std::uint32_t vertex_count = 0xffffffffu; // XdxrTriangles::vertex_count; the default bounds nothing | ||
| 108 | }; | 109 | }; |
| 109 | 110 | ||
| 110 | // The world-space triangles a geometry describes, as the reference must see them. | 111 | // The world-space triangles a geometry describes, as the reference must see them. |
| @@ -114,8 +115,9 @@ void expand(const Geometry& g, std::uint32_t geometry, std::vector<Tri>& out) { | |||
| 114 | Tri tri{}; | 115 | Tri tri{}; |
| 115 | for (int k = 0; k < 3; ++k) { | 116 | for (int k = 0; k < 3; ++k) { |
| 116 | const std::uint32_t v = g.indices.empty() ? 3 * t + k : g.indices[3 * t + k]; | 117 | const std::uint32_t v = g.indices.empty() ? 3 * t + k : g.indices[3 * t + k]; |
| 117 | float p[3] = {g.vertex_data[v * floats], g.vertex_data[v * floats + 1], | 118 | float p[3] = {std::nanf(""), std::nanf(""), std::nanf("")}; // past VertexCount: inactive, nothing read |
| 118 | g.xy ? 0.0f : g.vertex_data[v * floats + 2]}; | 119 | if (v < g.vertex_count) |
| 120 | for (int c = 0; c < 3; ++c) p[c] = c == 2 && g.xy ? 0.0f : g.vertex_data[v * floats + c]; | ||
| 119 | for (int c = 0; c < 3; ++c) | 121 | for (int c = 0; c < 3; ++c) |
| 120 | tri.v[k][c] = g.transform ? g.m[4 * c] * p[0] + g.m[4 * c + 1] * p[1] + g.m[4 * c + 2] * p[2] + g.m[4 * c + 3] | 122 | tri.v[k][c] = g.transform ? g.m[4 * c] * p[0] + g.m[4 * c + 1] * p[1] + g.m[4 * c + 2] * p[2] + g.m[4 * c + 3] |
| 121 | : p[c]; | 123 | : p[c]; |
| @@ -139,7 +141,7 @@ struct Built { | |||
| 139 | int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir, const std::string& name, | 141 | int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir, const std::string& name, |
| 140 | const std::vector<Geometry>& geometries, Built& built, unsigned rays = 0, | 142 | const std::vector<Geometry>& geometries, Built& built, unsigned rays = 0, |
| 141 | const std::vector<Geometry>* moved = nullptr, bool into_other = false, bool box16 = false, | 143 | const std::vector<Geometry>* moved = nullptr, bool into_other = false, bool box16 = false, |
| 142 | bool pair = false, bool expect_no_pairs = false) { | 144 | bool pair = false, bool expect_no_pairs = false, int poison = 0) { |
| 143 | std::vector<Buffer> keep, vertex_buffers; | 145 | std::vector<Buffer> keep, vertex_buffers; |
| 144 | std::vector<XdxrTriangles> descs; | 146 | std::vector<XdxrTriangles> descs; |
| 145 | std::uint32_t total = 0; | 147 | std::uint32_t total = 0; |
| @@ -153,6 +155,7 @@ int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir | |||
| 153 | d.vertex_stride = geo.stride; | 155 | d.vertex_stride = geo.stride; |
| 154 | d.xy_only = geo.xy; | 156 | d.xy_only = geo.xy; |
| 155 | d.triangle_count = geo.triangle_count; | 157 | d.triangle_count = geo.triangle_count; |
| 158 | d.vertex_count = geo.vertex_count; | ||
| 156 | d.flags = 1; | 159 | d.flags = 1; |
| 157 | keep.push_back(v); | 160 | keep.push_back(v); |
| 158 | vertex_buffers.push_back(v); | 161 | vertex_buffers.push_back(v); |
| @@ -223,12 +226,29 @@ int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir | |||
| 223 | Buffer other = into_other ? make(gpu, layout.size + 256) : Buffer{}; | 226 | Buffer other = into_other ? make(gpu, layout.size + 256) : Buffer{}; |
| 224 | const std::uint64_t target = into_other ? (other.address + 255) & ~std::uint64_t(255) : base; | 227 | const std::uint64_t target = into_other ? (other.address + 255) & ~std::uint64_t(255) : base; |
| 225 | EXPECT(!into_other || other.buffer); | 228 | EXPECT(!into_other || other.buffer); |
| 229 | // `poison`: the update's source is not a structure this layout built (a title passing one it never built). 1: all | ||
| 230 | // zero, 2: random bytes, 3: the built structure with another element count in its header, 4: its header kept and | ||
| 231 | // the rest random. The builder must read nothing past the layout; 1-3 then become a full build of the moved | ||
| 232 | // geometry (check-build validates it), 4 refits garbage pointers, whose result is not checked, only that it ends. | ||
| 233 | if (poison) { | ||
| 234 | auto* s = reinterpret_cast<std::uint32_t*>(static_cast<char*>(dst.map) + (base - dst.address)); | ||
| 235 | std::mt19937 prng(11); | ||
| 236 | const std::size_t words = layout.size / 4; | ||
| 237 | if (poison == 1) std::fill(s, s + words, 0u); | ||
| 238 | if (poison == 2) for (std::size_t w = 0; w < words; ++w) s[w] = std::uint32_t(prng()); | ||
| 239 | if (poison == 3) s[3] += 1; | ||
| 240 | if (poison == 4) for (std::size_t w = 16; w < words; ++w) s[w] = std::uint32_t(prng()); | ||
| 241 | } | ||
| 226 | EXPECT(gpu.run([&](VkCommandBuffer cb) { | 242 | EXPECT(gpu.run([&](VkCommandBuffer cb) { |
| 227 | recorded = builder.record_blas(cb, layout, descs, target, scratch.address, base); | 243 | recorded = builder.record_blas(cb, layout, descs, target, scratch.address, base); |
| 228 | barrier_to_host(gpu, cb); | 244 | barrier_to_host(gpu, cb); |
| 229 | return recorded; | 245 | return recorded; |
| 230 | })); | 246 | })); |
| 231 | if (into_other) EXPECT(dump(name + "_source", dst, base, built.tris)); // a refit must not touch its source | 247 | if (poison == 4) { |
| 248 | std::printf("%s: %u triangles refitted from a garbage tree, %u bytes\n", name.c_str(), total, layout.size); | ||
| 249 | return 0; | ||
| 250 | } | ||
| 251 | if (into_other && !poison) EXPECT(dump(name + "_source", dst, base, built.tris)); // a refit must not touch its source | ||
| 232 | EXPECT(dump(name, into_other ? other : dst, target, moved_tris)); | 252 | EXPECT(dump(name, into_other ? other : dst, target, moved_tris)); |
| 233 | built.tris = moved_tris; | 253 | built.tris = moved_tris; |
| 234 | built.address = target; | 254 | built.address = target; |
| @@ -349,6 +369,18 @@ int main(int argc, char** argv) { | |||
| 349 | b.vertex_data[3 * 3 * 7] = std::nanf(""); // triangle 7 of geometry 1: inactive | 369 | b.vertex_data[3 * 3 * 7] = std::nanf(""); // triangle 7 of geometry 1: inactive |
| 350 | if (build_blas(gpu, builder, dir, "blas_two_geometries", {a, b}, multi)) return 1; | 370 | if (build_blas(gpu, builder, dir, "blas_two_geometries", {a, b}, multi)) return 1; |
| 351 | if (build_blas(gpu, builder, dir, "blas_empty", {}, empty)) return 1; | 371 | if (build_blas(gpu, builder, dir, "blas_empty", {}, empty)) return 1; |
| 372 | // VertexCount bounds the vertex reads: an unindexed geometry whose last triangle lies past it (the buffer holds | ||
| 373 | // finite vertices there, so a read would show), an index far past the buffer, and VertexCount 0: those | ||
| 374 | // triangles are inactive. | ||
| 375 | { | ||
| 376 | Built bounded; | ||
| 377 | Geometry past = soup(8), wild = grid(4, 3, false), no_vertices = soup(2); | ||
| 378 | past.vertex_count = 21; | ||
| 379 | wild.vertex_count = 25; | ||
| 380 | wild.indices[3 * 5 + 1] = 0xfffffff0u; | ||
| 381 | no_vertices.vertex_count = 0; | ||
| 382 | if (build_blas(gpu, builder, dir, "blas_vertex_count", {past, wild, no_vertices}, bounded)) return 1; | ||
| 383 | } | ||
| 352 | // many radix-sort tiles (RADIX_TILE elements each), the last one partial (fewer rays: the brute force is slow) | 384 | // many radix-sort tiles (RADIX_TILE elements each), the last one partial (fewer rays: the brute force is slow) |
| 353 | Built tiles; | 385 | Built tiles; |
| 354 | if (build_blas(gpu, builder, dir, "blas_three_sort_tiles", {soup(5000)}, tiles, 200)) return 1; | 386 | if (build_blas(gpu, builder, dir, "blas_three_sort_tiles", {soup(5000)}, tiles, 200)) return 1; |
| @@ -374,6 +406,19 @@ int main(int argc, char** argv) { | |||
| 374 | const Geometry g = grid(12, 4, false); // R32 indices, stride 16; the small-sort path | 406 | const Geometry g = grid(12, 4, false); // R32 indices, stride 16; the small-sort path |
| 375 | const std::vector<Geometry> after_grid = {move(g, 0.3f)}; | 407 | const std::vector<Geometry> after_grid = {move(g, 0.3f)}; |
| 376 | if (build_blas(gpu, builder, dir, "blas_refit_into_other", {g}, copied, 0, &after_grid, true)) return 1; | 408 | if (build_blas(gpu, builder, dir, "blas_refit_into_other", {g}, copied, 0, &after_grid, true)) return 1; |
| 409 | // updates whose source is no structure of this layout: a full build instead, or (garbage tree) a bounded walk | ||
| 410 | const char* poisoned[] = {"blas_refit_zero_source", "blas_refit_garbage_source", "blas_refit_other_layout", | ||
| 411 | "blas_refit_garbage_tree"}; | ||
| 412 | for (int poison = 1; poison <= 4; ++poison) { | ||
| 413 | Built b; | ||
| 414 | if (build_blas(gpu, builder, dir, poisoned[poison - 1], {big}, b, 100, &after, poison == 2, false, false, | ||
| 415 | false, poison)) | ||
| 416 | return 1; | ||
| 417 | Built small; | ||
| 418 | if (build_blas(gpu, builder, dir, std::string(poisoned[poison - 1]) + "_small", {g}, small, 0, &after_grid, | ||
| 419 | poison != 2, false, false, false, poison)) | ||
| 420 | return 1; | ||
| 421 | } | ||
| 377 | } | 422 | } |
| 378 | 423 | ||
| 379 | // BOX16 inner nodes: the same tree with half boxes rounded outward (64-byte nodes instead of 128). | 424 | // BOX16 inner nodes: the same tree with half boxes rounded outward (64-byte nodes instead of 128). |
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 | ||
| 13 | namespace { | 17 | namespace { |
| 14 | 18 | ||
| 15 | using XApuConnectFn = HRESULT(__stdcall*)(void*, void*, void**); | 19 | using XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**); |
| 16 | using XApuDisconnectFn = HRESULT(__stdcall*)(void*); | 20 | using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t); |
| 17 | using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const uint32_t*, uint64_t); | 21 | using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*); |
| 18 | using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint64_t); | 22 | using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*); |
| 19 | using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); | 23 | using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); |
| 20 | using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**); | 24 | using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**); |
| 21 | using XDspActivateFn = HRESULT(__stdcall*)(void*, const void*, void**, void**); | 25 | using XDspActivateFn = HRESULT(__stdcall*)(void*, const void*, void**, void**); |
| @@ -23,6 +27,55 @@ using XDspDeactivateFn = HRESULT(__stdcall*)(void*, uint64_t, uint64_t, uint64_t | |||
| 23 | using XDspDisconnectFn = HRESULT(__stdcall*)(void*); | 27 | using XDspDisconnectFn = HRESULT(__stdcall*)(void*); |
| 24 | using XDspSubmitCommandFn = HRESULT(__stdcall*)(void*, void*, uint32_t*); | 28 | using XDspSubmitCommandFn = HRESULT(__stdcall*)(void*, void*, uint32_t*); |
| 25 | 29 | ||
| 30 | constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u); | ||
| 31 | constexpr HRESULT kNoResult = static_cast<HRESULT>(0x8AC81001u); | ||
| 32 | constexpr HRESULT kInvalidCommand = static_cast<HRESULT>(0x8AC81002u); | ||
| 33 | constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u); | ||
| 34 | constexpr HRESULT kAlreadyActive = static_cast<HRESULT>(0x8AC81005u); | ||
| 35 | constexpr HRESULT kBadPacket = static_cast<HRESULT>(0x8AC81008u); | ||
| 36 | |||
| 37 | #pragma pack(push, 1) | ||
| 38 | struct ConnectInput { | ||
| 39 | uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options; | ||
| 40 | }; | ||
| 41 | struct ConnectOutput { | ||
| 42 | void* memory; | ||
| 43 | HANDLE result_event; | ||
| 44 | }; | ||
| 45 | struct CommandId { | ||
| 46 | uint32_t kind, stream, sequence, options; | ||
| 47 | uint64_t context; | ||
| 48 | }; | ||
| 49 | struct 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 | }; | ||
| 57 | struct 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 | }; | ||
| 65 | struct 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) | ||
| 77 | static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts"); | ||
| 78 | |||
| 26 | int g_checks = 0; | 79 | int g_checks = 0; |
| 27 | int g_failures = 0; | 80 | int 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 | ||
| 95 | CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; } | ||
| 96 | |||
| 42 | } // namespace | 97 | } // namespace |
| 43 | 98 | ||
| 44 | int main() { | 99 | int 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 | |||
| 17 | namespace { | ||
| 18 | |||
| 19 | using XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**); | ||
| 20 | using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t); | ||
| 21 | using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*); | ||
| 22 | using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*); | ||
| 23 | using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); | ||
| 24 | |||
| 25 | constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u); | ||
| 26 | constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u); | ||
| 27 | |||
| 28 | #pragma pack(push, 1) | ||
| 29 | struct ConnectInput { | ||
| 30 | uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options; | ||
| 31 | }; | ||
| 32 | struct ConnectOutput { | ||
| 33 | void* memory; | ||
| 34 | HANDLE result_event; | ||
| 35 | }; | ||
| 36 | struct CommandId { | ||
| 37 | uint32_t kind, stream, sequence, options; | ||
| 38 | uint64_t context; | ||
| 39 | }; | ||
| 40 | struct 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 | }; | ||
| 48 | struct 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 | }; | ||
| 56 | struct 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) | ||
| 68 | static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts"); | ||
| 69 | |||
| 70 | int g_checks = 0; | ||
| 71 | int g_failures = 0; | ||
| 72 | |||
| 73 | void 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 | |||
| 79 | template <typename T> | ||
| 80 | T 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 | |||
| 86 | CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; } | ||
| 87 | |||
| 88 | } // namespace | ||
| 89 | |||
| 90 | int 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/xgameruntime_gamesave_test.cpp b/runtime/test/xgameruntime_gamesave_test.cpp index b53461944..2e5944ad8 100644 --- a/runtime/test/xgameruntime_gamesave_test.cpp +++ b/runtime/test/xgameruntime_gamesave_test.cpp | |||
| @@ -228,6 +228,20 @@ int main() { | |||
| 228 | std::strcmp(out[1].info.name, "profile/main") == 0 && | 228 | std::strcmp(out[1].info.name, "profile/main") == 0 && |
| 229 | std::memcmp(out[1].data, profile.data(), profile.size()) == 0, | 229 | std::memcmp(out[1].data, profile.data(), profile.size()) == 0, |
| 230 | "ReadBlobData returns both blobs, byte for byte, pointing into the buffer"); | 230 | "ReadBlobData returns both blobs, byte for byte, pointing into the buffer"); |
| 231 | // A title sizes the buffer as sizeof(XGameSaveBlob) + data + name and its NUL per blob, with no padding: such a | ||
| 232 | // buffer is enough, the blobs packed back to back. | ||
| 233 | const char* one[] = {"story"}; | ||
| 234 | count = 1; | ||
| 235 | std::vector<uint8_t> exact(sizeof(Blob) + story.size() + std::strlen("story") + 1); | ||
| 236 | auto* tight = reinterpret_cast<Blob*>(exact.data()); | ||
| 237 | check(at<Read>(save, 20)(save, container, one, &count, exact.size(), tight) == S_OK && count == 1 && | ||
| 238 | std::strcmp(tight[0].info.name, "story") == 0 && tight[0].info.size == story.size() && | ||
| 239 | std::memcmp(tight[0].data, story.data(), story.size()) == 0 && | ||
| 240 | tight[0].info.name + std::strlen("story") + 1 <= reinterpret_cast<const char*>(exact.data() + exact.size()), | ||
| 241 | "ReadBlobData into a buffer of the unpadded size returns the blob"); | ||
| 242 | count = 1; | ||
| 243 | check(at<Read>(save, 20)(save, container, one, &count, exact.size() - 1, tight) == E_GS_PROVIDED_BUFFER_TOO_SMALL, | ||
| 244 | "one byte less than the unpadded size is too small"); | ||
| 231 | const char* absent[] = {"nope"}; | 245 | const char* absent[] = {"nope"}; |
| 232 | count = 1; | 246 | count = 1; |
| 233 | check(at<Read>(save, 20)(save, container, absent, &count, buffer.size() * 8, out) == E_GS_BLOB_NOT_FOUND, | 247 | check(at<Read>(save, 20)(save, container, absent, &count, buffer.size() * 8, out) == E_GS_BLOB_NOT_FOUND, |
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 991388c7f..79f655412 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp | |||
| @@ -741,7 +741,19 @@ void test_copy_page_mappings_cpu_view(const PhysicalApi& api) { | |||
| 741 | check(readable(other) && page_holds(other, 0x7300u), | 741 | check(readable(other) && page_holds(other, 0x7300u), |
| 742 | "a GPU-only source page unmapped there is looked up at its CPU range"); | 742 | "a GPU-only source page unmapped there is looked up at its CPU range"); |
| 743 | 743 | ||
| 744 | // A null source unmaps both ranges. | 744 | // 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 |
| 745 | // GPU-only page alone (the console's CopyPageMappingsBatchX edits only that range's page table). | ||
| 746 | check(copy(gpu + 2 * kPage64k, pool + kPage64k, 1, false), "a copy onto a GPU-only page whose CPU page is the title's"); | ||
| 747 | check(readable(gpu + 2 * kPage64k) && page_holds(gpu + 2 * kPage64k, 0x7301u), | ||
| 748 | "the GPU-only page shows the copied pool page"); | ||
| 749 | check(readable(cpu + 2 * kPage64k) && page_holds(cpu + 2 * kPage64k, 0x7300u), | ||
| 750 | "the title's own mapping at the paired CPU page is kept, not replaced by the copy"); | ||
| 751 | check(copy(gpu + 2 * kPage64k, nullptr, 1, false), "a null source unmaps a GPU-only page whose CPU page is the title's"); | ||
| 752 | check(!readable(gpu + 2 * kPage64k), "the GPU-only page is unmapped"); | ||
| 753 | check(readable(cpu + 2 * kPage64k) && page_holds(cpu + 2 * kPage64k, 0x7300u), | ||
| 754 | "the title's own mapping at the paired CPU page survives the unmap"); | ||
| 755 | |||
| 756 | // 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"); | 757 | 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"); | 758 | check(!readable(gpu) && !readable(cpu) && !readable(cpu + kPage64k), "the paired CPU range is unmapped with it"); |
| 747 | 759 | ||
| @@ -1544,6 +1556,38 @@ void test_physical_pages_commit_on_touch(const PhysicalApi& api) { | |||
| 1544 | check(read_ok, "ReadFile fills a page that commit_physical_range committed"); | 1556 | check(read_ok, "ReadFile fills a page that commit_physical_range committed"); |
| 1545 | 1557 | ||
| 1546 | check(api.map(second, 2, nullptr) == second && api.map(window, kMapped, nullptr) == window, "they unmap"); | 1558 | check(api.map(second, 2, nullptr) == second && api.map(window, kMapped, nullptr) == window, "they unmap"); |
| 1559 | { | ||
| 1560 | // A host guarded read (outside the title image at 0x140000000) of an unmapped window page exits as | ||
| 1561 | // passed_guarded without counting as left_to_title; a title read still counts as left_to_title. | ||
| 1562 | void* const stub_page = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); | ||
| 1563 | const uint8_t mov_eax_rcx_ret[] = {0x8b, 0x01, 0xc3}; | ||
| 1564 | DWORD stub_old = 0; | ||
| 1565 | bool stub_ready = false; | ||
| 1566 | if (stub_page) { | ||
| 1567 | std::memcpy(stub_page, mov_eax_rcx_ret, sizeof(mov_eax_rcx_ret)); | ||
| 1568 | stub_ready = VirtualProtect(stub_page, 4096, PAGE_EXECUTE_READ, &stub_old) != FALSE; | ||
| 1569 | FlushInstructionCache(GetCurrentProcess(), stub_page, sizeof(mov_eax_rcx_ret)); | ||
| 1570 | } | ||
| 1571 | const auto host_read_faults = [&](const void* p) { | ||
| 1572 | __try { | ||
| 1573 | reinterpret_cast<uint32_t (*)(const void*)>(stub_page)(p); | ||
| 1574 | return false; | ||
| 1575 | } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER | ||
| 1576 | : EXCEPTION_CONTINUE_SEARCH) { | ||
| 1577 | return true; | ||
| 1578 | } | ||
| 1579 | }; | ||
| 1580 | const uint64_t guarded_before = rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded); | ||
| 1581 | const uint64_t left_before = rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title); | ||
| 1582 | check(stub_ready && host_read_faults(second) && | ||
| 1583 | rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded) == guarded_before + 1 && | ||
| 1584 | rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before, | ||
| 1585 | "a host guarded read of an unmapped window page exits as passed_guarded"); | ||
| 1586 | check(access_faults(reinterpret_cast<volatile uint32_t*>(second), false) && | ||
| 1587 | rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before + 1, | ||
| 1588 | "a title read of an unmapped window page still exits as left_to_title"); | ||
| 1589 | if (stub_page) VirtualFree(stub_page, 0, MEM_RELEASE); | ||
| 1590 | } | ||
| 1547 | check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them"); | 1591 | check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them"); |
| 1548 | } | 1592 | } |
| 1549 | 1593 | ||
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. |