From 7ca448516f850b545882c70b30a7ec763fc1d8ca Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:08:24 +0100 Subject: [PATCH 01/49] d3d12: an image made for slot-70 views holds no device reference, so a released device goes (RT-SLOT70-DEVICE-CYCLE) make_title_texture made its image with create_committed, which attaches the device; the registry (state_.title_textures) holds the image, and a retired image waits in retired_title_textures_ for a refresh pass 3 s later, which only runs before a submission. A device released while such an image existed was never destroyed and kept every Vulkan object it had: d3d12_existing_heap's device without host image copies left 93 at vkDestroyDevice (VUID-vkDestroyDevice-device-05137). The image now drops its device reference right after it is made, as the registry's reference keeps it alive, and ~Device releases the registry's and the retired images after the GPU is idle (release_title_images), before the deferred deletions are drained. d3d12_existing_heap checks that the last Release of each device returns 0 and fails on validation errors counted after vkDestroyDevice. --- docs/d3d12_vulkan.md | 5 +++ runtime/shims/d3d12_vulkan_device.cpp | 21 +++++++++++++ runtime/test/d3d12_existing_heap_test.cpp | 38 ++++++++++++++++++++--- 3 files changed, 60 insertions(+), 4 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e843d8debc..37f82588d3 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3578,6 +3578,11 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv over the map itself would step into a freed node (measured: an access violation reading the nil flag of a null child, 0x19, in `Device::refresh_title_textures`). The snapshot also holds a reference to each entry, so an entry retired during the pass is still alive when its turn comes. +- An image made for slot-70 views (`make_title_texture`) is held by the registry and holds no reference to the device; + a retired one is released by the first refresh pass 3 s later, and `~Device` releases the rest after the GPU is idle + (`release_title_images`). With a device reference, a device released before those passes never went: it kept every + Vulkan object it had (`d3d12_existing_heap`'s device without host image copies: 93 at `vkDestroyDevice` on an + RX 7900 XT, VUID-vkDestroyDevice-device-05137). - Sampled title images can use device-local memory even when Vulkan host image copies require a host-visible memory type. The runtime queries the same image with and without host-transfer usage. When only the latter permits plain device-local backing, it detiles the complete image into a reusable diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 748d6144a5..e12279f01c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -16038,6 +16038,7 @@ class Device final state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); } + release_title_images(); // their Vulkan objects go to the deferred queue drained next state_.context->drain_deleted_resources(UINT64_MAX); state_.context->set_pipeline_workers(nullptr); // before the pipeline cache is written and destroyed state_.context->set_bindless_release(nullptr, nullptr); @@ -17148,6 +17149,11 @@ class Device final log_once("an image for a slot-70 texture view could not be made; HRESULT", int(hr)); return refuse_title_view("image not created", d, address), nullptr; } + // The registry's reference keeps the image and the device keeps the registry, so the image holds no device + // reference: with one, a device its title (or a test) released stayed alive, with all its Vulkan objects, + // while an image made here was in the registry or retired and not yet released (3 s on, at a refresh pass a + // released device never runs). ~Device releases what is left (release_title_images). + r->attach_device(nullptr); if (!title_layout_fits(entry->layout, d, *r, why)) { r->Release(); return refuse_title_view(why, d, address), nullptr; @@ -17187,6 +17193,21 @@ class Device final ++title_stats_.retired; } + // Device teardown, after the GPU is idle: the last release of the images made for slot-70 views, those in the + // registry and those retired. Each destructor reaches the device state, so this comes before the context goes. + void release_title_images() { + std::vector release; + { + std::lock_guard lock(state_.title_texture_mutex); + for (auto& [address, t] : state_.title_textures) + if (t && t->owned && t->resource) release.push_back(std::exchange(t->resource, nullptr)); + for (const auto& [when, r] : retired_title_textures_) release.push_back(r); + retired_title_textures_.clear(); + retired_backing_ = 0; + } + for (Resource* r : release) r->Release(); + } + // LEONIDA_TITLE_PARTIAL_MIPS=1 (off by default). A slot-70 2D texture whose larger mips are not readable is filled from the // first mip that is, with every smaller one, when its last view starts there or later. The T#s of views that start // above stay on the fallback (PendingImage::first_mip), so no shader samples a mip that was not filled. Larger diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 1d940a7e48..f108b40b50 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -4,7 +4,8 @@ // on the host devices too. With VK_EXT_external_memory_host, OpenExistingHeapFromAddress on real host memory is // compared case by case with the host devices (open_cases: RTX 4090 and WARP agree), and a heap is opened on a // committed range; without it, the device reports EXISTING_HEAPS unsupported and answers an accepted range E_NOTIMPL. -// No shaders or game data. +// Each Vulkan-backed device goes with the test's last reference to it (release_device), and under +// LEONIDA_VK_VALIDATION=1 vkDestroyDevice must find nothing left over. No shaders or game data. // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress #include "../shims/title_gpu_placements.h" #include "../shims/xg_xs_layout.h" @@ -2387,9 +2388,19 @@ void print_cases(const std::vector& cases, const char* who) { int(c.desc.Properties.CPUPageProperty), int(c.desc.Properties.MemoryPoolPreference), unsigned(c.desc.Flags)); } -} // namespace -int main(int argc, char** argv) { +// The test's last reference to a device destroys it: nothing the layer made for it keeps it alive, such as the images +// made for slot-70 views, live or retired (a retired one is released at the first refresh pass 3 s later, which a +// device released before then never reaches). Otherwise the device and all its Vulkan objects outlive the test and +// vkDestroyDevice reports them (VUID-vkDestroyDevice-device-05137). +int release_device(Ref& device, const char* who) { + const ULONG left = device.p->Release(); + device.p = nullptr; + EXPECT(left == 0); + return 0; +} + +int run(int argc, char** argv) { const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0; const bool async_plane = argc == 2 && std::strcmp(argv[1], "--mapped-plane-async") == 0; if (argc != 1 && !prefix_only && !async_plane) return 2; @@ -2418,7 +2429,8 @@ int main(int argc, char** argv) { if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; if (prefix_only) { if (!vk.host_pointer_alignment) return 77; - const int result = check_host_prefix_buffers(ours.p); + int result = check_host_prefix_buffers(ours.p); + result += release_device(ours, "vulkan device"); return result || vk.validation_errors() ? 1 : 0; } if (async_plane) { @@ -2428,6 +2440,8 @@ int main(int argc, char** argv) { Ref staged; if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; result += check_mapped_plane_first_use(staged.p); + result += release_device(staged, "staged device"); + result += release_device(ours, "vulkan device"); return result || vk.validation_errors() ? 1 : 0; } failures += check(ours.p, "vulkan"); @@ -2455,6 +2469,7 @@ int main(int argc, char** argv) { failures += check_shared_bc_placements(staged.p, true); failures += check_mapped_plane(staged.p); failures += check_mapped_bc_array(staged.p); + failures += release_device(staged, "staged device"); } failures += check_written_pages_all(ours.p); { @@ -2468,6 +2483,7 @@ int main(int argc, char** argv) { failures += check_write_watched(ours.p, second.p, modifier); failures += check_rereserved(ours.p); } + if (second.p) failures += release_device(second, "second device"); } failures += check_heap_lock_faults(ours.p); Ref factory; @@ -2485,6 +2501,7 @@ int main(int argc, char** argv) { if (vk.host_pointer_alignment) failures += compare_cases(vulkan_cases, host_cases, who.c_str()); } } + failures += release_device(ours, "vulkan device"); } if (vk.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", vk.validation_errors()); @@ -2492,3 +2509,16 @@ int main(int argc, char** argv) { } return failures ? 1 : 0; } +} // namespace + +int main(int argc, char** argv) { + // run's vktest::Device destroys the Vulkan device on return, so what vkDestroyDevice finds left over + // (VUID-vkDestroyDevice-device-05137 under LEONIDA_VK_VALIDATION=1) is counted here. + const int result = run(argc, argv); + if (result) return result; + if (const unsigned errors = vktest::validation_error_count()) { + std::fprintf(stderr, "%u validation errors at teardown\n", errors); + return 1; + } + return 0; +} From f28d6cf2a9d1dd82d0e3ba7a2906184761673d0b Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:08:39 +0100 Subject: [PATCH 02/49] d3d12_xs: PSO streams with equal shader bytecode share one copy (RT-PSO-BYTECODE-INTERN) PsoStreamRecord::capture copied the bytecode of every stage into the record's own blobs, so each slot 86 PSO kept a private copy of every container it was made from, and a slot 55 PSO kept another one when keep_pso_stream captured its stream again. The title makes some 50 000 slot 86 calls in its first boot from about 26 500 shaders (docs/embedded_shaders.md), and the carved containers average 9.6 KB on this machine, so most of them were kept many times over: an estimated 0.65 to 1.0 GB of private bytes. Both compile modes copied: keep_pso_stream by default, prepare_console_stream with LEONIDA_PIPELINE_COMPILE=on-demand. copy_pointed_data now takes the bytecode from a process-wide table keyed by the size and the DXBC checksum (bytes 4..19, as key_shader uses; FNV-1a over the bytes for a container without one). A candidate is only taken when all of its bytes are equal, since hand-built containers can share a checksum. The record holds a shared reference in payloads_->shaders and its stream points at the shared bytes, which are never written. The table holds weak references, swept every 1024 new entries, so a container is freed with the last PSO that uses it; the copy is made outside the table's lock and looked up again before it is added. The stream bytes, the bytecode every consumer reads and the containers a caller passes in (shared_native_graphics) are unchanged. pso_stream_test: two streams with equal bytecode in different buffers, 10000 streams of one VS/PS pair, and records made and freed on 8 threads share one copy per container; bytecode with an equal checksum but other bytes, and checksum-less bytecode that differs in one byte, are not merged. On d44285197 5 of its 41 checks fail and the 10000 records grow private bytes by 202.9 MiB; with this change all pass and they grow by 3.0 MiB. --- docs/d3d12_vulkan.md | 3 +- runtime/shims/d3d12_xs_pso_stream.cpp | 70 ++++++++- runtime/shims/d3d12_xs_pso_stream.h | 5 +- runtime/test/pso_stream_test.cpp | 197 ++++++++++++++++++++++++++ 4 files changed, 271 insertions(+), 4 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e843d8debc..36ab49c4a9 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -92,7 +92,8 @@ enough for the bundled middleware's `d3d12_xs` calls, not for the game. The laye start handles returned in RAX at heap slots 9/10. Implement the public chain plus those measured overrides explicitly; do not assume every slot. On the retail executable's higher device slots (`runtime/shims/d3d12_xs_device.cpp`), slot 86 routes `CreatePipelineState(desc, riid, out)` to PC slot 47 (`ID3D12Device2::CreatePipelineState`) and keeps - a deep copy of the stream on the PSO it returns; slot 55 (`CreateDerivedPipelineState(pBasePSO, n, pRecords, riid, + a deep copy of the stream on the PSO it returns (its shader bytecode once per content for the process, shared by + every PSO whose stream carries the same bytes); slot 55 (`CreateDerivedPipelineState(pBasePSO, n, pRecords, riid, out)`, `n` = 1..4 records of 0x14c bytes: a u32 tag, then the payload at +4) patches a copy of that stream and creates the PSO through the same path. Tags 0 (`D3D12_DEPTH_STENCIL_DESC`, on DEPTH_STENCIL or DEPTH_STENCIL1), 1 (`D3D12_RASTERIZER_DESC`), 2 (`D3D12_BLEND_DESC`) and 3 (sample mask) are the TomBox layout (GPL-3.0, diff --git a/runtime/shims/d3d12_xs_pso_stream.cpp b/runtime/shims/d3d12_xs_pso_stream.cpp index e2d0cb5b5d..715d2a73f7 100644 --- a/runtime/shims/d3d12_xs_pso_stream.cpp +++ b/runtime/shims/d3d12_xs_pso_stream.cpp @@ -3,9 +3,12 @@ #include "../src/shader_library.h" +#include #include #include #include +#include +#include namespace rt::d3d12_xs { namespace { @@ -106,6 +109,68 @@ const unsigned char* own_blob(std::vector>& blobs, co return blobs.back().data(); } +// Shader bytecode kept once per content for every record in the process. The title makes some 50 000 slot 86 calls +// in its first boot from about 26 500 shaders (docs/embedded_shaders.md; the carved containers average 9.6 KB), so a +// copy of each stage per record kept most containers many times over. A record holds a reference to the shared +// bytes and the table holds weak references only, so a container is freed with the last record that uses it. The +// bytes are never written after they are copied, so every stream that points at them reads what its own source held. +class ShaderTable { +public: + using ShaderData = PsoStreamRecord::ShaderData; + + ShaderData acquire(const void* source, std::size_t size) { + const auto* bytes = static_cast(source); + const std::uint64_t key = content_key(bytes, size); + { + std::lock_guard lock(mutex_); + if (auto found = find_locked(key, bytes, size)) return found; + } + // Copied outside the lock: another thread may have added the same bytes meanwhile, and then its copy is used. + auto made = std::make_shared>(bytes, bytes + size); + std::lock_guard lock(mutex_); + if (auto found = find_locked(key, bytes, size)) return found; + if (++added_ % 1024 == 0) std::erase_if(shaders_, [](const auto& entry) { return entry.second.expired(); }); + shaders_.emplace(key, made); + return made; + } + +private: + // A DXBC container carries a checksum of its contents in bytes 4..19, so that and the size pick the candidates + // without reading the whole program (as key_shader does in d3d12_vulkan_device.cpp). A container without one (all + // zero, as hand-built test containers have) or other bytecode is hashed with FNV-1a. A candidate is only taken + // when all its bytes are equal: hand-built containers can share a checksum. + static std::uint64_t content_key(const std::uint8_t* bytes, std::size_t size) { + std::uint64_t h = 0xcbf29ce484222325ull; + const auto mix = [&h](const std::uint8_t* data, std::size_t count) { + for (std::size_t i = 0; i < count; ++i) h = (h ^ data[i]) * 0x100000001b3ull; + }; + mix(reinterpret_cast(&size), sizeof(size)); + if (size >= 20 && std::memcmp(bytes, "DXBC", 4) == 0 && + std::any_of(bytes + 4, bytes + 20, [](std::uint8_t b) { return b != 0; })) + mix(bytes + 4, 16); + else + mix(bytes, size); + return h; + } + ShaderData find_locked(std::uint64_t key, const std::uint8_t* bytes, std::size_t size) { + const auto [first, last] = shaders_.equal_range(key); + for (auto it = first; it != last; ++it) + if (auto live = it->second.lock(); + live && live->size() == size && std::memcmp(live->data(), bytes, size) == 0) + return live; + return {}; + } + + std::mutex mutex_; + std::unordered_multimap>> shaders_; + std::uint64_t added_ = 0; +}; + +ShaderTable& shader_table() { + static auto* table = new ShaderTable; // never destroyed: a PSO may still be created during teardown + return *table; +} + // Holds a PsoStreamRecord as an IUnknown: the object keeps one reference, the creation code drops its own. class RecordOwner final : public IUnknown { public: @@ -303,7 +368,10 @@ bool PsoStreamRecord::copy_pointed_data(std::size_t type, std::size_t payload_of if (code.pShaderBytecode && code.BytecodeLength) { for (const auto& shader : payloads_->shaders) if (shader->data() == code.pShaderBytecode && shader->size() == code.BytecodeLength) return true; - code.pShaderBytecode = own_blob(payloads_->blobs, code.pShaderBytecode, code.BytecodeLength); + // Equal bytecode from any stream is kept once (ShaderTable); this record holds a reference to it. + ShaderData shared = shader_table().acquire(code.pShaderBytecode, code.BytecodeLength); + code.pShaderBytecode = shared->data(); + payloads_->shaders.push_back(std::move(shared)); std::memcpy(payload, &code, sizeof(code)); } return true; diff --git a/runtime/shims/d3d12_xs_pso_stream.h b/runtime/shims/d3d12_xs_pso_stream.h index bfeaf29b31..0d42397f99 100644 --- a/runtime/shims/d3d12_xs_pso_stream.h +++ b/runtime/shims/d3d12_xs_pso_stream.h @@ -42,7 +42,8 @@ inline constexpr unsigned kDerivedMaxRecords = 4; // An owned deep copy of one pipeline state stream. The root signature references are held until destruction; shader // bytecode, stream-output and input-layout arrays and strings, and cached blobs are copied, and their pointers in the -// copy point at the copies. +// copy point at the copies. Shader bytecode is copied once per content for the whole process: records whose streams +// carry equal bytecode, from any buffer, share one read-only copy, which lives as long as the last of them. class PsoStreamRecord { public: // Null when the stream is malformed, holds a subobject type this module does not walk, or is too large. @@ -74,7 +75,7 @@ class PsoStreamRecord { std::vector bytes_; struct Payloads { std::vector> blobs; // owned copies; their buffers do not move when this grows - std::vector shaders; + std::vector shaders; // the caller's containers and the shared bytecode copies std::vector roots; // AddRef'd ~Payloads(); }; diff --git a/runtime/test/pso_stream_test.cpp b/runtime/test/pso_stream_test.cpp index 07ac13a326..638d892f91 100644 --- a/runtime/test/pso_stream_test.cpp +++ b/runtime/test/pso_stream_test.cpp @@ -1,9 +1,15 @@ // Pipeline state stream copies and the derived-state patch (device slot 55) with synthetic streams only: no D3D12 // device, no game data. The layout rule is the one measured on the console's slot 86 stream (see the offsets check). #include +#include +#include +#include #include #include +#include +#include +#include #include #include "d3d12_xs_pso_stream.h" @@ -254,6 +260,194 @@ void test_refusals() { "a stream with an unmodelled subobject type is not captured"); } +// A hand-built container of `size` bytes: the DXBC magic, 16 checksum bytes made from `checksum` (all zero when it is +// 0, as a container without a checksum has) and a body filled from `seed`. The record parses none of it. +std::vector container(std::size_t size, unsigned char checksum, unsigned seed) { + std::vector bytes(size); + std::memcpy(bytes.data(), "DXBC", 4); + for (std::size_t i = 4; i < 20; ++i) bytes[i] = static_cast(checksum ? checksum + i : 0); + for (std::size_t i = 20; i < size; ++i) bytes[i] = static_cast(seed * 131 + i * 7 + (i >> 8)); + return bytes; +} + +// Root signature (null), VS and PS, as the title's slot 86 streams start. +std::vector shader_stream(const std::vector& vs, const std::vector& ps) { + StreamBuilder s; + ID3D12RootSignature* root = nullptr; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, 8, 8); + D3D12_SHADER_BYTECODE code{vs.data(), vs.size()}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &code, sizeof(code), 8); + code = {ps.data(), ps.size()}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, &code, sizeof(code), 8); + return s.bytes; +} + +// Captures a stream the test built; the record reads the stream and never writes it. +std::unique_ptr keep(const std::vector& stream) { + return rt::d3d12_xs::PsoStreamRecord::capture({stream.size(), const_cast(stream.data())}); +} + +D3D12_SHADER_BYTECODE stage_of(const rt::d3d12_xs::PsoStreamRecord& record, unsigned type) { + D3D12_SHADER_BYTECODE code{}; + std::memcpy(&code, record.bytes().data() + payload_of_type(record.bytes(), type), sizeof(code)); + return code; +} + +bool holds(const D3D12_SHADER_BYTECODE& code, const std::vector& bytes) { + return code.pShaderBytecode && code.BytecodeLength == bytes.size() && + std::memcmp(code.pShaderBytecode, bytes.data(), bytes.size()) == 0; +} + +std::uint64_t private_bytes() { + PROCESS_MEMORY_COUNTERS_EX counters{}; + counters.cb = sizeof(counters); + if (!GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&counters), + sizeof(counters))) + return 0; + return counters.PrivateUsage; +} + +void test_equal_bytecode_is_kept_once() { + // The title creates tens of thousands of PSOs from far fewer shaders, and every slot 86 stream points at the + // bytecode it was made from. Equal bytecode in many streams, from different source buffers, is kept once. + constexpr std::size_t kMeanContainer = 9800; // the corpus mean is about 9.6 KB per container + const auto vs_a = container(kMeanContainer, 0x40, 1); + const auto vs_a_again = vs_a; // another buffer with the same bytes, as a second load of the shader would be + const auto ps = container(kMeanContainer + 512, 0x80, 2); + const auto ps_again = ps; + const auto first_stream = shader_stream(vs_a, ps); + const auto second_stream = shader_stream(vs_a_again, ps_again); + + auto first = keep(first_stream); + auto second = keep(second_stream); + if (!first || !second) { check(false, "shader streams captured"); return; } + const auto vs1 = stage_of(*first, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto vs2 = stage_of(*second, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto ps1 = stage_of(*first, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS); + const auto ps2 = stage_of(*second, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS); + check(holds(vs1, vs_a) && holds(vs2, vs_a) && holds(ps1, ps) && holds(ps2, ps), + "every stage of the kept streams holds the source bytes"); + check(vs1.pShaderBytecode != vs_a.data() && vs2.pShaderBytecode != vs_a_again.data(), + "the kept bytecode is not the caller's buffer"); + check(vs1.pShaderBytecode == vs2.pShaderBytecode && ps1.pShaderBytecode == ps2.pShaderBytecode, + "two streams with equal bytecode in different buffers share one copy of each stage"); + check(vs1.pShaderBytecode != ps1.pShaderBytecode, "stages with different bytecode keep different copies"); + + // Bytecode with the same DXBC checksum and size but other bytes (hand-built containers can share one) stays apart. + auto vs_b = vs_a; + vs_b[kMeanContainer / 2] ^= 0xff; + const auto third_stream = shader_stream(vs_b, ps); + auto third = keep(third_stream); + if (!third) { check(false, "the equal-checksum stream is captured"); return; } + const auto vs3 = stage_of(*third, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + check(vs3.pShaderBytecode != vs1.pShaderBytecode && holds(vs3, vs_b) && holds(vs1, vs_a), + "equal checksums with different bytes are not merged, and each keeps its own bytes"); + check(stage_of(*third, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS).pShaderBytecode == ps1.pShaderBytecode, + "the third stream's PS, equal to the others, is still shared"); + + // Containers without a checksum (all zero, as hand-built ones have) are told apart by their bytes too. + const auto bare = container(4096, 0, 3); + const auto bare_again = bare; + auto bare_other = bare; + bare_other.back() ^= 0x01; + const auto s4 = shader_stream(bare, ps), s5 = shader_stream(bare_again, ps), s6 = shader_stream(bare_other, ps); + auto r4 = keep(s4); + auto r5 = keep(s5); + auto r6 = keep(s6); + if (!r4 || !r5 || !r6) { check(false, "the checksum-less streams are captured"); return; } + const auto b4 = stage_of(*r4, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto b5 = stage_of(*r5, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto b6 = stage_of(*r6, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + check(b4.pShaderBytecode == b5.pShaderBytecode && holds(b4, bare), "equal checksum-less bytecode is shared"); + check(b6.pShaderBytecode != b4.pShaderBytecode && holds(b6, bare_other), + "checksum-less bytecode that differs in its last byte is not merged"); + + // A derived PSO keeps the base's copies, and a record keeps the shared bytes alive after the others are gone. + std::vector patched = first->bytes(); + auto derived = rt::d3d12_xs::PsoStreamRecord::derived(*first, std::move(patched)); + first.reset(); + second.reset(); + const auto vs_derived = stage_of(*derived, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + check(vs_derived.pShaderBytecode == vs1.pShaderBytecode && holds(vs_derived, vs_a), + "a derived record shares the base's bytecode and keeps it after the base records are freed"); + derived.reset(); + auto again = keep(first_stream); + check(again && holds(stage_of(*again, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS), vs_a) && + holds(stage_of(*again, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS), ps), + "bytecode captured again after every record that held it was freed holds the source bytes"); +} + +void test_many_streams_share_their_bytecode() { + // N records of one VS and one PS: the streams' bytes are each record's own, the bytecode is kept once. + constexpr unsigned kRecords = 10000; + const auto vs = container(9800, 0x11, 4); + const auto ps = container(9400, 0x22, 5); + const auto stream = shader_stream(vs, ps); + std::vector> records; + records.reserve(kRecords); + const std::uint64_t before = private_bytes(); + for (unsigned i = 0; i < kRecords; ++i) + if (auto record = keep(stream)) + records.push_back(std::move(record)); + const std::uint64_t after = private_bytes(); + check(records.size() == kRecords, "10000 streams are captured"); + if (records.size() != kRecords) return; + const void* vs_kept = stage_of(*records[0], D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS).pShaderBytecode; + const void* ps_kept = stage_of(*records[0], D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS).pShaderBytecode; + std::size_t vs_shared = 0, ps_shared = 0, intact = 0; + for (const auto& record : records) { + const auto v = stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto p = stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS); + vs_shared += v.pShaderBytecode == vs_kept; + ps_shared += p.pShaderBytecode == ps_kept; + intact += holds(v, vs) && holds(p, ps) && record->bytes().size() == stream.size(); + } + check(intact == kRecords, "every one of the 10000 records holds the source bytecode and stream size"); + check(vs_shared == kRecords && ps_shared == kRecords, "the 10000 records share one copy of each stage"); + std::printf("INFO 10000 records of a %zu + %zu byte VS/PS: private bytes %+.1f MiB (%.1f MiB if each record kept " + "its own bytecode)\n", + vs.size(), ps.size(), (double(after) - double(before)) / (1024.0 * 1024.0), + double(kRecords) * double(vs.size() + ps.size()) / (1024.0 * 1024.0)); +} + +void test_streams_from_many_threads() { + // PSOs are created on many threads. Records made and freed side by side from the same three containers each hold + // their own source bytes, and the ones still alive at the end share one copy per content. + const std::vector shaders[3] = {container(6000, 0x31, 6), container(7000, 0x32, 7), + container(8000, 0x33, 8)}; + const std::vector streams[3] = {shader_stream(shaders[0], shaders[1]), + shader_stream(shaders[1], shaders[2]), + shader_stream(shaders[2], shaders[0])}; + constexpr unsigned kThreads = 8, kRounds = 2000; + std::vector>> kept(kThreads); + std::atomic wrong{0}; + std::vector threads; + for (unsigned t = 0; t < kThreads; ++t) + threads.emplace_back([&, t] { + for (unsigned i = 0; i < kRounds; ++i) { + const unsigned which = (t + i) % 3; + auto record = keep(streams[which]); + if (!record || !holds(stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS), shaders[which]) || + !holds(stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS), shaders[(which + 1) % 3])) + ++wrong; + if (i % 16 == t % 16) kept[t].push_back(std::move(record)); // the others are freed at once + } + }); + for (auto& thread : threads) thread.join(); + std::set copies; + bool intact = true; + for (const auto& list : kept) + for (const auto& record : list) { + const auto v = stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto p = stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS); + copies.insert(v.pShaderBytecode); + copies.insert(p.pShaderBytecode); + intact = intact && (holds(v, shaders[0]) || holds(v, shaders[1]) || holds(v, shaders[2])); + } + check(wrong.load() == 0 && intact, "records made and freed on 8 threads each hold their source bytecode"); + check(copies.size() == 3, "the records alive after 8 threads share one copy per container (3 in all)"); +} + } // namespace int main() { @@ -263,6 +457,9 @@ int main() { test_derive_single_and_all_tags(); test_stencil_mask_record(); test_refusals(); + test_equal_bytecode_is_kept_once(); + test_many_streams_share_their_bytecode(); + test_streams_from_many_threads(); std::printf("%s: %d failure(s)\n", g_failures ? "FAILED" : "OK", g_failures); return g_failures ? 1 : 0; } From 5fa9c200f8a060752487e7aba2758ee0f1f5dc4c Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:13:37 +0100 Subject: [PATCH 03/49] d3d12: upload memory comes back at its command allocator's Reset (RT-UPLOAD-ARENA-REWIND) The arena behind console list slot 148 (AllocateUploadMemory) only advanced: upload_alloc moved chunk->used forward and made a new 8 MiB UPLOAD buffer whenever nothing fitted, and the only release was destroy_upload_state when the device went. A title that uploads every frame (the XDXR builder asks count * 40 bytes per build) grew it by one buffer each time the newest was full, in VRAM with Resizable BAR and in host memory without, for as long as it ran. Each allocator now has its own chunks, keyed by the real allocator the list records into (ListProxy::allocator). The allocator proxy's Reset (slot 8), which D3D12 allows only once the GPU has finished the lists recorded into it, starts them from the front again when the real Reset succeeds; a chunk that served nothing for 8 of these in a row is given back, and the allocator proxy's release frees its chunks. A list's own Reset gives nothing back, and one allocator's Reset leaves another's memory alone. A freed chunk leaves the title VA table too under LEONIDA_UPLOAD_ALIAS=1, as at the device's release, and the upload log names it. upload_translate finds the chunk through a map ordered by CPU base instead of walking every chunk. LEONIDA_UPLOAD_REWIND=0 keeps the one arena all lists share, which only grows, as before (runtime/README.md). An allocator the device hands out unwrapped (a PC runtime's) never reaches the proxy's Reset, so its chunks still only advance until the device goes. xs_proxy_mock_test check_upload_rewind: 200 frames of {list Reset, 1 MiB, Close, allocator Reset} on one allocator made 25 chunks and moved the pointer 199 times before; now one chunk and the same pointer. Two allocators, a failed allocator Reset, a list moved to another allocator, an idle chunk given back and an allocator's release are covered too; --upload-rewind-off (new ctest) checks the switch. --- docs/d3d12_command_objects.md | 4 +- docs/d3d12_vulkan.md | 4 +- runtime/CMakeLists.txt | 2 + runtime/README.md | 1 + runtime/shims/d3d12_xs_device.cpp | 185 +++++++++++++++++++---- runtime/test/xs_proxy_mock_test.cpp | 218 +++++++++++++++++++++++++++- 6 files changed, 377 insertions(+), 37 deletions(-) diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index eea693c701..7746144618 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -411,7 +411,9 @@ Slot 148 matters beyond the builder: the address it returns is written by the CP as a root SRV address, so console upload memory has the same address for the CPU and the GPU. On a PC the two address spaces differ, so `d3d12_xs_device.cpp` carves a bump arena out of persistently-mapped UPLOAD-heap buffers: the title writes the mapped memory and the six root descriptor setters and the IA/SO view setters -translate the CPU pointer to the chunk's buffer device address before forwarding. +translate the CPU pointer to the chunk's buffer device address before forwarding. The buffers belong to the command +allocator the list records into: that allocator's Reset, which D3D12 allows only once the GPU has finished its +lists, carves them from the front again, and its release frees them (`LEONIDA_UPLOAD_REWIND`, runtime/README.md). The function at `0xd580` uses the 71/73 pair instead of the slot-146 barrier when the byte at RVA `0xd773c` is set. That byte is one of seven bools at `0xd7738`–`0xd773e` in zero-initialised `.bss`. The only accesses to them in diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e843d8debc..aa7c2e2dcc 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1903,8 +1903,8 @@ texture coverage and the game's use of tile streaming remain open. lookups a summary by format, type and tiling. - `LEONIDA_UNBACKED_VSHARP=1`: the buffer V#s `fix_vsharp` writes empty because nothing backs their base; one line for each of the first 120 distinct bases and every 8192 a summary by 4 GiB range of the base. -- `LEONIDA_UPLOAD_LOG=1` (`d3d12_xs_device.cpp`): each upload chunk (CPU base, device address, size) and the first 96, - then every 8192nd, `AllocateUploadMemory` result as an offset into its chunk. +- `LEONIDA_UPLOAD_LOG=1` (`d3d12_xs_device.cpp`): each upload chunk (CPU base, device address, size), made and given + back, and the first 96, then every 8192nd, `AllocateUploadMemory` result as an offset into its chunk. - `LEONIDA_UPLOAD_ALIAS=1` (an experiment, changes behaviour): enters each upload chunk's CPU range in the title VA table, so a V# the title wrote with the CPU pointer `AllocateUploadMemory` handed it is rewritten to the chunk instead of left empty. A chunk below the arena needs `LEONIDA_IMPORT_BELOW_ARENA=1` as well. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..af08e87b2b 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1505,6 +1505,8 @@ if(BUILD_TESTING) add_test(NAME xs_proxy_mock_env_slots_74 COMMAND xs_proxy_mock_test --env-slots-74) # LEONIDA_SLOT133_LAYOUT_WORD=1 (set by the test itself): the slot 133 stand-in reads its fourth word as a layout. add_test(NAME xs_proxy_mock_slot133_layout COMMAND xs_proxy_mock_test --slot133-layout) + # LEONIDA_UPLOAD_REWIND=0 (set by the test itself): the upload arena only advances, as before the rewind. + add_test(NAME xs_proxy_mock_upload_rewind_off COMMAND xs_proxy_mock_test --upload-rewind-off) endif() # Reads d3d12.h and takes MSVC options, so only where the Windows runtime is built. if(TARGET gta6rt) diff --git a/runtime/README.md b/runtime/README.md index cdce0a811d..24dfa8a674 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -449,6 +449,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_STRAY_RO_HEAL` | unset | `1`: a title write into a read-only page of title memory that no guard of ours owns (a guard left behind) makes the page writable again and retries the write, so the title goes on; a shadow may then miss that page's next writes for a frame. Unset: the first 32 such pages are logged. | | `LEONIDA_PRELUDE_QUEUE_WAIT` | on | The prelude pass of a submission (the console-heap pass) waits for the last submission of another queue that recorded one (`src/vulkan_backend.h`). `0` (an experiment): no wait, so the queues do not serialise on each other's submissions; a list may read what the other pass has not written yet. | | `LEONIDA_DEPTH_BOUNDS_SLOT70` | on | Slot 70 of the console command list is forwarded to `OMSetDepthBounds` (`shims/d3d12_xs_device.cpp`). `0` leaves the slot to the default thunk. | +| `LEONIDA_UPLOAD_REWIND` | on | The memory console list slot 148 (`AllocateUploadMemory`) hands out belongs to the command allocator the list records into (`shims/d3d12_xs_device.cpp`): the allocator's Reset carves its upload buffers from the front again, gives back the ones it has not used for 8 Resets, and its release frees them. A list's own Reset gives nothing back. `0` keeps the one arena all lists share, which only grows until the device goes, as before: one more 8 MiB buffer each time the newest is full, in VRAM with Resizable BAR and in host memory without. | | `LEONIDA_DESCRIPTOR_RING` | unset | *Diagnostic.* `1` records the descriptor-table slots each list binds (`shims/d3d12_com.cpp`), as `LEONIDA_DEVICE_FAULT=1` does; it takes a global lock on almost every table bind. | | `LEONIDA_DESC_PROBE` | unset | *Diagnostic.* `1` logs which console-heap slots the API wrote and which the title wrote itself, what the title's records decode to and whether the GPU can see them. It hashes every slot of every bound table at each submission. The log quotes title data: keep it local. | | `LEONIDA_DRAW_DIAG` | on with the local diagnostics or `LEONIDA_FSDRAW_PROBE` | *Diagnostic.* Logs the first 8 draws and one in 1,200 after them, with whether each was skipped for having no viewport, its pipeline, render target, viewport and scissor (`shims/d3d12_com.cpp`). `0` turns it off, any other value on. | diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index c5f12dc050..88af937a5c 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -76,6 +76,7 @@ #include #include #include +#include #include #include #include @@ -188,6 +189,10 @@ bool call_presentation(DeviceProxy* self, F&& f) { // Freed in proxy_release; defined where the states are complete. void destroy_present_state(void* present_state); void destroy_upload_state(void* upload_state); +// The upload memory console list slot 148 handed out under an allocator (the real one, as ListProxy::allocator names +// it): rewound at the allocator proxy's Reset and freed with the proxy. Defined with the upload arena. +void upload_allocator_reset(DeviceProxy* device, const void* allocator); +void upload_allocator_gone(DeviceProxy* device, const void* allocator); constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles @@ -1561,7 +1566,12 @@ template unsigned long child_release(ChildProxy* self) { note_child_slot(2); const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (refs == 0) destroy_child(self); + if (refs == 0) { + // The title's last reference to an allocator: the upload memory handed out under it goes with it. D3D12 asks + // the same of a release as of a Reset, that the GPU has finished the allocator's lists. + if constexpr (K == ChildKind::allocator) upload_allocator_gone(self->device, self->real); + destroy_child(self); + } return refs; } @@ -2701,6 +2711,14 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); auto fn = reinterpret_cast(self->real_vtable[Slot]); + if constexpr (K == ChildKind::allocator && Slot == 8) { + // Reset. D3D12 allows it only once the GPU has finished every list recorded into the allocator, so the + // upload memory handed out under it is free again and upload_allocator_reset rewinds it. A refused Reset + // (the Vulkan layer's while a list still records into the allocator) gives nothing back. + const std::uint64_t result = fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); + if (SUCCEEDED(static_cast(result))) upload_allocator_reset(self->device, self->real); + return result; + } if constexpr (K == ChildKind::fence && Slot == kFenceSignal) { const std::uint64_t result = fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); if (FenceMirror* m = self->mirror.load(std::memory_order_acquire)) refresh_mirror(m); @@ -2829,22 +2847,56 @@ constexpr unsigned kListSlots = 160; // address (the same backing memory) before forwarding. Translation covers the six root VA setters (console // 41-46); VAs inside view structs (IASetVertexBuffers/IASetIndexBuffer) and ExecuteIndirect arguments are not // rewritten yet and stay title addresses. +// +// The memory belongs to the command allocator the list records into, as the list's commands do. Each allocator has +// its own chunks, carved from front to back; its Reset (allocator slot 8), which D3D12 allows only once the GPU has +// finished every list recorded into it, starts them from the front again, and its release frees them. A list's own +// Reset gives nothing back: the allocator's earlier lists may still be pending. The arena used to only advance, so +// for as long as the title ran it grew by one 8 MiB buffer each time the newest was full, in VRAM with Resizable BAR +// and in host memory without. An allocator the device hands out unwrapped (a PC runtime's, see +// resolves_allocator_proxies) never reaches its Reset here: its chunks only advance, as before, until the device goes. +// LEONIDA_UPLOAD_REWIND=0 keeps the one arena all lists share, which only advances, as before. struct UploadChunk { - UploadChunk* next; + UploadChunk* next; // the allocator's next older chunk ID3D12Resource* resource; // the mapped buffer; released with the chunk std::uint8_t* cpu_base; D3D12_GPU_VIRTUAL_ADDRESS gpu_base; std::size_t size; std::size_t used; + unsigned idle_resets; // how many of its allocator's Resets in a row found it unused }; struct UploadArena { - UploadChunk* chunks = nullptr; + // Each allocator's chunks, newest first, by the real allocator (ListProxy::allocator). The null key holds the + // chunks of a list whose allocator is not known and, with LEONIDA_UPLOAD_REWIND=0, every chunk: nothing rewinds it. + std::map owners; + std::map by_cpu; // every chunk by its CPU base, for upload_translate std::mutex lock; }; constexpr std::size_t kUploadChunkMin = 8 << 20; // one chunk serves a title's whole frame of uploads +// A chunk that served nothing for this many Resets of its allocator in a row goes back, so an allocator keeps what its +// recent frames needed rather than the most they ever did. More than one, so that a load which comes and goes every +// other frame does not make and free a buffer each time. +constexpr unsigned kUploadIdleResets = 8; + +inline bool upload_rewind() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_UPLOAD_REWIND"); + return !(v && v[0] == '0' && v[1] == '\0'); + }(); + return on; +} + +// LEONIDA_UPLOAD_ALIAS=1 (experiment): see upload_chunk_new. +inline bool upload_alias() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_UPLOAD_ALIAS"); + return v && *v == '1'; + }(); + return on; +} // LEONIDA_UPLOAD_LOG=1 (diagnostic): each upload chunk (its CPU base, device address and size), and the first 96 and // then every 8192nd AllocateUploadMemory result as an offset into its chunk, so the addresses the title builds @@ -2902,11 +2954,7 @@ UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { // the title VA table, the chunk's CPU range answers with the chunk's console VA (its device address minus // heap_base), so a V# the title wrote with such a pointer is rewritten to the chunk instead of left empty. A // chunk below the arena has a negative console VA, usable in a V# only with LEONIDA_IMPORT_BELOW_ARENA=1. - static const bool alias = [] { - const char* v = std::getenv("LEONIDA_UPLOAD_ALIAS"); - return v && *v == '1'; - }(); - if (alias) { + if (upload_alias()) { const bool added = leonida::title_va_aliases().add(reinterpret_cast(chunk->cpu_base), chunk->size, chunk->gpu_base); std::fprintf(stderr, "[rt] d3d12_xs: upload chunk 0x%llx (%llu bytes) entered as an alias of console VA " @@ -2931,7 +2979,34 @@ UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { return chunk; } -std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_t alignment) { +// Unmaps and releases (or frees) a chunk that is out of its arena, so that no list is handed it again. +void upload_chunk_free(UploadChunk* chunk) { + if (chunk->resource) { + if (upload_alias()) + leonida::title_va_aliases().remove(reinterpret_cast(chunk->cpu_base), chunk->gpu_base); + chunk->resource->Unmap(0, nullptr); + chunk->resource->Release(); + } else { + VirtualFree(chunk->cpu_base, 0, MEM_RELEASE); + } + delete chunk; +} + +// Frees a list of chunks (linked by `next`) taken out of their arena; `why` names the reason in the upload log. +void upload_chunks_free(UploadChunk* chunk, const char* why) { + while (chunk) { + UploadChunk* next = chunk->next; + if (upload_log()) + std::fprintf(stderr, "[rt] upload-log: chunk at 0x%llx, %llu bytes, given back (%s)\n", + static_cast(reinterpret_cast(chunk->cpu_base)), + static_cast(chunk->size), why); + upload_chunk_free(chunk); + chunk = next; + } +} + +// `allocator` is the real allocator the list records into (ListProxy::allocator), the owner of what it hands out. +std::uint64_t upload_alloc(DeviceProxy* device, const void* allocator, std::uint64_t size, std::uint64_t alignment) { if (!device || !size) return 0; alignment = alignment < 16 ? 16 : alignment; // every measured call asked for 16 // Refuse what cannot be served before any arithmetic runs: only power-of-two alignments are measured, @@ -2956,9 +3031,11 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_ arena = static_cast(expected); } } + const void* const owner = upload_rewind() ? allocator : nullptr; std::lock_guard lock(arena->lock); const std::size_t need = static_cast(size); - for (UploadChunk* chunk = arena->chunks; chunk; chunk = chunk->next) { + const auto owned = arena->owners.find(owner); + for (UploadChunk* chunk = owned != arena->owners.end() ? owned->second : nullptr; chunk; chunk = chunk->next) { const std::size_t aligned = (chunk->used + (alignment - 1)) & ~(static_cast(alignment) - 1); if (aligned >= chunk->used && aligned <= chunk->size && need <= chunk->size - aligned) { chunk->used = aligned + need; @@ -2969,13 +3046,22 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_ } const std::size_t chunk_size = need + alignment > kUploadChunkMin ? need + alignment : kUploadChunkMin; UploadChunk* chunk = upload_chunk_new(device, chunk_size); + if (chunk) { + try { + UploadChunk*& newest = arena->owners[owner]; + arena->by_cpu.emplace(reinterpret_cast(chunk->cpu_base), chunk); + chunk->next = newest; + newest = chunk; + } catch (const std::bad_alloc&) { // no exception may leave a thunk for the title's code + upload_chunk_free(chunk); + chunk = nullptr; + } + } if (!chunk) { std::fprintf(stderr, "[rt] d3d12_xs: AllocateUploadMemory(%llu, %llu) failed\n", static_cast(size), static_cast(alignment)); return 0; } - chunk->next = arena->chunks; - arena->chunks = chunk; const std::size_t aligned = (alignment - 1) & ~(static_cast(alignment) - 1); // 0-based chunk->used = aligned + need; if (upload_log()) @@ -2989,36 +3075,70 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_ } // An address inside an upload chunk becomes the chunk's device address plus the offset; anything else — a -// real resource VA the title already holds — passes through. +// real resource VA the title already holds — passes through. Every root CBV/SRV/UAV and IA/SO view asks, so the +// chunk is found by its CPU base rather than by walking them all. std::uint64_t upload_translate(DeviceProxy* device, std::uint64_t va) { auto* arena = static_cast( device ? device->upload_state.load(std::memory_order_acquire) : nullptr); if (!arena) return va; std::lock_guard lock(arena->lock); - for (UploadChunk* chunk = arena->chunks; chunk; chunk = chunk->next) { - const std::uint64_t base = reinterpret_cast(chunk->cpu_base); - if (va >= base && va < base + chunk->size) return chunk->gpu_base + (va - base); + auto above = arena->by_cpu.upper_bound(va); // the first chunk starting past va + if (above == arena->by_cpu.begin()) return va; + const auto& [base, chunk] = *--above; + return va - base < chunk->size ? chunk->gpu_base + (va - base) : va; +} + +// The allocator proxy's Reset succeeded: the GPU is done with every list recorded into `allocator`, so its chunks are +// carved from the front again. One that served nothing for kUploadIdleResets of these in a row is given back. +void upload_allocator_reset(DeviceProxy* device, const void* allocator) { + auto* arena = static_cast( + device ? device->upload_state.load(std::memory_order_acquire) : nullptr); + if (!arena || !allocator) return; + UploadChunk* idle = nullptr; // taken out under the lock, freed after it + { + std::lock_guard lock(arena->lock); + const auto owned = arena->owners.find(allocator); + if (owned == arena->owners.end()) return; + UploadChunk** link = &owned->second; + while (UploadChunk* chunk = *link) { + chunk->idle_resets = chunk->used ? 0 : chunk->idle_resets + 1; + chunk->used = 0; + if (chunk->idle_resets < kUploadIdleResets) { + link = &chunk->next; + continue; + } + *link = chunk->next; + arena->by_cpu.erase(reinterpret_cast(chunk->cpu_base)); + chunk->next = idle; + idle = chunk; + } + if (!owned->second) arena->owners.erase(owned); } - return va; + upload_chunks_free(idle, "idle at its allocator's Resets"); +} + +// The allocator proxy's last reference went: its chunks go with it. +void upload_allocator_gone(DeviceProxy* device, const void* allocator) { + auto* arena = static_cast( + device ? device->upload_state.load(std::memory_order_acquire) : nullptr); + if (!arena || !allocator) return; + UploadChunk* gone = nullptr; + { + std::lock_guard lock(arena->lock); + const auto owned = arena->owners.find(allocator); + if (owned == arena->owners.end()) return; + gone = owned->second; + for (const UploadChunk* chunk = gone; chunk; chunk = chunk->next) + arena->by_cpu.erase(reinterpret_cast(chunk->cpu_base)); + arena->owners.erase(owned); + } + upload_chunks_free(gone, "its allocator was released"); } void destroy_upload_state(void* upload_state) { auto* arena = static_cast(upload_state); if (!arena) return; - for (UploadChunk* chunk = arena->chunks; chunk;) { - UploadChunk* next = chunk->next; - if (chunk->resource) { - const char* alias = std::getenv("LEONIDA_UPLOAD_ALIAS"); - if (alias && *alias == '1') - leonida::title_va_aliases().remove(reinterpret_cast(chunk->cpu_base), chunk->gpu_base); - chunk->resource->Unmap(0, nullptr); - chunk->resource->Release(); - } else { - VirtualFree(chunk->cpu_base, 0, MEM_RELEASE); - } - delete chunk; - chunk = next; - } + for (const auto& entry : arena->by_cpu) upload_chunk_free(entry.second); delete arena; } @@ -3610,7 +3730,8 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t } #endif if constexpr (Slot == kConsoleAllocateUpload) { - return upload_alloc(self->device, a1, a2); // (size, alignment); the comment at UploadChunk + // (size, alignment), under the allocator the list records into; the comment at UploadChunk + return upload_alloc(self->device, self->allocator, a1, a2); } if constexpr (Slot >= 69 && Slot <= 74) { // memory writes and waits, by the layout (console_value_op) const ConsoleValueOp op = console_value_op(Slot, layout); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index e808256231..32e9dcb240 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -117,6 +117,13 @@ struct Mock { Mock* completes_with; // fence: once its completed value reaches completes_at, a GetCompletedValue first std::uint64_t completes_at, completes_value; // signals that fence to completes_value (GPU order across queues) bool signals_complete; // queue: a Signal (slot 14) completes the fence at once, as an idle GPU would + // device: an UPLOAD-heap committed resource it makes is a mapped buffer of its own (`mapped`, freed with the last + // reference) with a device address of its own (`gpu_va`, outside the CPU's user range), as the upload chunks of + // console list slot 148 are on a real device. Off, Map hands out g_mock_mapped and the address is 0. + bool mapped_uploads; + std::uint8_t* mapped; // resource: what Map (slot 8) hands out, when set + std::uint64_t gpu_va; // resource: what GetGPUVirtualAddress (slot 11) returns, when set + HRESULT reset_result; // allocator: what Reset (slot 8) returns unsigned calls[kMockSlots]; std::uint64_t args[kMockSlots][6]; std::uint64_t array[kMockSlots][4]; // device: the first entries of the array argument, as received @@ -549,8 +556,10 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { *reinterpret_cast(a2) = mock_cpu_origin(); } if (m->kind == Kind::resource && slot == 8 && a3) { // Map(subresource, range, data): the test's readback - *reinterpret_cast(a3) = g_mock_mapped; + *reinterpret_cast(a3) = m->mapped ? m->mapped : g_mock_mapped; } + if (m->kind == Kind::resource && slot == 11 && m->gpu_va) return m->gpu_va; // GetGPUVirtualAddress + if (m->kind == Kind::allocator && slot == 8) return static_cast(m->reset_result); // Reset if (m->kind == Kind::heap && slot == 9) { if (a1) reinterpret_cast(a1)->ptr = kMockHeapCpuStart; return kMockHeapCpuStart; @@ -599,6 +608,10 @@ std::uint64_t WINAPI mock_slot(Mock* self, std::uint64_t a1, std::uint64_t a2, s self->held = nullptr; held->Release(); } + if (left == 0 && self->mapped) { // a mapped upload buffer's memory goes with it (gpu_va stays, for checks) + VirtualFree(self->mapped, 0, MEM_RELEASE); + self->mapped = nullptr; + } return static_cast(left); } else if constexpr (Slot == 5) { // SetPrivateDataInterface(guid, object): keeps one reference ++self->calls[5]; @@ -692,6 +705,13 @@ HRESULT WINAPI mock_create_committed_resource(Mock* self, const D3D12_HEAP_PROPE if (self->create_null || FAILED(self->create_result)) return self->create_result; Mock* child = new_mock(Kind::resource); self->last_child = child; + if (self->mapped_uploads && heap && heap->Type == D3D12_HEAP_TYPE_UPLOAD && desc && desc->Width) { + static std::uint64_t made = 0; + child->mapped = static_cast( + VirtualAlloc(nullptr, static_cast(desc->Width), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!child->mapped) return E_OUTOFMEMORY; + child->gpu_va = 0x0001000000000000ull + (++made << 32); + } return mock_query(child, riid, out); } @@ -2503,6 +2523,199 @@ int check_lists() { return 0; } +// ---- 9a. Upload memory comes back at its allocator's Reset ---- +// AllocateUploadMemory (console list slot 148) is asked every frame (the XDXR builder takes count * 40 bytes per +// build, docs/d3d12_command_objects.md §3.3a). The arena only ever advanced: 200 frames of 1 MiB made 25 chunks of +// 8 MiB, and kept them. D3D12 allows an allocator Reset only once the GPU has finished the lists recorded into it, so +// the memory handed out under that allocator is free again then. A list Reset gives nothing back (the allocator's +// other lists may still be pending), and one allocator's Reset leaves another's memory alone. + +constexpr std::uint64_t kUploadMiB = 1 << 20; + +// The resource of the one upload chunk made on `mock` since `seen` CreateCommittedResource calls, or null when there +// was not exactly one; `seen` moves on. +Mock* new_upload_chunk(const Mock* mock, unsigned& seen) { + const unsigned made = mock->calls[27] - seen; + seen = mock->calls[27]; + Mock* const chunk = mock->last_child; + return made == 1 && chunk && chunk->kind == Kind::resource && chunk->mapped ? chunk : nullptr; +} + +// 200 frames on one allocator: list Reset, 1 MiB at alignment 16, Close, allocator Reset. `moved` counts the frames +// whose pointer was not the first frame's, `chunks` the chunks they made. +int upload_frames(const Mock* mock, void* list, void* allocator, unsigned& moved, unsigned& chunks) { + const unsigned before = mock->calls[27]; + std::uint64_t first = 0; + moved = 0; + for (int frame = 0; frame < 200; ++frame) { + EXPECT(hr_of(raw(list, 139, word(allocator), 0)) == S_OK); + const std::uint64_t p = raw(list, 148, kUploadMiB, 16); + EXPECT(p && (p & 15) == 0); + std::memset(reinterpret_cast(p), frame & 0xff, 64); // the title writes what it was handed + if (!first) first = p; + if (p != first) ++moved; + EXPECT(hr_of(raw(list, 9)) == S_OK); // Close + EXPECT(hr_of(raw(allocator, 8)) == S_OK); // the allocator's Reset, once the GPU is done with it + } + chunks = mock->calls[27] - before; + std::printf("%s: 200 frames of 1 MiB on one allocator: the pointer moved in %u, %u upload chunks made\n", g_label, + moved, chunks); + return 0; +} + +// A device whose upload chunks are mapped buffers with their own device addresses, two allocator proxies and a +// closed list on each. +struct UploadSetup { + Mock* mock = nullptr; + void* device = nullptr; + void* allocator[2] = {}; + Mock* real_allocator[2] = {}; + void* list[2] = {}; + Mock* real_list[2] = {}; +}; + +int make_upload_setup(UploadSetup& s) { + const IID allocator_iid = __uuidof(ID3D12CommandAllocator); + const IID gcl_iid = __uuidof(ID3D12GraphicsCommandList); + s.device = make_device(s.mock, 9, true, true, true); + EXPECT(s.device); + s.mock->mapped_uploads = true; + for (int i = 0; i < 2; ++i) { + EXPECT(hr_of(raw(s.device, 9, 0, word(&allocator_iid), word(&s.allocator[i]))) == S_OK); + s.real_allocator[i] = s.mock->last_child; + EXPECT(xs::is_allocator_proxy(s.allocator[i])); + EXPECT(hr_of(raw(s.device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(s.allocator[i]), 0, word(&gcl_iid), + word(&s.list[i]))) == S_OK); + s.real_list[i] = s.mock->last_child; + EXPECT(hr_of(raw(s.list[i], 9)) == S_OK); // closed, as a title's list is between frames + } + return 0; +} + +bool upload_ranges_apart(std::uint64_t a, std::uint64_t b, std::uint64_t bytes) { + return a + bytes <= b || b + bytes <= a; +} + +int check_upload_rewind() { + UploadSetup s; + if (make_upload_setup(s)) return 1; + void* const list_a = s.list[0]; + void* const list_b = s.list[1]; + void* const allocator_a = s.allocator[0]; + void* const allocator_b = s.allocator[1]; + unsigned seen = s.mock->calls[27]; + + // One chunk serves every frame, and the pointer is the same each time. + unsigned moved = 0, made = 0; + if (upload_frames(s.mock, list_a, allocator_a, moved, made)) return 1; + EXPECT(moved == 0 && made == 1); + Mock* const chunk_a1 = new_upload_chunk(s.mock, seen); + EXPECT(chunk_a1 && chunk_a1->refs == 1); + const std::uint64_t a1 = word(chunk_a1->mapped); + + // The root SRV setter (console 43 -> PC 39) gets the chunk's device address for a pointer into it. + EXPECT(hr_of(raw(list_a, 139, word(allocator_a), 0)) == S_OK); + EXPECT(raw(list_a, 148, kUploadMiB, 16) == a1); + EXPECT(hr_of(raw(list_a, 43, 0, a1 + 0x123)) == S_OK && s.real_list[0]->args[39][1] == chunk_a1->gpu_va + 0x123); + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + + // A failed allocator Reset (the Vulkan layer refuses one while a list records into it) gives nothing back. + s.real_allocator[0]->reset_result = E_FAIL; + EXPECT(hr_of(raw(allocator_a, 8)) == E_FAIL); + s.real_allocator[0]->reset_result = S_OK; + EXPECT(hr_of(raw(list_a, 139, word(allocator_a), 0)) == S_OK); + EXPECT(raw(list_a, 148, kUploadMiB, 16) == a1 + kUploadMiB); + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + EXPECT(hr_of(raw(allocator_a, 8)) == S_OK); + + // Allocator B's memory is its own: A's Resets do not hand it out again. + EXPECT(hr_of(raw(list_b, 139, word(allocator_b), 0)) == S_OK); + const std::uint64_t b1 = raw(list_b, 148, kUploadMiB, 16); + EXPECT(b1 && upload_ranges_apart(b1, a1, 8 * kUploadMiB)); + std::memset(reinterpret_cast(b1), 0xb1, kUploadMiB); + EXPECT(hr_of(raw(list_b, 9)) == S_OK); + Mock* const chunk_b = new_upload_chunk(s.mock, seen); + EXPECT(chunk_b && b1 == word(chunk_b->mapped)); + // Two frames of 16 MiB on A meanwhile: a second chunk for A, then both again. + for (int frame = 0; frame < 2; ++frame) { + EXPECT(hr_of(raw(list_a, 139, word(allocator_a), 0)) == S_OK); + for (int i = 0; i < 16; ++i) { + const std::uint64_t p = raw(list_a, 148, kUploadMiB, 16); + EXPECT(p && upload_ranges_apart(p, b1, kUploadMiB)); + std::memset(reinterpret_cast(p), 0xa0, kUploadMiB); + } + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + EXPECT(hr_of(raw(allocator_a, 8)) == S_OK); + } + Mock* const chunk_a2 = new_upload_chunk(s.mock, seen); + EXPECT(chunk_a2); + const auto* b_bytes = reinterpret_cast(b1); + EXPECT(std::all_of(b_bytes, b_bytes + kUploadMiB, [](std::uint8_t v) { return v == 0xb1; })); + + // A list Reset gives nothing back: B's next pointer is new memory, and B's own Reset brings b1 back. + EXPECT(hr_of(raw(list_b, 139, word(allocator_b), 0)) == S_OK); + const std::uint64_t b2 = raw(list_b, 148, kUploadMiB, 16); + EXPECT(b2 && upload_ranges_apart(b2, b1, kUploadMiB)); + EXPECT(hr_of(raw(list_b, 9)) == S_OK); + EXPECT(hr_of(raw(allocator_b, 8)) == S_OK); + EXPECT(hr_of(raw(list_b, 139, word(allocator_b), 0)) == S_OK); + EXPECT(raw(list_b, 148, kUploadMiB, 16) == b1); + EXPECT(hr_of(raw(list_b, 9)) == S_OK); + // A list records into the allocator of its last Reset: list A on allocator B takes B's memory. + EXPECT(hr_of(raw(allocator_b, 8)) == S_OK); + EXPECT(hr_of(raw(list_a, 139, word(allocator_b), 0)) == S_OK); + EXPECT(raw(list_a, 148, kUploadMiB, 16) == b1); + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + + // A chunk its allocator has not used for a while goes back; the one in use stays. A's frames now fit in its + // newest chunk, so its first one is idle. + EXPECT(chunk_a1->refs == 1 && chunk_a2->refs == 1); + std::uint64_t kept = 0; + for (int frame = 0; frame < 32; ++frame) { + EXPECT(hr_of(raw(list_a, 139, word(allocator_a), 0)) == S_OK); + const std::uint64_t p = raw(list_a, 148, kUploadMiB, 16); + EXPECT(p && (!kept || p == kept)); + kept = p; + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + EXPECT(hr_of(raw(allocator_a, 8)) == S_OK); + } + EXPECT(chunk_a1->refs == 0 && chunk_a1->calls[9] == 1 && chunk_a2->refs == 1 && kept == word(chunk_a2->mapped)); + EXPECT(s.mock->calls[27] == seen); // no chunk made since A's second one + // A pointer into a chunk that went back is no longer translated: it passes through as any other address. + EXPECT(hr_of(raw(list_a, 139, word(allocator_a), 0)) == S_OK); + EXPECT(hr_of(raw(list_a, 43, 0, a1)) == S_OK && s.real_list[0]->args[39][1] == a1); + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + + // An allocator's chunks go with it, and another allocator's stay. + EXPECT(release(list_b) == 0 && release(allocator_b) == 0); + EXPECT(chunk_b->refs == 0 && chunk_b->calls[9] == 1 && chunk_a2->refs == 1); + EXPECT(release(list_a) == 0 && release(allocator_a) == 0); + EXPECT(chunk_a2->refs == 0); + EXPECT(release(s.device) == 0 && s.mock->refs == 0); + std::printf("%s: upload memory comes back at its own allocator's Reset (not a list's), idle chunks go back, an " + "allocator's chunks go with it\n", g_label); + return 0; +} + +// --upload-rewind-off: LEONIDA_UPLOAD_REWIND=0 (set here, before the device's first upload) keeps one arena that +// only advances, as before the rewind: the 200 frames make 25 chunks, and an allocator's release frees none of them. +int run_upload_rewind_off() { + g_label = "xs_proxy_mock --upload-rewind-off"; + EXPECT(_putenv_s("LEONIDA_UPLOAD_REWIND", "0") == 0); + UploadSetup s; + if (make_upload_setup(s)) return 1; + unsigned moved = 0, made = 0; + if (upload_frames(s.mock, s.list[0], s.allocator[0], moved, made)) return 1; + EXPECT(moved == 199 && made == 25); + Mock* const last_chunk = s.mock->last_child; + EXPECT(last_chunk->kind == Kind::resource && last_chunk->refs == 1); + for (int i = 0; i < 2; ++i) EXPECT(release(s.list[i]) == 0 && release(s.allocator[i]) == 0); + EXPECT(last_chunk->refs == 1); + EXPECT(release(s.device) == 0 && s.mock->refs == 0 && last_chunk->refs == 0); + std::printf("%s: PASS (one arena, never rewound)\n", g_label); + return 0; +} + // ---- 10. SignalX layout detection ------------------------------------------------------------ // A fence at queue slot 25 while the layout is still unknown is itself the newer-layout evidence: a title that // signals only through SignalX never reaches Signal/Wait at 16/17, so an unanswered SignalX used to return @@ -5379,12 +5592,13 @@ int main(int argc, char** argv) { if (std::strcmp(argv[1], "--env-slots-74") == 0) return run_env_slots(true, true); if (std::strcmp(argv[1], "--env-slots-70") == 0) return run_env_slots(true, false, true); if (std::strcmp(argv[1], "--slot133-layout") == 0) return run_slot133_layout_word(); + if (std::strcmp(argv[1], "--upload-rewind-off") == 0) return run_upload_rewind_off(); return run_fault_mode(argv[1]); } if (argc != 1) return 2; if (check_tail(true) || check_host_device_floor() || check_levels() || check_slot48() || check_fence1() || check_fence_completed_value() || check_create_failures() || check_open_shared() || - check_alloc_failures() || check_allocators() || check_xbox_slots() || check_lists() || + check_alloc_failures() || check_allocators() || check_xbox_slots() || check_lists() || check_upload_rewind() || check_signalx_detection() || check_list_tail_names() || check_console_command_list() || check_custom_heap_properties() || check_resource_allocation_info() || check_slot70() || check_slot70_raw_buffer() || From c7d8306916df24072507d88eb985a0b182000d17 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:18:10 +0100 Subject: [PATCH 04/49] d3d12: LEONIDA_SHADOW_GPU=1 alone keeps no released ranges for the console heap pass (RT-SHADOW-GPU-RELEASED-RANGES) With LEONIDA_SHADOW_GPU=1 and LEONIDA_CONSOLE_HEAP_GPU unset, setup_console_heap_gpu makes heap_gpu for the shadows' page copies and turns the alias table's removal list on, but only the pass takes released_ranges and that list (console_heap_gpu_begin), and the pass runs only with LEONIDA_CONSOLE_HEAP_GPU=1. Every arena release (the per-submission geometry upload leases among them), title block destroyed, slot-133 import released and alias range removed added an entry nothing took, for as long as the process ran. The pushes in backing() and title_block_gone now ask heap_pass_enabled() (heap_gpu and LEONIDA_CONSOLE_HEAP_GPU=1), and the alias table records removals only when the pass runs. arena_release called backing() twice for a release since 9f98dcc61. The second call erased nothing more: it only repeated the slot change, the generation bump and the released range. It is gone, so a release is one range for the pass and one slot change. A device that owns its VkDevice (create_vulkan_device_standalone) faulted when released with either variable set: the pass's pipeline and buffers went in ~DeviceState, after the VkDevice. ~Device now clears the context's prelude and releases them first. Test: d3d12_shadow_gpu_releases (new). LEONIDA_SHADOW_GPU=1 alone: 1,024 committed and 16 slot-133 buffers released over 16 submissions leave nothing waiting (2,064 released ranges and 16 removed alias ranges on d44285197). With --console-heap-gpu, 64 releases are 64 ranges (128 before), all taken by the next submission. The accessors are console_heap_gpu_pending (d3d12_com.h) and TitleVaAliases::removals_pending. --- runtime/CMakeLists.txt | 12 ++ runtime/shims/d3d12_com.h | 9 + runtime/shims/d3d12_vulkan_device.cpp | 32 +++- runtime/src/title_va_alias.h | 5 + .../test/d3d12_shadow_gpu_releases_test.cpp | 168 ++++++++++++++++++ 5 files changed, 221 insertions(+), 5 deletions(-) create mode 100644 runtime/test/d3d12_shadow_gpu_releases_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..4515a08f46 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2874,6 +2874,18 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_placed_heap_lifetime PROPERTIES SKIP_RETURN_CODE 77 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # LEONIDA_SHADOW_GPU=1 alone keeps no released arena range or removed alias range for the console heap pass, + # which never runs then; with LEONIDA_CONSOLE_HEAP_GPU=1 an arena release is one range, taken by the next + # submission (RT-SHADOW-GPU-RELEASED-RANGES). The test sets both variables itself. + add_executable(d3d12_shadow_gpu_releases_test test/d3d12_shadow_gpu_releases_test.cpp) + target_link_libraries(d3d12_shadow_gpu_releases_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_shadow_gpu_releases_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_shadow_gpu_releases_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_shadow_gpu_releases COMMAND d3d12_shadow_gpu_releases_test) + add_test(NAME d3d12_console_heap_gpu_releases COMMAND d3d12_shadow_gpu_releases_test --console-heap-gpu) + set_tests_properties(d3d12_shadow_gpu_releases d3d12_console_heap_gpu_releases PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # ClearUnorderedAccessViewUint/Float on buffers and textures, read back through D3D12. add_executable(d3d12_uav_clear_test test/d3d12_uav_clear_test.cpp) target_link_libraries(d3d12_uav_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 2c948ff3d3..6366a5f975 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -347,6 +347,15 @@ struct TitleShadowWatch { std::uint64_t asks = 0, written = 0, faults = 0, watched_bytes = 0, hot_bytes = 0; }; TitleShadowWatch title_shadow_watch(ID3D12Device* device); +// What waits for the console heaps' GPU pass (LEONIDA_CONSOLE_HEAP_GPU, src/console_heap_gpu.h) to drop from its key +// table at the next submission that runs it: the arena ranges `device` released since the last one, and the alias +// ranges removed since (the alias table's list, one for the process). `made`: the device made the pass's object at +// all (LEONIDA_CONSOLE_HEAP_GPU=1 or LEONIDA_SHADOW_GPU=1). For tests. +struct ConsoleHeapGpuPending { + bool made = false; + std::uint64_t released = 0, removed = 0; +}; +ConsoleHeapGpuPending console_heap_gpu_pending(ID3D12Device* device); // True when `device` has VK_KHR_acceleration_structure + VK_KHR_ray_query enabled. bool device_supports_ray_tracing(ID3D12Device* device); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 748d6144a5..8b8ed7ff5a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -4583,7 +4583,7 @@ struct DeviceState { std::lock_guard lock(backing_mutex); backing_generation.fetch_add(1, std::memory_order_relaxed); note_slot_change(leonida::SlotChange::target_gone, address, bytes); - if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); + if (heap_pass_enabled()) released_ranges.emplace_back(address - arena.address, bytes); } void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) { std::lock_guard lock(backing_mutex); @@ -4598,7 +4598,7 @@ struct DeviceState { // The heap slots whose copy names it are fixed again at the next refresh. note_slot_change(leonida::SlotChange::target_gone, address, bytes); // LEONIDA_CONSOLE_HEAP_GPU: the key entries answering into it go at the next refresh. - if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); + if (heap_pass_enabled()) released_ranges.emplace_back(address - arena.address, bytes); } } @@ -4976,11 +4976,10 @@ struct DeviceState { // had must not change them, and a double free must not count the bytes twice. const auto fault = arena.blocks.release(offset, bytes); if (fault != leonida::ArenaBlocks::Fault::outside_arena) { + // A heap copy re-fixes the slots that named a backing that has gone (slot_changes): the range is no view's. backing(arena.address + offset, bytes, offset, false); arena.in_use -= bytes; arena.use_in_use[use] -= bytes; - // A heap copy re-fixes the slots that named a backing that has gone (slot_changes): the range is no view's. - backing(arena.address + offset, bytes, offset, false); } if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) { std::fprintf(stderr, @@ -5795,6 +5794,9 @@ struct DeviceState { std::unique_ptr heap_gpu; std::array gpu_heaps{}; // console_heap_mutex std::vector> released_ranges; // (shader VA, bytes); backing_mutex + // Whether the pass runs: only it takes released_ranges and the alias table's removals (console_heap_gpu_begin). + // LEONIDA_SHADOW_GPU=1 alone makes heap_gpu for the shadows' page copies, and a range kept for it is never taken. + bool heap_pass_enabled() const { return heap_gpu && console_heap_gpu_enabled(); } struct GpuKeyHash { std::size_t operator()(const leonida::ConsoleHeapKeys::Key& k) const { return leonida::ConsoleHeapKeys::hash(k); @@ -6087,7 +6089,8 @@ struct DeviceState { } heap_gpu = std::move(gpu); heap_gpu->set_signed_offsets(signed_vsharp_offsets()); - leonida::title_va_aliases().record_removals(true); + // Only the pass takes what the alias table records (heap_pass_enabled). + if (console_heap_gpu_enabled()) leonida::title_va_aliases().record_removals(true); context->set_prelude([this](VkCommandBuffer cb) { return heap_gpu->record(cb); }, [this](bool submitted, std::uint64_t ticket) { heap_gpu->commit(submitted, ticket); }); gpu_resolver = std::make_unique(); @@ -16046,6 +16049,10 @@ class Device final if (state_.context) { if (state_.gpu_resolver) state_.gpu_resolver->halt(); // it calls into the geometry copies ShadowPages::gpu_copy = nullptr; + // The console heap pass's pipeline and buffers (LEONIDA_CONSOLE_HEAP_GPU, LEONIDA_SHADOW_GPU) are the + // VkDevice's, and a device that owns its VkDevice destroys it below, before ~DeviceState: they go now. + state_.context->set_prelude(nullptr, nullptr); + state_.heap_gpu.reset(); state_.geometry.release(state_); state_.external_windows.release(state_); std::lock_guard upload(state_.title_upload_mutex); @@ -22006,6 +22013,21 @@ TitleShadowWatch title_shadow_watch(ID3D12Device* device) { } return watch; } +ConsoleHeapGpuPending console_heap_gpu_pending(ID3D12Device* device) { + ConsoleHeapGpuPending pending; + if (!device) return pending; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + auto* d = Device::from(real ? real : device); + if (!d) return pending; + auto& state = d->state(); + pending.made = state.heap_gpu != nullptr; + { + std::lock_guard lock(state.backing_mutex); + pending.released = state.released_ranges.size(); + } + pending.removed = leonida::title_va_aliases().removals_pending(); + return pending; +} HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear) { diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 8ed315ecf1..46a37016d4 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -511,6 +511,11 @@ class TitleVaAliases { std::unique_lock lock(mutex_); out.swap(removed_); } + // The removals recorded and not taken yet. For tests. + std::size_t removals_pending() const { + std::shared_lock lock(mutex_); + return removed_.size(); + } void note_translation(Kind kind) { translated_[kind].fetch_add(1, std::memory_order_relaxed); } std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); } std::uint64_t untranslated(Kind kind) const { return untranslated_[kind].load(std::memory_order_relaxed); } diff --git a/runtime/test/d3d12_shadow_gpu_releases_test.cpp b/runtime/test/d3d12_shadow_gpu_releases_test.cpp new file mode 100644 index 0000000000..ea463dd98a --- /dev/null +++ b/runtime/test/d3d12_shadow_gpu_releases_test.cpp @@ -0,0 +1,168 @@ +// LEONIDA_SHADOW_GPU=1 without LEONIDA_CONSOLE_HEAP_GPU (RT-SHADOW-GPU-RELEASED-RANGES): the device makes the +// console heaps' GPU pass object for the shadows' copies alone, and the pass itself never runs, so nothing may keep +// the arena ranges released and the alias ranges removed for it: only the pass takes those lists, at the start of a +// submission that runs it. Before, every arena release added two entries (backing() ran twice for it), a slot-133 +// import added one for its backing and one for its alias range, and both lists grew for as long as the process ran. +// Checked on the Vulkan-backed device: committed buffers and slot-133 buffers made and released, with submissions +// between, leave nothing waiting. With --console-heap-gpu (LEONIDA_CONSOLE_HEAP_GPU=1) the pass still gets one entry +// per arena release, and the next submission takes them all. Both release the device at the end, which owns its +// VkDevice here: the pass's pipeline and buffers were destroyed after it before, a fault in ~ConsoleHeapGpu. No game +// data. LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation. +#include "../shims/d3d12_com.h" + +#include +#include +#include +#include + +namespace { +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + T* operator->() const { return p; } + void reset() { + if (p) p->Release(); + p = nullptr; + } +}; + +D3D12_RESOURCE_DESC buffer(UINT64 bytes) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return desc; +} + +// An empty command list, executed and waited for: what runs before every submission runs (refresh_console_heaps). +struct Submitter { + Ref queue; + Ref allocator; + Ref list; + Ref fence; + HANDLE done = nullptr; + UINT64 value = 0; + ~Submitter() { + if (done) CloseHandle(done); + } + bool init(ID3D12Device* device) { + D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + return done && SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue.p))) && + SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) && + SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p))) && + SUCCEEDED(list->Close()) && + SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))); + } + bool submit() { + ID3D12CommandList* lists[]{list.p}; + queue->ExecuteCommandLists(1, lists); + return SUCCEEDED(queue->Signal(fence.p, ++value)) && SUCCEEDED(fence->SetEventOnCompletion(value, done)) && + WaitForSingleObject(done, 30000) == WAIT_OBJECT_0; + } +}; + +// `count` committed buffers made and released: as many arena releases. +bool churn_committed(ID3D12Device* device, unsigned count) { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC desc = buffer(64 << 10); + for (unsigned i = 0; i < count; ++i) { + Ref made; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&made.p)))) + return false; + } + return true; +} +} // namespace + +int main(int argc, char** argv) { + const bool heap_pass = argc == 2 && std::strcmp(argv[1], "--console-heap-gpu") == 0; + if (argc != 1 && !heap_pass) return 2; + // Both are read once, when the device is made. An empty value removes the variable. + _putenv_s("LEONIDA_SHADOW_GPU", "1"); + _putenv_s("LEONIDA_CONSOLE_HEAP_GPU", heap_pass ? "1" : ""); + Ref device; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))) || !device.p) { + std::printf("SKIP: no Vulkan device\n"); + return 77; // ctest skips + } + if (!rt::d3d12::device_arena_size(device.p) || !rt::d3d12::console_heap_gpu_pending(device.p).made) { + std::printf("SKIP: no GPU address arena, or the console heap pass could not be made on this device\n"); + return 77; + } + Submitter gpu; + if (!gpu.init(device.p) || !gpu.submit()) { + std::printf("FAIL: a queue and an empty command list\n"); + return 1; + } + constexpr unsigned kRounds = 16, kBuffers = 64; + int failures = 0; + + if (heap_pass) { + // The pass runs at every submission: one entry per release (not two), all taken by the next submission. + const auto before = rt::d3d12::console_heap_gpu_pending(device.p); + if (!churn_committed(device.p, kBuffers)) { + std::printf("FAIL: CreateCommittedResource\n"); + return 1; + } + const auto released = rt::d3d12::console_heap_gpu_pending(device.p); + std::printf("LEONIDA_CONSOLE_HEAP_GPU=1: %u buffers released: %llu ranges waiting (%llu before)\n", kBuffers, + static_cast(released.released), + static_cast(before.released)); + if (released.released - before.released != kBuffers) { + std::printf("FAIL: an arena release is not one range for the pass\n"); + ++failures; + } + if (!gpu.submit()) { + std::printf("FAIL: a submission\n"); + return 1; + } + const auto after = rt::d3d12::console_heap_gpu_pending(device.p); + std::printf("after a submission: %llu released ranges, %llu removed alias ranges waiting\n", + static_cast(after.released), static_cast(after.removed)); + if (after.released || after.removed) { + std::printf("FAIL: the pass did not take what was released\n"); + ++failures; + } + if (!failures) std::printf("console heap pass: the released ranges are taken at the next submission\n"); + return failures ? 1 : 0; + } + + // Slot-133 buffers on pages of our own (an import and its alias range each, where the driver imports them). + constexpr SIZE_T kPages = 64 << 10; + void* pages = VirtualAlloc(nullptr, kPages, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!pages) return 1; + unsigned placed = 0; + for (unsigned round = 0; round < kRounds && !failures; ++round) { + if (!churn_committed(device.p, kBuffers)) { + std::printf("FAIL: CreateCommittedResource\n"); + ++failures; + } + Ref title; + if (SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, pages, buffer(kPages), 0xFFFFFFFFu, + IID_PPV_ARGS(&title.p)))) + ++placed; + title.reset(); + if (!gpu.submit()) { + std::printf("FAIL: a submission\n"); + ++failures; + } + } + VirtualFree(pages, 0, MEM_RELEASE); + const auto pending = rt::d3d12::console_heap_gpu_pending(device.p); + std::printf("LEONIDA_SHADOW_GPU=1 alone: %u committed and %u slot-133 buffers released over %u submissions: %llu " + "released ranges and %llu removed alias ranges waiting\n", + kRounds * kBuffers, placed, kRounds, static_cast(pending.released), + static_cast(pending.removed)); + if (pending.released || pending.removed) { + std::printf("FAIL: ranges are kept for a console heap pass that never runs\n"); + ++failures; + } + if (!failures) std::printf("shadow GPU copies: nothing is kept for the console heap pass\n"); + return failures ? 1 : 0; +} From 096bedb6dd830ffdee6a66152204f2d2bbbeb604 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:19:49 +0100 Subject: [PATCH 05/49] d3d12: an idle list-cut spare drops its recording and holds back no retired title window (RT-SPARE-LIST-EPOCHS) Since #2465 a retired title window is freed only once every command list whose recording began before the retirement is gone (src/ command_list_epochs.h). The list proxy's spare real lists never were: restart_recording moves the cut parts and the last real list into the spares closed and not reset, and cut_list reuses the newest spare first. After a recording cut twice or more, later recordings that cut at most once reset only the newest spare, so the others kept their last recording's stamp until the list proxy was released, and every title window retired after it kept its memory as long. The idle spares also kept their commands and the pipeline states, root signatures and BVH scratch those held. A spare is not executed again before a cut resets it: a submission names only the proxy's parts and current list, and the title's Reset ended the recording they made. restart_recording now drops a spare's recording through rt::d3d12::drop_recording: the layer list clears its commands, releases what it held and resets its state, as Reset does, and stays closed with no epoch stamp (CommandList::drop_recording, Stamp::drop). A copy a held batch made earlier keeps its own stamp. A retired window still without a ticket 30 s after its retirement is logged once, with what it waits for, and the title memory report at device release counts the retired windows not freed yet and how many command-list epochs ago the oldest live list began. Tests: xbox_list_cut_spares (new; a Vulkan device and the queue and list proxies, no game data) records a list with three cuts, advances the epoch as a retirement does, then records it eight times with at most one cut. On d44285197 the oldest live recording stays at epoch 1 with the retirement at 2, and the root signature the first recording set keeps 3 references; with the change the oldest is 2 and the references 1. command_list checks CommandList::drop_recording and copies of a dropped list. --- docs/d3d12_vulkan.md | 5 +- docs/d3d12_xs_console_abi.md | 5 + runtime/CMakeLists.txt | 8 ++ runtime/shims/d3d12_com.cpp | 15 ++ runtime/shims/d3d12_com.h | 7 + runtime/shims/d3d12_vulkan_device.cpp | 55 ++++++- runtime/shims/d3d12_xs_device.cpp | 17 ++- runtime/src/command_list.h | 11 ++ runtime/src/command_list_epochs.h | 14 +- runtime/test/command_list_test.cpp | 37 +++++ runtime/test/xbox_list_cut_spares_test.cpp | 160 +++++++++++++++++++++ 11 files changed, 327 insertions(+), 7 deletions(-) create mode 100644 runtime/test/xbox_list_cut_spares_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e843d8debc..1d44fbdc13 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1719,7 +1719,10 @@ The copies: began before the retirement is gone (reset, released, or a held batch's or the async worker's copy of it run), and the submissions recorded by then have completed: a list resolves its root views when they are recorded, so one recorded before the retirement and executed, or executed again, after it still names the window - (`src/command_list_epochs.h`). Until then its copy stays a target of its pages' tracker, refreshed like the others, + (`src/command_list_epochs.h`). A list-value cut's spare drops its recording when it becomes one + ([d3d12_xs_console_abi.md](d3d12_xs_console_abi.md)); a list the title closes and then neither resets nor releases + keeps every window retired after its recording began, and a retired window still waiting after 30 s is logged once. + Until it is freed its copy stays a target of its pages' tracker, refreshed like the others, and what the GPU wrote in it goes back to the title's pages: with its submissions' write-back, and once more when it is freed (a range noted when a list was recorded can be copied back before a held batch has run). A retired copy goes back only on the bytes no live copy over them changed, byte by byte (the window and the buffer that replaced it can diff --git a/docs/d3d12_xs_console_abi.md b/docs/d3d12_xs_console_abi.md index 986acf6802..2418aa380f 100644 --- a/docs/d3d12_xs_console_abi.md +++ b/docs/d3d12_xs_console_abi.md @@ -252,6 +252,11 @@ The runtime's model: state set so far (heaps, root signatures and arguments, pipeline, viewports, scissors, targets, vertex and index buffers, blend factor, stencil reference, predication; what an executed bundle set, and nothing from before a `ClearState`) is set on it again. A cut that would split an open query waits for the query's `EndQuery`. + At the title's next `Reset` the parts' real lists become spares for later cuts, the newest reused first. Nothing + executes a spare again before a cut resets it, so it drops its recording then (`rt::d3d12::drop_recording`): an + idle spare keeps no commands, no pipeline states, root signatures or scratch they held, and no command-list epoch + that would keep a retired title window from being freed (`src/command_list_epochs.h`). `xbox_list_cut_spares` + covers it. Bundles record neither method (`ExecuteBundle` names one real list, so a bundle cannot be cut). - At submission each part's waits are checked: met ones cost nothing; one that a write still in flight will meet becomes a queue `Wait` on that write's fence (the GPU orders the two queues); any other makes the queue `Wait` on diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..32626c5fdc 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3461,6 +3461,14 @@ if(TARGET Vulkan::Headers) target_link_options(xbox_list_value_fallback_test PRIVATE /OPT:NOREF) add_test(NAME xbox_list_value_fallback COMMAND xbox_list_value_fallback_test) set_tests_properties(xbox_list_value_fallback PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + # The spare real lists a list-value cut leaves: an idle one drops its recording, so it holds back no retired title + # window (src/command_list_epochs.h) and holds nothing its recording used. + add_executable(xbox_list_cut_spares_test test/xbox_list_cut_spares_test.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp) + target_link_libraries(xbox_list_cut_spares_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_list_cut_spares_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) + add_test(NAME xbox_list_cut_spares COMMAND xbox_list_cut_spares_test) + set_tests_properties(xbox_list_cut_spares PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) add_executable(d3d12_present_test test/d3d12_present_test.cpp) target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi) target_compile_definitions(d3d12_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4a61ffadbc..c49c382edf 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -227,6 +227,16 @@ class GraphicsCommandList final const std::vector& pinned() const { return held_; } // rt::d3d12::hold_until_reset: an object the recording uses that its caller does not keep (a shim's own scratch). void hold_for_recording(IUnknown* object) { hold(object); } + // rt::d3d12::drop_recording: what Reset lets go of, now, without a new recording; the list stays closed. + bool drop_recording() { + if (!list_.drop_recording()) return false; + calls_.clear(); + tables_.clear(); + directly_indexed_ = false; + release_held(); + reset_state(nullptr); + return true; + } bool needs_all_sampled_views() const { if (directly_indexed_) return true; for (const auto& command : list_.commands()) { @@ -2998,6 +3008,11 @@ bool hold_until_reset(ID3D12GraphicsCommandList* list, IUnknown* object) { return true; } +bool drop_recording(ID3D12GraphicsCommandList* list) { + GraphicsCommandList* l = GraphicsCommandList::from(list); + return l && l->drop_recording(); +} + bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands) { const GraphicsCommandList* l = GraphicsCommandList::from(list); if (!l) return false; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 2c948ff3d3..0c2203ac52 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -672,6 +672,13 @@ bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& // lists or `object` is null. bool hold_until_reset(ID3D12GraphicsCommandList* list, IUnknown* object); +// Drops what a closed `list` recorded, as its next Reset would, without beginning a new recording: for a list its +// owner will not execute again before that Reset (a list-value cut's spare, d3d12_xs_device.cpp restart_recording). +// It then keeps no commands and no reference to what they used (the pipeline states, root signatures and objects +// hold_until_reset gave it), and holds back no retired title window (src/command_list_epochs.h). Executed anyway, it +// replays nothing. False when `list` is not one of this module's command lists or is still recording. +bool drop_recording(ID3D12GraphicsCommandList* list); + // A copy of the commands `list` has recorded so far, for tests of what a bundle puts into its parent. False when // `list` is not one of this module's command lists. bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 748d6144a5..5ff51a7290 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3376,7 +3376,12 @@ struct DeviceState { std::uint64_t start, shader_va, size, ticket, epoch; std::uint8_t* mapped; std::uint64_t lists; // the command-list epoch of the retirement + std::chrono::steady_clock::time_point retired_at; // for the warning in stamp_retired_windows }; + // A retired window still without a ticket this long after its retirement is reported once: a replay that does + // not end, or a command list recorded before the retirement that is closed and never reset or released. + static constexpr std::chrono::seconds kRetiredWindowWait{30}; + std::atomic retired_window_wait_reported{false}; static constexpr std::size_t kWindowAliasRemovals = 4096; // kept before every window is looked at instead std::mutex window_alias_removal_mutex; // a leaf: taken in alias_changed, under the alias table's lock std::vector> window_alias_removals; // (shader VA, bytes) @@ -3488,12 +3493,13 @@ struct DeviceState { std::vector retiring; const std::uint64_t epoch = geometry.execute_epoch(); const std::uint64_t lists = leonida::command_list_epochs::advance(); + const auto now = std::chrono::steady_clock::now(); std::uint64_t bytes = 0; std::erase_if(title_windows, [&](const TitleWindow& window) { if (!is_gone(window.shader_va)) return false; retire_shadow(window.mapped); retiring.push_back({window.start, window.shader_va, window.size, rt::d3d12::GeometryViews::kAfterExecutes, - epoch, window.mapped, lists}); + epoch, window.mapped, lists, now}); title_window_bytes -= window.size; bytes += window.size; return true; @@ -3552,12 +3558,34 @@ struct DeviceState { const std::uint64_t oldest_list = leonida::command_list_epochs::oldest(); const std::uint64_t ticket = context->submitted_retire_ticket(); bool left = false; + const RetiredWindow* longest = nullptr; // the earliest retired of those left without a ticket + std::size_t waiting = 0; + std::uint64_t waiting_bytes = 0; for (RetiredWindow& window : retired_windows) { if (window.ticket != rt::d3d12::GeometryViews::kAfterExecutes) continue; - if (window.epoch < oldest && window.lists <= oldest_list) window.ticket = ticket; - else left = true; + if (window.epoch < oldest && window.lists <= oldest_list) { + window.ticket = ticket; + continue; + } + left = true; + ++waiting; + waiting_bytes += window.size; + if (!longest || window.retired_at < longest->retired_at) longest = &window; } retired_windows_unstamped.store(left, std::memory_order_release); + if (!longest || retired_window_wait_reported.load(std::memory_order_relaxed)) return; + const auto waited = std::chrono::steady_clock::now() - longest->retired_at; + if (waited < kRetiredWindowWait || retired_window_wait_reported.exchange(true, std::memory_order_relaxed)) + return; + const std::uint64_t latest = leonida::command_list_epochs::current(); + std::fprintf(stderr, "[rt] d3d12: a title window retired %lld s ago still waits for %s; %zu retired windows " + "(%llu KiB) wait for a ticket, and the oldest command list alive began %llu command-list " + "epochs ago (logged once)\n", + static_cast(std::chrono::duration_cast(waited).count()), + longest->epoch >= oldest ? "a replay in progress at its retirement" + : "a command list recorded before its retirement", + waiting, static_cast(waiting_bytes >> 10), + static_cast(latest - std::min(oldest_list, latest))); } // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases). // A plain aggregate on purpose: a C++ thread_local with a destructor in gta6rt.exe adds TLS callbacks to the image @@ -4966,6 +4994,27 @@ struct DeviceState { static_cast(pool_span_bytes >> 10), static_cast(geometry_spans), static_cast(pool_spans_retired), static_cast(unbacked_requests)); + // The retired windows whose memory is not freed yet, and of those the ones still without a ticket, which + // wait for a replay in progress at their retirement or for a command list recorded before it + // (stamp_retired_windows); and how many command-list epochs ago the oldest list alive began. + std::lock_guard retired(retired_window_mutex); + std::size_t unstamped = 0; + std::uint64_t retired_bytes = 0, unstamped_bytes = 0; + for (const RetiredWindow& window : retired_windows) { + retired_bytes += window.size; + if (window.ticket != rt::d3d12::GeometryViews::kAfterExecutes) continue; + ++unstamped; + unstamped_bytes += window.size; + } + const std::uint64_t latest = leonida::command_list_epochs::current(); + const std::uint64_t oldest_list = leonida::command_list_epochs::oldest(); + std::fprintf(stderr, + "[rt] d3d12: title memory: %zu retired windows (%llu KiB) not freed yet, %zu of them " + "(%llu KiB) without a ticket; the oldest command list alive began %llu command-list epochs " + "ago\n", + retired_windows.size(), static_cast(retired_bytes >> 10), unstamped, + static_cast(unstamped_bytes >> 10), + static_cast(latest - std::min(oldest_list, latest))); } } diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index c5f12dc050..ac2d8d5a28 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -3287,17 +3287,30 @@ void note_list_state(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::u (void)self, (void)a1, (void)a2, (void)a3, (void)a4; } +// A closed real list of the last recording becomes a spare. Nothing executes it again before a cut resets it: a +// submission names the proxy's parts and `real`, and the title's Reset ended the recording they were. So it drops +// that recording now: an idle spare would otherwise keep its commands and the pipeline states, root signatures and +// scratch they hold, and its command-list epoch would hold back every title window retired after that recording +// began (src/command_list_epochs.h) until a cut reset it, which never comes for a spare past the cuts later +// recordings make (cut_list takes the newest spare first). +void keep_spare(ListProxy* self, ID3D12GraphicsCommandList* list) { +#ifdef LEONIDA_VULKAN_DEVICE + rt::d3d12::drop_recording(list); +#endif + self->spares.push_back(list); +} + // A new recording (Reset): the primary list records again; the other real lists of the last recording are closed and // wait with the spares for later cuts. void restart_recording(ListProxy* self) { for (const ListProxy::Part& part : self->parts) - if (part.list != self->primary) self->spares.push_back(part.list); + if (part.list != self->primary) keep_spare(self, part.list); self->parts.clear(); if (self->real != self->primary) { // A title resets a list it closed; one still open (a D3D12 error, which the real Reset reports) is closed // here so that a later cut can Reset it. if (!self->real_closed) self->real->Close(); - self->spares.push_back(self->real); + keep_spare(self, self->real); self->real = self->primary; } self->pre_writes.clear(); diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 8b79c987e9..bbbf06b38b 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -988,6 +988,17 @@ class CommandList { return true; } + // The recording is dropped and no new one begins, for a closed list its owner will not execute again before its + // next Reset (a list-value cut's spare, d3d12_xs_device.cpp restart_recording): it keeps no commands and no + // stamp, so it holds back no copy the layer retires (command_list_epochs.h). Executed anyway, it replays nothing. + bool drop_recording() { + if (!closed_) return false; + commands_.clear(); + active_.clear(); + stamp_.drop(); + return true; + } + bool closed() const { return closed_; } std::span commands() const { return commands_; } diff --git a/runtime/src/command_list_epochs.h b/runtime/src/command_list_epochs.h index 61c73565db..1df5d16d95 100644 --- a/runtime/src/command_list_epochs.h +++ b/runtime/src/command_list_epochs.h @@ -4,7 +4,8 @@ // retires (a title window, DeviceState::retire_orphan_windows) may still be named by a list recorded before the // retirement and executed, or executed again, after it; a held batch and the async worker keep copies of the lists // too. Each list, and each copy of it, carries the epoch its recording began in (Stamp, a CommandList member): -// whatever was retired at epoch E is named by no list once the oldest live stamp is E or later. +// whatever was retired at epoch E is named by no list once the oldest live stamp is E or later. A list whose recording +// was dropped (CommandList::drop_recording) names nothing and carries no stamp until its next Reset. #include #include #include @@ -24,6 +25,8 @@ inline Registry& registry() { // A new epoch: lists whose recording began before it carry a smaller stamp. inline std::uint64_t advance() { return registry().epoch.fetch_add(1, std::memory_order_acq_rel) + 1; } +// The epoch a recording begun now carries. +inline std::uint64_t current() { return registry().epoch.load(std::memory_order_acquire); } // The oldest stamp alive (UINT64_MAX with no list at all). inline std::uint64_t oldest() { @@ -49,16 +52,25 @@ class Stamp { leave(epoch_); epoch_ = enter(registry().epoch.load(std::memory_order_acquire)); } + // The recording was dropped (CommandList::drop_recording): no stamp until restamp(), and a copy made meanwhile + // has none either. epoch() is 0 then; the epochs begin at 1. + void drop() { + leave(epoch_); + epoch_ = kNone; + } std::uint64_t epoch() const { return epoch_; } private: + static constexpr std::uint64_t kNone = 0; static std::uint64_t enter(std::uint64_t epoch) { + if (epoch == kNone) return kNone; Registry& r = registry(); std::lock_guard lock(r.mutex); r.live.insert(epoch); return epoch; } static void leave(std::uint64_t epoch) { + if (epoch == kNone) return; Registry& r = registry(); std::lock_guard lock(r.mutex); if (const auto it = r.live.find(epoch); it != r.live.end()) r.live.erase(it); diff --git a/runtime/test/command_list_test.cpp b/runtime/test/command_list_test.cpp index ea81503e6e..de57ed91ba 100644 --- a/runtime/test/command_list_test.cpp +++ b/runtime/test/command_list_test.cpp @@ -9,9 +9,46 @@ } \ } while (0) +// Command-list epochs (src/command_list_epochs.h), checked before main records any list. A list closed and never +// reset may be executed again, so it holds back every copy the layer retires after its recording began; one whose +// recording was dropped (drop_recording: its owner does not execute it again before its next Reset) holds back +// nothing, nor does a copy of it, until a Reset begins a new recording. Only a closed list drops its recording. +static int check_epochs() { + using namespace leonida; + namespace epochs = command_list_epochs; + CHECK(epochs::oldest() == UINT64_MAX); // no list yet + { + CommandList idle, busy; + const std::uint64_t first = epochs::oldest(); + CHECK(idle.uav_barrier({0}) && idle.close() && busy.close()); + const std::uint64_t retirement = epochs::advance(); + CHECK(busy.reset() && !busy.drop_recording() && busy.close()); // a list still recording keeps its recording + CHECK(first < retirement && epochs::oldest() == first); // the idle list, closed and never reset + { + const CommandList held = idle; // a held batch's copy, made before the drop + CHECK(idle.drop_recording() && idle.closed() && idle.commands().empty()); + CHECK(held.commands().size() == 1 && epochs::oldest() == first); // the copy still names the recording + } + CHECK(epochs::oldest() == retirement); // only the busy list, reset after the retirement + const std::uint64_t later = epochs::advance(); + CHECK(busy.drop_recording() && epochs::oldest() == UINT64_MAX); + { + const CommandList copy = idle; // copies of a dropped recording name nothing either + CommandList assigned; // a new list's recording begins at once + CHECK(epochs::oldest() == later); + assigned = busy; + CHECK(epochs::oldest() == UINT64_MAX); + } + CHECK(idle.reset() && epochs::oldest() == later); // a new recording counts again, from its Reset + } + CHECK(epochs::oldest() == UINT64_MAX); + return 0; +} + int main() { using namespace leonida; namespace s = d3d12_state; + if (check_epochs()) return 1; CommandList list; TargetView descriptor{12, 1, 2, 3}; ClearColor color{1, 0, 0, 1}; diff --git a/runtime/test/xbox_list_cut_spares_test.cpp b/runtime/test/xbox_list_cut_spares_test.cpp new file mode 100644 index 0000000000..e9f6a86f1e --- /dev/null +++ b/runtime/test/xbox_list_cut_spares_test.cpp @@ -0,0 +1,160 @@ +// The spare real lists a list-value cut leaves behind (d3d12_xs_device.cpp restart_recording), on a Vulkan device +// and the queue and list proxies. No game data. +// A recording cut three times leaves three spare real lists when the title resets its list; later recordings cut at +// most once reuse only the last of them, and the other two stay closed and idle until the list is released. A title +// window the layer retires is freed only once every command list whose recording began before the retirement is gone +// (src/command_list_epochs.h), and a list holds the root signatures and pipeline states its recording set until its +// next Reset. The idle spares must therefore drop their recordings when they become spares: they can never be +// executed again before a cut resets them. Without that, the oldest live recording stays the first one's, and the +// root signature it set stays referenced by the two idle spares. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/command_list_epochs.h" + +#include +#include + +#define CHECK(x) \ + do { \ + if (!(x)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); \ + return 1; \ + } \ + } while (0) + +using namespace d3d12test; +namespace xs = rt::d3d12_xs; +namespace epochs = leonida::command_list_epochs; + +namespace { +using Create = HRESULT(WINAPI *)(void *, const void *, ID3D12CommandAllocator *, ID3D12PipelineState *, const IID *, + void **); +// Console list slots on the newer layout (an undetected one reads the same): wait64(address, comparison, reference, +// flags) and SetComputeRootSignature (PC slot 29). +using WaitFn = std::uint64_t(WINAPI *)(void *, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); +using RootSignatureFn = std::uint64_t(WINAPI *)(void *, std::uint64_t); +constexpr unsigned kConsoleWait64 = 74, kConsoleSetComputeRootSignature = 33; +constexpr std::uint64_t kGreaterEqual = 7; // memory >= reference, in D3D12_COMPARISON_FUNC order + +ULONG references(IUnknown *object) { + object->AddRef(); + return object->Release(); +} +} // namespace + +int main() { + xs::set_list_values_enabled(true); + vktest::Device gpu; + auto status = gpu.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + CHECK(status == vktest::DeviceStatus::ready); + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = gpu.instance_proc; + info.instance = gpu.instance; + info.physical = gpu.physical; + info.device = gpu.device; + info.queue = gpu.queue; + info.queue_family = gpu.family; + info.buffer_device_address = true; + ID3D12Device *inner = nullptr; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + CHECK( + SUCCEEDED(xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(&device.p), true))); + rt::d3d12::set_device_outer(inner, device.p); + { + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + Ref allocator; + CHECK(SUCCEEDED(inner->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + Ref fence; + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + // The work each wait follows: a copy between two buffers. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto desc = buffer_desc(4096); + Ref source, destination; + CHECK(SUCCEEDED(inner->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&source.p)))); + CHECK(SUCCEEDED(inner->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&destination.p)))); + // An empty root signature: the first recording sets it before its first cut, so every cut sets it again on + // the spare that records the next part, which holds it until its next Reset. + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + const auto blob = serialize_root_signature(root_desc); + CHECK(!blob.empty()); + Ref root; + CHECK(SUCCEEDED(inner->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)))); + // What every wait reads: already met, so no submission is held at a gate. + auto *cell = static_cast(VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE)); + CHECK(cell); + *cell = 1; + + // No other command list is alive in this process: the oldest recording is one of the lists below. + CHECK(epochs::oldest() == UINT64_MAX); + std::uint64_t create_desc[4]{}; + Ref list; + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))(device.p, create_desc, allocator.p, nullptr, + &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&list.p)))); + CHECK(xs::is_list_proxy(list.p)); + CHECK(SUCCEEDED(list->Close())); + const auto wait = reinterpret_cast(slot(list.p, kConsoleWait64)); + const auto set_root = reinterpret_cast(slot(list.p, kConsoleSetComputeRootSignature)); + UINT64 submitted = 0; + // One recording, executed and waited for: `cuts` waits for a memory value, each after a copy, and a copy + // after the last. + const auto record = [&](unsigned cuts, bool with_root) { + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return false; + if (with_root) set_root(list.p, reinterpret_cast(root.p)); + for (unsigned i = 0; i < cuts; ++i) { + list->CopyBufferRegion(destination.p, 0, source.p, 0, 256); + wait(list.p, reinterpret_cast(cell), kGreaterEqual, 1, 0); + } + list->CopyBufferRegion(destination.p, 0, source.p, 0, 256); + if (FAILED(list->Close()) || xs::list_proxy_part_count(list.p) != cuts + 1) return false; + ID3D12CommandList *lists[1] = {list.p}; + queue->ExecuteCommandLists(1, lists); + return SUCCEEDED(queue->Signal(fence.p, ++submitted)) && + SUCCEEDED(fence->SetEventOnCompletion(submitted, nullptr)); + }; + + xs::reset_list_value_stats(); + // 1. Three cuts: the list has three spare real lists from the next Reset on, each of which set the root + // signature again (the test's reference, the primary list's and the three spares'). + CHECK(record(3, true)); + const ULONG held_by_cuts = references(root.p); + // 2. A title window retired now is freed only once no list recorded before this point is alive. + const std::uint64_t retirement = epochs::advance(); + // 3. Recordings cut at most once: only the last spare records again; the other two stay idle. + constexpr unsigned kRecordings = 8; + for (unsigned i = 0; i < kRecordings; ++i) CHECK(record(i % 2, false)); + const std::uint64_t oldest = epochs::oldest(); + const ULONG held_after = references(root.p); + const auto stats = xs::list_value_stats(); + std::printf("list cut spares: %llu cuts; after %u recordings cut at most once, the oldest live recording " + "began in epoch %llu (the retirement: %llu); the root signature the three-cut recording set has " + "%lu references (%lu after that recording)\n", + static_cast(stats.cuts), kRecordings, + static_cast(oldest), static_cast(retirement), held_after, + held_by_cuts); + CHECK(stats.cuts == 3 + kRecordings / 2 && stats.cut_failures == 0); + CHECK(held_by_cuts == 5); + // Every recording alive began after the retirement: a window retired there would get its ticket now. + CHECK(oldest != UINT64_MAX && oldest >= retirement); + // Nothing but the test holds the root signature: the idle spares let go of what their recordings used. + CHECK(held_after == 1); + VirtualFree(const_cast(cell), 0, MEM_RELEASE); + } + // The list and its spares are gone: no recording is alive. + CHECK(epochs::oldest() == UINT64_MAX); + CHECK(gpu.validation_errors() == 0); + std::puts("list cut spares: idle spare lists hold back no retired title window and hold no root signature"); + return 0; +} From a1f7aac6bd46da27b19d38bcb2af4294c070febc Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:24:19 +0100 Subject: [PATCH 06/49] d3d12: a title texture destroyed inside the registry leaves the async refresh's indexes too (RT-TITLE-TEXTURE-GONE-RANGES) A slot-133 texture destroyed while its thread holds title_texture_mutex (a slot-70 view overwrote the descriptor that held its last reference, 5f549cf5f) only stops naming its resource, and drain_titles_gone erases the registry entry once the lock is free. With LEONIDA_TEXTURE_REFRESH_ASYNC=1 the entry is also in texture_ranges (index_texture) and, once mapped, in mapped_title_textures, and drain_titles_gone left both. The next refresh pass that saw a title write or a map change over the texture's memory looked the key up with title_textures.at(), and the std::out_of_range ended the process on the refresh worker. The mapped list also kept the TitleTexture alive. drain_titles_gone now erases the range key with the registry entry, as title_texture_gone does outside the registry, and the mapped entry when it has no resource (also when a texture made at the address since replaced the registry entry). The async pass looks a key up with find() and skips one without an entry. The other places an entry leaves the registry already erase its range key or replace it; a texture made for slot-70 views is never in the mapped list. Test: d3d12_mapped_plane_async (d3d12_existing_heap_test --mapped-plane-async) adds check_mapped_plane_gone_in_registry: a mapped slot-133 plane released under the registry's lock, then a write over its pages and a pass of the refresh worker. On d44285197 the process ends with 0xC0000409 (std::out_of_range from the at() in refresh_title_textures, on the worker); now the registry is back to 0 entries, 0 range keys and 0 mapped textures. The accessors are title_texture_registry and release_in_title_registry (d3d12_com.h) and TitleTextureRangeIndex::size. --- runtime/CMakeLists.txt | 3 +- runtime/shims/d3d12_com.h | 12 ++++ runtime/shims/d3d12_vulkan_device.cpp | 43 +++++++++++++- runtime/src/title_texture_refresh.h | 2 + runtime/test/d3d12_existing_heap_test.cpp | 68 +++++++++++++++++++++++ 5 files changed, 125 insertions(+), 3 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..37c09f33a6 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2956,7 +2956,8 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_host_prefix COMMAND d3d12_existing_heap_test --host-prefix-only) set_tests_properties(d3d12_host_prefix PROPERTIES SKIP_RETURN_CODE 77) set_tests_properties(d3d12_existing_heap PROPERTIES SKIP_RETURN_CODE 77) - # LEONIDA_TEXTURE_REFRESH_ASYNC=1 (set by the test itself): a mapped plane's first submission reads its bytes. + # LEONIDA_TEXTURE_REFRESH_ASYNC=1 (set by the test itself): a mapped plane's first submission reads its bytes, and + # a mapped plane destroyed inside the registry leaves nothing for the refresh worker (RT-TITLE-TEXTURE-GONE-RANGES). add_test(NAME d3d12_mapped_plane_async COMMAND d3d12_existing_heap_test --mapped-plane-async) set_tests_properties(d3d12_mapped_plane_async PROPERTIES SKIP_RETURN_CODE 77) # The same with write watching off: the guarded cases only, the concurrent writers among them. diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 2c948ff3d3..010a4d7f68 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -460,6 +460,18 @@ void note_refused_tsharp_for_test(std::uint64_t heap_va, std::size_t offset, // or TitleImage::unknown / TitleImage::not_tsharp. TitleImage test_bind_title_image(ID3D12Device* device, const std::array& words, const char** why = nullptr); +// The title texture registry of `device` (the slot-133 textures and the images made for slot-70 views): its entries, +// the keys of the async refresh's range index and the mapped textures that refresh visits every pass. Read under the +// registry's lock, so a refresh pass on the worker (LEONIDA_TEXTURE_REFRESH_ASYNC=1) is over when it returns. For +// tests. +struct TitleTextureRegistry { + std::uint64_t textures = 0, ranges = 0, mapped = 0; +}; +TitleTextureRegistry title_texture_registry(ID3D12Device* device); +// Releases the caller's reference to `resource` with the registry's lock held on this thread, as a slot-70 view that +// overwrites the descriptor holding a texture's last reference does (title_texture_gone inside the registry), then +// lets drain_titles_gone remove what went. False when `device` is not a Vulkan device of this module. For tests. +bool release_in_title_registry(ID3D12Device* device, ID3D12Resource* resource); // Returns the internal image address registered for a resource in the device's image table. std::uint64_t resource_image_address(ID3D12Resource* resource); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 748d6144a5..dd10cc8dcb 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -14459,8 +14459,15 @@ void DeviceState::drain_titles_gone() { if (!titles_gone_pending.load(std::memory_order_acquire)) return; std::lock_guard lock(title_texture_mutex); for (const auto& [resource, address] : titles_gone) { + // As title_texture_gone outside the registry: LEONIDA_TEXTURE_REFRESH_ASYNC's range index and mapped list + // name the entry too. A texture made at the address since has a resource and keeps all three. const auto it = title_textures.find(address); - if (it != title_textures.end() && !it->second->resource) title_textures.erase(it); + if (it != title_textures.end() && !it->second->resource) { + texture_ranges.erase(address); + title_textures.erase(it); + } + const auto mapped = mapped_title_textures.find(address); + if (mapped != mapped_title_textures.end() && !mapped->second->resource) mapped_title_textures.erase(mapped); } titles_gone.clear(); titles_gone_pending.store(false, std::memory_order_release); @@ -16561,7 +16568,10 @@ class Device final const auto apply = [&](const auto& ranges, bool write) { for (const auto& [from, to] : ranges) state_.texture_ranges.overlapping(from, to, [&](auto key) { - auto& t = *state_.title_textures.at(key); + // A key without an entry is skipped: an exception here would end the process. + const auto it = state_.title_textures.find(key); + if (it == state_.title_textures.end()) return; + auto& t = *it->second; invalidate(t, write, !write); if (t.stale) queue_title_fill(key); }); @@ -23940,6 +23950,35 @@ TitleImage test_bind_title_image(ID3D12Device* device, const std::arraystate(), w, why); } +TitleTextureRegistry title_texture_registry(ID3D12Device* device) { + TitleTextureRegistry registry; + if (!device) return registry; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + Device* d = Device::from(real ? real : device); + if (!d) return registry; + DeviceState& state = d->state(); + std::lock_guard lock(state.title_texture_mutex); + registry.textures = state.title_textures.size(); + registry.ranges = state.texture_ranges.size(); + registry.mapped = state.mapped_title_textures.size(); + return registry; +} + +bool release_in_title_registry(ID3D12Device* device, ID3D12Resource* resource) { + if (!device || !resource) return false; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + Device* d = Device::from(real ? real : device); + if (!d) return false; + DeviceState& state = d->state(); + { + std::lock_guard lock(state.title_texture_mutex); + const InTitleTextures inside; + resource->Release(); + } + state.drain_titles_gone(); + return true; +} + std::uint64_t resource_image_address(ID3D12Resource* resource) { if (!resource) return 0; const Resource* r = Resource::from(resource); diff --git a/runtime/src/title_texture_refresh.h b/runtime/src/title_texture_refresh.h index b39defdcda..a1058faae2 100644 --- a/runtime/src/title_texture_refresh.h +++ b/runtime/src/title_texture_refresh.h @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -39,6 +40,7 @@ class TitleTextureRangeIndex { pages_[shift][{number, key}] = {first, last}; location_[key] = {shift, number}; } + std::size_t size() const { return location_.size(); } // the keys with a range template void overlapping(Address from, Address to, Visit visit) const { if (from >= to) return; diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 1d940a7e48..118ca5f5bf 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1753,6 +1753,73 @@ int check_mapped_plane_first_use(ID3D12Device* device) { return 0; } +// The refresh worker's pass after the texel writes noted so far (LEONIDA_TEXTURE_REFRESH_ASYNC=1): submissions wake the +// worker (a busy one can miss a request) until a pass has taken the writes, and title_texture_registry, read under the +// registry's lock, returns once that pass is over. +int wait_async_refresh(ID3D12Device* device, GpuReader& gpu) { + const char* who = "async texture refresh"; + auto& writes = leonida::title_texel_writes::state(); + ID3D12CommandList* lists[]{gpu.list.p}; + for (int i = 0; i < 2000 && writes.pending.load(std::memory_order_acquire); ++i) { + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, ++gpu.fence_value), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(gpu.fence_value, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + Sleep(1); + } + EXPECT(!writes.pending.load(std::memory_order_acquire)); + rt::d3d12::title_texture_registry(device); + return 0; +} + +// LEONIDA_TEXTURE_REFRESH_ASYNC=1 (the d3d12_mapped_plane_async test): a mapped slot-133 texture destroyed while its +// thread held the registry's lock (a slot-70 view overwrote the descriptor that held its last reference) leaves +// nothing in the async refresh's range index or mapped list once drain_titles_gone removes its entry. A key left in +// the index made the next pass that saw a write over the texture's memory look the gone entry up with +// title_textures.at(), and the std::out_of_range ended the process on the refresh worker +// (RT-TITLE-TEXTURE-GONE-RANGES). +int check_mapped_plane_gone_in_registry(ID3D12Device* device) { + const char* who = "mapped slot-133 plane destroyed inside the registry"; + constexpr UINT width = 256, height = 8, size = width * height; + void* pages = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(pages); + std::memset(pages, 29, size); + GpuReader gpu; + EXPECT(!gpu.init(device, size)); + const auto before = rt::d3d12::title_texture_registry(device); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.SampleDesc.Count = desc.DepthOrArraySize = desc.MipLevels = 1; + leonida::title_xg_layouts::note({UINT(desc.Dimension), UINT(desc.Format), height, 1, 1, width}, 1); + ID3D12Resource* texture = nullptr; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture)), S_OK); + void* mapped = nullptr; + EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + EXPECT(mapped == pages); + const auto registered = rt::d3d12::title_texture_registry(device); + EXPECT(registered.textures == before.textures + 1 && registered.ranges == before.ranges + 1 && + registered.mapped == before.mapped + 1); + // One pass first: the worker's first pass looks at every texture, a later one only at those a write overlaps. + leonida::title_texel_writes::note(pages, size); + EXPECT(!wait_async_refresh(device, gpu)); + EXPECT(rt::d3d12::release_in_title_registry(device, texture)); + // The title writes those pages again, and submits. + std::memset(pages, 41, size); + leonida::title_texel_writes::note(pages, size); + EXPECT(!wait_async_refresh(device, gpu)); + const auto after = rt::d3d12::title_texture_registry(device); + std::printf("%s: %llu textures, %llu range keys, %llu mapped after it went (%llu, %llu, %llu before it)\n", who, + static_cast(after.textures), static_cast(after.ranges), + static_cast(after.mapped), static_cast(before.textures), + static_cast(before.ranges), static_cast(before.mapped)); + EXPECT(after.textures == before.textures && after.ranges == before.ranges && after.mapped == before.mapped); + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + // Several threads write the same watched pages while submissions keep making them read-only again. Two threads that // fault on one page race: the first fault reopens it, a submission can protect it again before the second fault is // handled, and the second write must still be retried, not refused (refused, the process ends: seen natively). After @@ -2423,6 +2490,7 @@ int main(int argc, char** argv) { } if (async_plane) { int result = vk.host_image_copy ? check_mapped_plane_first_use(ours.p) : 0; + result += check_mapped_plane_gone_in_registry(ours.p); auto no_host_copy = info; // the staged upload too no_host_copy.host_image_copy = false; Ref staged; From 51677eacd55d6616c304accb12dfe941f132cf2f Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:25:41 +0100 Subject: [PATCH 07/49] d3d12: a slot-70 image a newer texture covers, or whose pages went, is retired once no view names it (RT-SLOT70-OWNED-RETIRE) The images the layer makes for slot-70 texture views of the title's memory (owned TitleTextures) were retired only when their own address got another description or a slot-133 texture. A title that streams places its textures at ever new addresses of the same memory, so each address named kept its image (in VRAM, then in host-visible memory), its bindless index and its turn in every refresh pass for the device's life. place_title_view now records when a view last named an image, and the refresh pass (retire_idle_owned_images) also retires one once a texture made or registered after that view covers some of its bytes, or once none of its pages has been committed since a title_memory_map change over them, in both cases when no view has named it for LEONIDA_TITLE_IMAGE_IDLE_MS (2000 by default). An image over exactly the same bytes (the other view of a stream pool) is not covered, one never filled does not go with its pages, and two textures over the same bytes that views keep naming both stay. The image is released 3 s later, as before; a later view makes it again with the same T#, so the descriptors the title kept find it once it is filled. LEONIDA_TITLE_IMAGE_RETIRE=0 keeps the images as before. The title textures census line counts the retirements under a newer texture and with their pages gone. d3d12_title_image_retire (d3d12_existing_heap_test --title-image-retire, with LEONIDA_TITLE_IMAGE_IDLE_MS=0): 16 textures named 4 KiB apart in one committed MiB leave one image (64 KiB) and one bindless index, where they left 16 (1024 KiB) and 16; a texture named again after its image was retired reads its texels and its first T# finds it again; decommitted pages and a slot-133 texture over its bytes retire the last image. Tests read the registry through title_images and title_image (d3d12_com.h). --- docs/d3d12_vulkan.md | 14 ++ runtime/CMakeLists.txt | 4 + runtime/README.md | 2 + runtime/shims/d3d12_com.h | 11 ++ runtime/shims/d3d12_vulkan_device.cpp | 161 ++++++++++++++++++++- runtime/src/title_texture_memory.h | 18 +++ runtime/test/d3d12_existing_heap_test.cpp | 168 +++++++++++++++++++++- 7 files changed, 374 insertions(+), 4 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e843d8debc..88955502de 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3557,6 +3557,20 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv complete CPU read. Copies of descriptors written earlier resolve to the fallback until that upload succeeds. `LEONIDA_TITLE_IMAGE_DEFER=0` allocates these textures eagerly. The memory probe reports the live unbound image count and its Vulkan memory requirements in MiB. +- **When a slot-70 image goes**: an image made for slot-70 views was retired only when its address got another + description or a slot-133 texture. A title that streams places its textures at ever new addresses of its memory, + so each address named kept an image, its bindless index (65,536 per dimension) and its turn in every refresh + pass for the device's life. Now an image is also retired once a texture made or registered after its last view + covers some of its bytes, or once none of its pages has been committed (freed, decommitted or unmapped: a + `title_memory_map` change over it, then a look at its pages) for `LEONIDA_TITLE_IMAGE_IDLE_MS` (2000), in both + cases when no slot-70 view has named it for that long. An image over exactly the same bytes (the other view of a + stream pool) does not cover it; one never filled (the view of a texture whose pages have not come) does not go + with its pages; two textures over the same bytes that views keep naming both stay. Its T# keys go at once and the + image 3 s later, as for an address given another description. A later view of the address makes it again: a T# + names the title address, so descriptors the title kept find the new image once it is filled; until then, and for + an address no view names again, they sample the fallback. The title textures census line counts the retirements + under a newer texture and with their pages gone. `LEONIDA_TITLE_IMAGE_RETIRE=0` keeps the images as before. + `d3d12_title_image_retire` covers it without game files. - With `LEONIDA_TITLE_PARTIAL_MIPS=1`, such a texture can be filled before all its pages are readable. The XG layout of a 2D texture of one slice stores its mips from the smallest to the largest, so the mips from `m` on are the first `mip_chain_bytes(layout, m)` bytes from its base (`xg_xs_layout.h`; checked in `xg_xs_test` for tiled, diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..862d26d4fe 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2959,6 +2959,10 @@ if(TARGET Vulkan::Headers) # LEONIDA_TEXTURE_REFRESH_ASYNC=1 (set by the test itself): a mapped plane's first submission reads its bytes. add_test(NAME d3d12_mapped_plane_async COMMAND d3d12_existing_heap_test --mapped-plane-async) set_tests_properties(d3d12_mapped_plane_async PROPERTIES SKIP_RETURN_CODE 77) + # LEONIDA_TITLE_IMAGE_IDLE_MS=0 (set by the test itself): the images made for slot-70 views of textures a streaming + # title places at ever new addresses of the same memory stay at the textures still there. + add_test(NAME d3d12_title_image_retire COMMAND d3d12_existing_heap_test --title-image-retire) + set_tests_properties(d3d12_title_image_retire PROPERTIES SKIP_RETURN_CODE 77) # The same with write watching off: the guarded cases only, the concurrent writers among them. add_test(NAME d3d12_existing_heap_no_write_watch COMMAND d3d12_existing_heap_test) set_tests_properties(d3d12_existing_heap_no_write_watch PROPERTIES SKIP_RETURN_CODE 77 diff --git a/runtime/README.md b/runtime/README.md index cdce0a811d..d0bcda1e36 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -400,6 +400,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TITLE_TEXTURE_FILL_MS` | `8` | Milliseconds one pass over the textures filled from the title's memory may spend filling; a texture already started is finished. `0` removes the time limit and leaves `LEONIDA_TITLE_TEXTURE_FILL_MB` to bound the pass. | | `LEONIDA_TITLE_PARTIAL_MIPS` | unset | `1`: a 2D texture of one slice the title keeps in its own memory, whose larger mips are not readable, is filled from the first mip that is when its last slot-70 view starts there or later. Views that start above keep the fallback until a later fill has their mips. Unset, a texture waits for all its mips. | | `LEONIDA_TITLE_PARTIAL_MIPS_MB` | `2048` | With `LEONIDA_TITLE_PARTIAL_MIPS=1`, the image memory the textures filled in part may hold, in MiB: each has memory for all its mips. A texture past it keeps the fallback. | +| `LEONIDA_TITLE_IMAGE_RETIRE` | on | An image the layer made for device slot 70 views of a texture in the title's memory is retired, with its bindless index, once a texture made or placed (slot 133) after its last view covers some of its bytes, or once none of its pages has been committed for `LEONIDA_TITLE_IMAGE_IDLE_MS`, and no slot 70 view has named it for that long. A title that streams places its textures at ever new addresses, and each such image stayed for the device's life. A later view of the address makes the image again, with the same T#. The title textures census line counts the retirements by reason. `0` keeps an image until its address gets another description or a slot-133 texture, as before. ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md), "When a slot-70 image goes") | +| `LEONIDA_TITLE_IMAGE_IDLE_MS` | `2000` | With `LEONIDA_TITLE_IMAGE_RETIRE` on: how long, in milliseconds, an image a newer texture covers must have gone without a slot 70 view, and one whose pages went must have stayed without them, before it is retired. `0` retires it at the next submission. | | `LEONIDA_MAP_READBACK` | unset | `1` writes the GPU's texels of a small render or unordered-access target the title placed into the title's pages when the title maps it, so a CPU read of the target sees what the GPU rendered (the title reads its exposure statistics that way). Only a single-row, single-mip, single-layer, single-sample 2D target of at most 4 KiB a row; the copy waits for the GPU's work already submitted, and a page that is not writable is left as it is. Unset, the title reads its own pages, which the GPU never writes. | | `LEONIDA_SLOT133_IMPORT` | on | *Diagnostic.* `0` imports no title-placed buffer (device slot 133) as host memory: each takes the shadow-buffer fallback, so no GPU store can reach the title's memory through an import. | | `LEONIDA_ARENA_NULL_MB` | `0` | `n` (MiB) keeps the first `n` MiB of the descriptor arena, at `heap_base + 0`, zeroed and never allocated, and moves the zero page and the quad indices above it. A translated shader whose address arithmetic starts from a null base then reads or writes there instead of in a title buffer or the shared zero page. Ignored when it would take half of the arena or more; the device logs the region it made. | diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 2c948ff3d3..fa405c0538 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -347,6 +347,17 @@ struct TitleShadowWatch { std::uint64_t asks = 0, written = 0, faults = 0, watched_bytes = 0, hot_bytes = 0; }; TitleShadowWatch title_shadow_watch(ID3D12Device* device); +// The device's registry of textures in the title's own memory now (write_placed_texture_view): the images it made for +// slot-70 texture views and their image memory, the slot-133 textures in it, the made images retired since the device +// was created (of them, those a newer texture over their bytes retired and those whose pages went), and how many +// retired images still wait for the GPU before their memory is freed. For tests. +struct TitleImages { + std::uint64_t owned = 0, owned_bytes = 0, slot133 = 0, retired = 0, superseded = 0, gone = 0, waiting = 0; +}; +TitleImages title_images(ID3D12Device* device); +// The image made for slot-70 texture views at `address`, with a reference added for the caller; null when the +// registry holds none there. For tests. +ID3D12Resource* title_image(ID3D12Device* device, std::uint64_t address); // True when `device` has VK_KHR_acceleration_structure + VK_KHR_ray_query enabled. bool device_supports_ray_tracing(ID3D12Device* device); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 748d6144a5..facb93fe81 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -14327,6 +14327,12 @@ struct TitleTexture { device_local = (r->memory_flags() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; } bool owned = false; // made here for slot-70 views (a reference is held); else slot 133's + // Owned, for its retirement (Device::retire_idle_owned_images): when a slot-70 view last named it, whether a + // texture made or registered since then covers some of its bytes, and since when no page of it has been committed + // (time_point{}: some were at the last look after a map change, or a view has named it since). + std::chrono::steady_clock::time_point named{}; + bool superseded = false; + std::chrono::steady_clock::time_point gone_since{}; bool attachment_4k = false; // slot 133: 3840x2160 color or depth attachment bool gpu_written = false; // render target, depth or unordered access: never filled bool mapped = false; // a slot-133 texture the title mapped: checked before submissions @@ -16370,6 +16376,12 @@ class Device final state_.index_texture(*entry); slot = std::move(entry); ++title_stats_.registered; + if (retire_owned_images()) { + forget_owned_range(address); + // A texture the GPU writes has no layout here: what it covers is not known. + if (slot->layout_known && !slot->gpu_written) + supersede_owned_images(address, slot->cpu, slot->layout.layout.size); + } } } @@ -16533,6 +16545,11 @@ class Device final leonida::merge_title_writes(title_map_changes_); stats.map_ranges += title_map_changes_.size(); stats.map_all += map_all; + // The owned images over these changes may have lost their pages (retire_idle_owned_images looks). Changes the + // journal lost are not looked for: such an image goes with the next change over it or a texture over it. + if (retire_owned_images()) + for (const auto& [from, to] : title_map_changes_) + owned_ranges_.overlapping(from, to, [&](std::uint64_t key) { retire_candidates_[key] = true; }); if (!written.empty() || overflow || map_all || !title_map_changes_.empty()) { stats.written_ranges += written.size(); leonida::merge_title_writes(written); @@ -16639,6 +16656,7 @@ class Device final stats.hashed += checked; stats.filled_bytes += filled; stats.max_pass_bytes = std::max(stats.max_pass_bytes, filled); + if (!retire_candidates_.empty()) retire_idle_owned_images(now); std::vector release; std::erase_if(retired_title_textures_, [&](const auto& r) { if (now - r.first < std::chrono::seconds(3)) return false; // descriptors may still be in flight @@ -16667,6 +16685,33 @@ class Device final for (Resource* r : release) r->Release(); } + // For tests (rt::d3d12::title_images, title_image). + TitleImages title_images() { + std::lock_guard lock(state_.title_texture_mutex); + TitleImages out; + for (const auto& [address, t] : state_.title_textures) { + if (!t->resource) continue; + if (!t->owned) { + ++out.slot133; + continue; + } + ++out.owned; + out.owned_bytes += t->resource->image_backing_bytes(); + } + out.retired = title_stats_.retired; + out.superseded = title_stats_.retired_superseded; + out.gone = title_stats_.retired_gone; + out.waiting = retired_title_textures_.size(); + return out; + } + ID3D12Resource* title_image(std::uint64_t address) { + std::lock_guard lock(state_.title_texture_mutex); + const auto it = state_.title_textures.find(address); + if (it == state_.title_textures.end() || !it->second->owned || !it->second->resource) return nullptr; + it->second->resource->AddRef(); + return it->second->resource; + } + private: struct TitleTextureStats { std::uint64_t mapped_checks = 0, mapped_changed = 0, mapped_fills = 0; @@ -16675,6 +16720,8 @@ class Device final std::map refused; // why a view is a null view -> views std::uint64_t views = 0, null_views = 0, of_slot133 = 0, of_cache = 0, made = 0, retired = 0, registered = 0, refusals = 0, written_ranges = 0, unmaps = 0, unreadable = 0, pending_views = 0; + // Of the retired: under a newer texture, with their pages gone (retire_idle_owned_images). + std::uint64_t retired_superseded = 0, retired_gone = 0; std::uint64_t fills = 0, fill_bytes = 0, fill_failures = 0; // Fills of some mips only; textures whose first fill was one; those that got larger mips later; first fills // refused by LEONIDA_TITLE_PARTIAL_MIPS_MB. @@ -16953,6 +17000,10 @@ class Device final VkDeviceSize retired_backing_ = 0; VkDeviceSize title_partial_bytes_ = 0; // likewise: image memory of the textures filled in part, as of this pass std::vector> retired_title_textures_; // likewise + // LEONIDA_TITLE_IMAGE_RETIRE, likewise: the owned images by the CPU bytes they are filled from, and those that may + // be retired (a newer texture covers them, or their pages may have gone: true until a pass has looked at them). + leonida::TitleTextureRangeIndex owned_ranges_; + std::map retire_candidates_; std::vector title_tiled_, title_linear_; // scratch, under title_texture_mutex std::vector title_columns_; @@ -17064,10 +17115,15 @@ class Device final }(); retire_title_texture(*t); state_.texture_ranges.erase(address); + forget_owned_range(address); textures.erase(address); t = make_title_texture(d, words, srv, address, view_mip, same_shape ? formats : std::vector{}); } else if (t) { ++title_stats_.of_cache; + // Named again: in use, whatever covers its bytes now, and a view of a texture whose pages may come back. + t->named = std::chrono::steady_clock::now(); + t->superseded = false; + t->gone_since = {}; if (t->view_mip != view_mip) { t->view_mip = view_mip; if (!t->fills) t->memory.retry(); // what is readable may do for this view @@ -17170,8 +17226,13 @@ class Device final } ++title_stats_.made; TitleTexture* t = entry.get(); + t->named = std::chrono::steady_clock::now(); state_.index_texture(*entry); state_.title_textures[address] = std::move(entry); + if (retire_owned_images()) { + owned_ranges_.set(address, t->cpu, t->layout.layout.size); + supersede_owned_images(address, t->cpu, t->layout.layout.size); + } if (title_fill_async() && readable) queue_title_fill(address); return t; } @@ -17187,6 +17248,91 @@ class Device final ++title_stats_.retired; } + // LEONIDA_TITLE_IMAGE_RETIRE (on by default; 0: as before). An image made for slot-70 views was retired only when + // its own address got another description or a slot-133 texture, and a title that streams places its textures at + // ever new addresses: each kept its image (in VRAM, then in system memory), its bindless index and its turn in the + // refresh passes for the device's life. Now one is also retired once a texture made or registered after the last + // view of it covers some of its bytes, or once no page of it has been committed for a while, when no slot-70 view + // has named it for LEONIDA_TITLE_IMAGE_IDLE_MS (2000 by default): the bytes now hold another texture, or nothing, + // as they would for its T# on the console. Two textures over the same bytes that views keep naming both stay. + // A view of a retired image's address makes it again (place_title_view): its T# names the title address + // (Resource::place_at_title_address), so the copies of its descriptors the title kept find the new image once it + // is filled. Until then, and for a T# whose address no view names again, a shader samples the fallback. + static bool retire_owned_images() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_TITLE_IMAGE_RETIRE"); + return !v || std::strcmp(v, "0"); + }(); + return on; + } + static std::chrono::milliseconds owned_image_idle() { + static const std::chrono::milliseconds idle([] { + const char* v = std::getenv("LEONIDA_TITLE_IMAGE_IDLE_MS"); + return v && *v ? std::strtoll(v, nullptr, 10) : 2000ll; + }()); + return idle; + } + + // A texture at `key` now holds the title's bytes [cpu, cpu + size): the owned images at other keys over some of + // them are superseded. One over exactly these bytes is the same texture named through the other view of a + // stream pool (title_gpu_views::other_view), or the same bytes in another shape, and is left alone. + void supersede_owned_images(std::uint64_t key, std::uint64_t cpu, std::uint64_t size) { + if (!size) return; + owned_ranges_.overlapping(cpu, cpu + size, [&](std::uint64_t other) { + const auto it = state_.title_textures.find(other); + if (other == key || it == state_.title_textures.end() || !it->second->owned || !it->second->resource) + return; + TitleTexture& t = *it->second; + if (t.cpu == cpu && t.layout.layout.size == size) return; + t.superseded = true; + retire_candidates_.try_emplace(other, false); + }); + } + + // The registry no longer holds an owned image at `key` (retired, or replaced by another texture). + void forget_owned_range(std::uint64_t key) { + owned_ranges_.erase(key); + retire_candidates_.erase(key); + } + + // Once a pass, after its visits: the candidates of LEONIDA_TITLE_IMAGE_RETIRE. One over a map change since the + // last pass is looked at first (a filled image none of whose pages is committed has gone; an image never filled + // is the view of a texture whose pages have not come yet, and stays). A superseded image goes once no view has + // named it for the idle time, one whose pages went once they have been gone that long; the others stay + // candidates. Its Release waits as every retired image's does (retired_title_textures_). + void retire_idle_owned_images(std::chrono::steady_clock::time_point now) { + const auto idle = owned_image_idle(); + for (auto it = retire_candidates_.begin(); it != retire_candidates_.end();) { + const std::uint64_t key = it->first; + const auto entry = state_.title_textures.find(key); + TitleTexture* t = entry == state_.title_textures.end() || !entry->second->owned || !entry->second->resource + ? nullptr + : entry->second.get(); + if (t && std::exchange(it->second, false)) { + if (!t->fills || leonida::texture_memory_committed(std::uintptr_t(t->cpu), t->layout.layout.size)) + t->gone_since = {}; + else if (t->gone_since == std::chrono::steady_clock::time_point{}) + t->gone_since = now; + } + const bool gone = t && t->gone_since != std::chrono::steady_clock::time_point{}; + if (!t || (!t->superseded && !gone)) { + it = retire_candidates_.erase(it); + continue; + } + const bool covered = t->superseded && now - t->named >= idle; + if (!covered && !(gone && now - t->gone_since >= idle)) { + ++it; + continue; + } + ++(covered ? title_stats_.retired_superseded : title_stats_.retired_gone); + retire_title_texture(*t); + it = retire_candidates_.erase(it); + owned_ranges_.erase(key); + state_.texture_ranges.erase(key); + state_.title_textures.erase(entry); + } + } + // LEONIDA_TITLE_PARTIAL_MIPS=1 (off by default). A slot-70 2D texture whose larger mips are not readable is filled from the // first mip that is, with every smaller one, when its last view starts there or later. The T#s of views that start // above stay on the fallback (PendingImage::first_mip), so no shader samples a mip that was not filled. Larger @@ -17486,14 +17632,15 @@ class Device final double(s.staged_ns) / 1e9, double(state_.title_upload.capacity()) / 1048576.0); std::fprintf(stderr, "[rt] d3d12: title textures (%s): %llu slot-70 texture views (%zu kinds), %llu of slot-133 textures, " - "%llu of images made for them (%llu made, %llu over memory not readable yet, %llu retired), %llu " - "null views; registry %zu images " + "%llu of images made for them (%llu made, %llu over memory not readable yet, %llu retired: %llu " + "under a newer texture, %llu with their pages gone), %llu null views; registry %zu images " "(%zu made, %zu slot 133 of %llu registered, %zu mapped, %zu filled); %llu fills %.1f MiB, %llu " "failed\n", when, static_cast(s.views), s.asked.size(), static_cast(s.of_slot133), static_cast(s.of_cache), static_cast(s.made), static_cast(s.unreadable), - static_cast(s.retired), + static_cast(s.retired), static_cast(s.retired_superseded), + static_cast(s.retired_gone), static_cast(s.null_views), state_.title_textures.size(), owned, slot133, static_cast(s.registered), mapped, filled, static_cast(s.fills), double(s.fill_bytes) / 1048576.0, @@ -21984,6 +22131,14 @@ TitleWindows title_windows(ID3D12Device* device) { windows.waiting = state.retired_windows.size(); return windows; } +TitleImages title_images(ID3D12Device* device) { + auto* d = Device::from(device); + return d ? d->title_images() : TitleImages{}; +} +ID3D12Resource* title_image(ID3D12Device* device, std::uint64_t address) { + auto* d = Device::from(device); + return d ? d->title_image(address) : nullptr; +} std::uint64_t title_shadow_trackers(ID3D12Device* device) { auto* d = Device::from(device); if (!d) return 0; diff --git a/runtime/src/title_texture_memory.h b/runtime/src/title_texture_memory.h index d2c512cecc..ee106f4297 100644 --- a/runtime/src/title_texture_memory.h +++ b/runtime/src/title_texture_memory.h @@ -89,4 +89,22 @@ inline bool texture_memory_readable(std::uintptr_t base, std::uint64_t size, Tex return size && texture_memory_readable_bytes(base, size, commit) == size; } +// Whether any page of [base, base + size) is committed, whatever its protection. False when the title has freed, +// decommitted or unmapped every page of the footprint: a texture there has gone whole, where one whose larger mips +// went (texture_memory_readable_bytes stops at the first missing page) still has its smaller ones. A page the layer +// write-protects to watch it stays committed. +inline bool texture_memory_committed(std::uintptr_t base, std::uint64_t size) { + if (!base || !size || size > (std::numeric_limits::max)() - base) return false; + const auto end = base + size; + for (auto at = base; at < end;) { + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region))) return false; + if (region.State == MEM_COMMIT) return true; + const auto next = reinterpret_cast(region.BaseAddress) + region.RegionSize; + if (next <= at) return false; + at = next; + } + return false; +} + } // namespace leonida diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 1d940a7e48..bb271fff90 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1658,6 +1658,160 @@ int check_placed_view_map_changes(ID3D12Device* device) { return 0; } +// The images the layer makes for slot-70 texture views of the title's memory have a lifetime (the +// d3d12_title_image_retire test, with LEONIDA_TITLE_IMAGE_IDLE_MS=0). A streaming title places its textures at ever new +// addresses of the same memory: here 16 textures of 64 KiB, each 4 KiB after the one before, in one committed range. +// An image a newer texture covers, or whose pages have all gone, and that no view named since, is retired at the next +// submission; before, each address named kept its image, and its bindless index, for the device's life. An image a +// view names again after a newer texture covered it is kept (two views of the same bytes in use). A texture named +// again after its image was retired gets a new one with its texels, and the T# its first view wrote finds it again. +// A slot-133 texture the title places over an image's bytes retires it as a newer slot-70 texture does. +int check_title_image_retirement(ID3D12Device* device) { + const char* who = "slot-70 image retirement"; + if (!rt::d3d12::bindless_set_layout(device)) return 0; + constexpr UINT width = 256, height = 256; + constexpr SIZE_T texture_bytes = width * height, step = 4096, bytes = 1 << 20; + constexpr unsigned count = 16; + auto* pages = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(pages); + GpuReader gpu; + EXPECT(!gpu.init(device, 4096)); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = desc.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + const auto va = [&](SIZE_T offset) { return reinterpret_cast(pages + offset); }; + // The title writes a texture's bytes, then names it. + const auto name = [&](SIZE_T offset, unsigned seed, leonida::gfx10::ImageWords& slot) { + for (SIZE_T i = 0; i < texture_bytes; ++i) pages[offset + i] = pattern_byte(i, seed); + std::array resource{}; + std::array words{}; + std::memcpy(resource.data(), &desc, sizeof(desc)); + std::memcpy(words.data(), &srv, sizeof(srv)); + return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), va(offset), + {reinterpret_cast(slot.data())}); + }; + const auto index = [&](const leonida::gfx10::ImageWords& descriptor) { + std::uint32_t key[8]; + std::memcpy(key, descriptor.data(), sizeof(key)); + return rt::d3d12::bindless_hash_lookup(device, key); + }; + // A submission: the registry's refresh pass runs before it. + ID3D12CommandList* lists[]{gpu.list.p}; + const auto submit = [&] { + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, ++gpu.fence_value), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(gpu.fence_value, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + return 0; + }; + // The image at `offset` holds the texels of `seed`. + const auto texels = [&](SIZE_T offset, unsigned seed) { + Ref image; + image.p = rt::d3d12::title_image(device, va(offset)); + EXPECT(image.p); + std::vector got(texture_bytes); + EXPECT_HR(image->ReadFromSubresource(got.data(), width, UINT(texture_bytes), 0, nullptr), S_OK); + for (SIZE_T i = 0; i < texture_bytes; ++i) + if (got[i] != pattern_byte(i, seed)) { + std::fprintf(stderr, "%s: texel %zu of the image at +0x%zx is %u, expected %u\n", who, i, offset, + unsigned(got[i]), unsigned(pattern_byte(i, seed))); + return 1; + } + return 0; + }; + const auto start = rt::d3d12::title_images(device); + const auto room = rt::d3d12::bindless_room(device).images_2d; + const auto owned = [&] { return rt::d3d12::title_images(device).owned - start.owned; }; + + // 1. Sixteen textures over the same memory, one after the other: one image is left, the last one. + leonida::gfx10::ImageWords first{}, slot{}; + for (unsigned i = 0; i < count; ++i) { + EXPECT(name(i * step, i, i ? slot : first)); + if (!i) EXPECT(index(first)); // published at its fill... + EXPECT(!submit()); + } + EXPECT(!submit() && !submit()); + const auto streamed = rt::d3d12::title_images(device); + std::printf("%s: %u textures named over the same memory: %llu images (%llu KiB), %llu retired, %llu of them under " + "a newer texture; %u bindless 2D indices taken\n", + who, count, static_cast(streamed.owned - start.owned), + static_cast((streamed.owned_bytes - start.owned_bytes) >> 10), + static_cast(streamed.retired - start.retired), + static_cast(streamed.superseded - start.superseded), + room - rt::d3d12::bindless_room(device).images_2d); + EXPECT(streamed.owned - start.owned == 1); + EXPECT(streamed.owned_bytes - start.owned_bytes <= 2 * texture_bytes); + EXPECT(streamed.superseded - start.superseded == count - 1); + EXPECT(room - rt::d3d12::bindless_room(device).images_2d <= 1); + EXPECT(!index(first)); // ...so its T# finds nothing + EXPECT(!texels((count - 1) * step, count - 1)); + + // 2. The first texture named again: a new image with its texels, which the T# of its first view finds again. + EXPECT(name(0, 0, slot)); + EXPECT(!submit()); + EXPECT(owned() == 1 && !texels(0, 0)); + EXPECT(slot == first && index(first)); + + // 3. A view names it again after a newer texture covered half of it: both stay, at every submission. + leonida::gfx10::ImageWords newer{}; + EXPECT(name(8 * step, 8, newer)); + EXPECT(name(0, 0, slot)); + EXPECT(!submit() && !submit()); + EXPECT(owned() == 2 && index(first) && index(newer)); + + // 4. A third texture over both, named alone: it is the one image left. + EXPECT(name(12 * step, 12, slot)); + EXPECT(!submit()); + EXPECT(owned() == 1 && !index(first) && !index(newer) && index(slot) && !texels(12 * step, 12)); + + // 5. Its pages decommitted: no image is left. + EXPECT(VirtualFree(pages, bytes, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(pages, bytes); + EXPECT(!submit()); + EXPECT(owned() == 0 && rt::d3d12::title_images(device).gone - start.gone == 1); + + // 6. The pages back, and a texture named there again: it has an image and its texels. + EXPECT(VirtualAlloc(pages, bytes, MEM_COMMIT, PAGE_READWRITE) == pages); + leonida::title_memory_map::changed(pages, bytes); + EXPECT(name(0, 0, slot)); + EXPECT(!submit()); + EXPECT(owned() == 1 && !texels(0, 0) && index(first)); + + // 7. A slot-133 texture the title places over its bytes retires it too. + { + Ref placed; + D3D12_RESOURCE_DESC placed_desc = desc; + placed_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages + 65536 - 2 * step, placed_desc, 0, + IID_PPV_ARGS(&placed.p)), S_OK); + EXPECT(!submit()); + EXPECT(owned() == 0 && !index(first)); + } + + // The retired images' memory is freed once no submission can still read them (3 s after their retirement). + Sleep(3100); + EXPECT(!submit()); + const auto end = rt::d3d12::title_images(device); + std::printf("%s: %llu images retired in all (%llu under a newer texture, %llu with their pages gone), %llu still " + "waiting for the GPU\n", + who, static_cast(end.retired - start.retired), + static_cast(end.superseded - start.superseded), + static_cast(end.gone - start.gone), static_cast(end.waiting)); + EXPECT(end.waiting == 0 && end.owned == start.owned); + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + // A persistent Map can become readable without notifying xmem or calling Map a second time. int check_mapped_plane(ID3D12Device* device) { const char* who = "persistent slot-133 plane"; @@ -2392,8 +2546,11 @@ void print_cases(const std::vector& cases, const char* who) { int main(int argc, char** argv) { const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0; const bool async_plane = argc == 2 && std::strcmp(argv[1], "--mapped-plane-async") == 0; - if (argc != 1 && !prefix_only && !async_plane) return 2; + const bool image_retire = argc == 2 && std::strcmp(argv[1], "--title-image-retire") == 0; + if (argc != 1 && !prefix_only && !async_plane && !image_retire) return 2; if (async_plane) _putenv_s("LEONIDA_TEXTURE_REFRESH_ASYNC", "1"); // read once, at the device's first refresh + // An image no view named since a newer texture covered it, or since its pages went, goes at the next pass. + if (image_retire) _putenv_s("LEONIDA_TITLE_IMAGE_IDLE_MS", "0"); _putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0"); _putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0"); vktest::Device vk; @@ -2430,6 +2587,15 @@ int main(int argc, char** argv) { result += check_mapped_plane_first_use(staged.p); return result || vk.validation_errors() ? 1 : 0; } + if (image_retire) { + int result = check_title_image_retirement(ours.p); + auto no_host_copy = info; // the staged upload too + no_host_copy.host_image_copy = false; + Ref staged; + if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; + result += check_title_image_retirement(staged.p); + return result || vk.validation_errors() ? 1 : 0; + } failures += check(ours.p, "vulkan"); const std::vector vulkan_cases = open_cases(ours.p); print_cases(vulkan_cases, "vulkan"); From e64222c1c9959e25aa720358188d00c11d7cba15 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:39:07 +0100 Subject: [PATCH 08/49] d3d12: a slot-record bucket goes with the last half it holds (RT-SLOT-RECORDS-BUCKETS) The two indexes of src/console_heap_slot_records.h hold each V# half of a console resource heap under (span class, granule), one unordered_map per class. A half that moved or was cleared left a stale entry behind, and nothing erased a bucket: push() cleaned only a bucket that was pushed again until it held 32 keys, find() skipped stale entries, and only reset(), at heap creation, emptied the maps. The main resource heap lives as long as the session, and fix_vsharp records as waiting any non-image word with w[2] != 0, so data the title keeps in a slot made a new bucket whenever it changed. The bucket count was every (class, granule) the session had written, not the live slots: two halves moved 200,001 times held 600,003 buckets, 60.4 MiB of private bytes (measured with a scratch program), with nothing recorded. A bucket now counts the halves it holds. set() works out, per index, the bucket a half leaves and the one it enters, and the last half to leave a bucket erases it with its stale entries. The buckets held are at most twice the halves recorded. Lookups name the same slots: they skipped those entries already. The heap's slot-record log line gives the bucket count after the halves recorded. console_heap_slot_records_test: a new case moves two halves 200,001 times and expects at most 4 buckets while they live and none once both slots are cleared (on main: 600,003 both times). Every apply() of the model now also compares touched() with a walk of every recorded half, and the random case bounds the buckets by twice the halves recorded after each round; both checks hold on main too. --- docs/d3d12_vulkan.md | 8 +- runtime/shims/d3d12_vulkan_device.cpp | 5 +- runtime/src/console_heap_slot_records.h | 56 +++++++++--- .../test/console_heap_slot_records_test.cpp | 91 ++++++++++++++++++- 4 files changed, 136 insertions(+), 24 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e843d8debc..6a3fe902b1 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2146,9 +2146,11 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all (a backing, an alias range, title memory) go on an unbounded per-device list; at the next submission each heap fixes again exactly the slots whose records a change touches: a release or removal every half naming it, an addition the waiting halves over it. Nothing walks the heap or reads the copy for this. A zeroed range, a slot - the title rewrote and a heap destroyed drop their records. `console_heap_slot_records_test` checks that a release - of a buffer 10 of 60,010 slots name looks at those 10, and compares the copy with a full re-resolution through - random writes, releases, additions and alias changes. + the title rewrote and a heap destroyed drop their records, and an index bucket goes with the last half it holds: + the indexes hold the granules of the live halves, not every granule the session wrote a V# into. + `console_heap_slot_records_test` checks that a release of a buffer 10 of 60,010 slots name looks at those 10, + compares the copy with a full re-resolution and each lookup with a walk of every half through random writes, + releases, additions and alias changes, and that two halves moved 200,001 times hold 3 buckets (600,003 before). Console resource heap copies and shader-visible CBV/SRV/UAV heaps with at least 65,536 slots request 64 MiB of zeroed padding after their last descriptor. `LEONIDA_HEAP_GUARD_MB` sets the padding in MiB (0 disables it). When arena space is tight, allocation can fall back to the heap alone. Only indices diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 748d6144a5..4782e9cc74 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -5482,10 +5482,11 @@ struct DeviceState { // entries looked at to find their slots, and the slots fixed again (apply_slot_changes). std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx slot records per submission: %.1f changes, " - "%.1f slots looked at, %.1f fixed again, %.3f ms; %zu V# halves recorded\n", + "%.1f slots looked at, %.1f fixed again, %.3f ms; %zu V# halves recorded, %zu index " + "buckets\n", static_cast(heap->console_va), double(heap->record_changes) / count, double(heap->record_looked) / count, double(heap->record_refixed) / count, - heap->record_ms / count, heap->records.recorded()); + heap->record_ms / count, heap->records.recorded(), heap->records.buckets()); for (auto& n : heap->changed) n = 0; heap->vsharp_halves = heap->vsharp_repeats = 0; heap->record_changes = heap->record_looked = heap->record_refixed = 0; diff --git a/runtime/src/console_heap_slot_records.h b/runtime/src/console_heap_slot_records.h index 4ab3c3b9d9..476c544ccc 100644 --- a/runtime/src/console_heap_slot_records.h +++ b/runtime/src/console_heap_slot_records.h @@ -16,6 +16,10 @@ // so a range [lo, hi) is answered by visiting, per class in use, the granules from lo - 2^class to hi: the cost is the // halves near the range, never the heap. An entry is checked against the record when visited (a half that moved // leaves a stale entry behind; a bucket drops its stale entries whenever it has doubled since it was last cleaned). +// A bucket counts the halves it holds and goes when the last one leaves it, so the buckets held are those of the live +// halves: without that, every granule a session ever wrote a V# into kept its bucket until the heap was destroyed, and +// the main heap lives as long as the session (many of its V#s are data the title keeps in a slot, with a new base +// whenever the data changes). // Portable, standard library only: console_heap_slot_records_test exercises it without a GPU. #include #include @@ -58,6 +62,14 @@ class ConsoleHeapSlotRecords { std::size_t recorded() const { return recorded_; } // halves in state resolved or waiting std::size_t waiting_count() const { return waiting_; } // halves in state waiting std::uint64_t looked_at() const { return looked_at_; } // index entries visited by touched(), all calls + // The buckets both indexes hold, counted over their maps: a diagnostic (the heap log line and + // console_heap_slot_records_test, which bounds it by the live halves). + std::size_t buckets() const { + std::size_t n = 0; + for (const auto& index : indexes_) + for (const auto& buckets : index.classes) n += buckets.size(); + return n; + } // Half `half` (0: the buffer V#, 1: the UAV counter V#) of `slot` now names [base, base + span) and resolved as // `state` says, its copy at `target` (see above). span 0 counts as 1. @@ -75,18 +87,15 @@ class ConsoleHeapSlotRecords { h.target = target; h.span_state = span | (std::uint64_t(state) << 56); count(state, +1); - if (state == none) return; // entries left behind are stale now - const auto add = [&](int which, std::uint64_t start, std::uint64_t old_start) { - const unsigned c = span_class(span); - const std::uint64_t granule = start >> granule_shift(c); + for (const int which : {kSource, kTarget}) { + unsigned was_c = 0, is_c = 0; + std::uint64_t was_granule = 0, is_granule = 0; + const bool was = held(which, old, was_c, was_granule), is = held(which, h, is_c, is_granule); // Unchanged key: the entry already there stands for it. - if (old.state() != none && (which == kSource || old.target) && span_class(old.span()) == c && - (old_start >> granule_shift(c)) == granule) - return; - push(which, c, granule, std::uint32_t(key)); - }; - add(kSource, base, old.base); - if (target) add(kTarget, target, old.target); + if (was && is && was_c == is_c && was_granule == is_granule) continue; + if (was) leave(which, was_c, was_granule); // the entry left behind is stale now + if (is) push(which, is_c, is_granule, std::uint32_t(key)); + } } void clear(std::size_t slot) { @@ -141,6 +150,7 @@ class ConsoleHeapSlotRecords { struct Bucket { std::vector keys; std::size_t clean = 0; // its size when it was last cleaned + std::size_t live = 0; // the halves held here now: each has a current entry in keys }; struct Index { std::array, kClasses> classes; @@ -158,18 +168,34 @@ class ConsoleHeapSlotRecords { if (state == waiting) waiting_ += std::size_t(std::ptrdiff_t(delta)); } + // Whether index `which` holds a half recorded as `h`, and if so under which class and granule. + static bool held(int which, const Half& h, unsigned& c, std::uint64_t& granule) { + if (h.state() == none || (which == kTarget && !h.target)) return false; + c = span_class(h.span()); + granule = (which == kSource ? h.base : h.target) >> granule_shift(c); + return true; + } + // Whether index `which` still holds `key` under (c, granule). bool current(int which, std::uint32_t key, unsigned c, std::uint64_t granule) const { - const Half& h = halves_[key]; - if (h.state() == none || span_class(h.span()) != c) return false; - if (which == kTarget && !h.target) return false; - return ((which == kSource ? h.base : h.target) >> granule_shift(c)) == granule; + unsigned hc = 0; + std::uint64_t hg = 0; + return held(which, halves_[key], hc, hg) && hc == c && hg == granule; + } + + // A half no longer held under (c, granule): its entry there is stale, and with the last live half the bucket + // goes, its stale entries with it (a lookup skips them, so it answers the same without them). + void leave(int which, unsigned c, std::uint64_t granule) { + auto& buckets = indexes_[which].classes[c]; + const auto it = buckets.find(granule); + if (it != buckets.end() && !--it->second.live) buckets.erase(it); } void push(int which, unsigned c, std::uint64_t granule, std::uint32_t key) { Index& index = indexes_[which]; index.used |= std::uint64_t(1) << c; Bucket& bucket = index.classes[c][granule]; + ++bucket.live; bucket.keys.push_back(key); if (bucket.keys.size() < 32 || bucket.keys.size() < 2 * bucket.clean) return; auto& keys = bucket.keys; diff --git a/runtime/test/console_heap_slot_records_test.cpp b/runtime/test/console_heap_slot_records_test.cpp index c5fcfbe9ab..a721d6b5a3 100644 --- a/runtime/test/console_heap_slot_records_test.cpp +++ b/runtime/test/console_heap_slot_records_test.cpp @@ -127,18 +127,57 @@ struct Model { changes.push_back({SlotChange::source_gone, title, a.end}); changes.push_back({SlotChange::target_gone, kArena + a.shader, kArena + a.shader + (a.end - title)}); } - // apply_slot_changes: the slots looked at (index entries) and fixed again. + // touched() as a walk of every recorded half answers it: the slots whose target (target changes, halves with one) + // or base range (source changes) overlaps a change, waiting halves only for an addition. + std::vector walk(const std::vector& list) const { + std::vector out; + for (std::size_t slot = 0; slot < slots.size(); ++slot) { + bool hit = false; + for (unsigned half = 0; half < 2 && !hit; ++half) { + const auto state = records.state(slot, half); + if (state == ConsoleHeapSlotRecords::none) continue; + const Words& w = slots[slot][half]; + const std::uint64_t target = records.target(slot, half); + for (const SlotChange& change : list) { + const bool on_target = + change.kind == SlotChange::target_gone || change.kind == SlotChange::target_added; + const bool waiting_only = + change.kind == SlotChange::target_added || change.kind == SlotChange::source_added; + if (change.hi <= change.lo || (on_target && !target)) continue; + if (waiting_only && state != ConsoleHeapSlotRecords::waiting) continue; + const std::uint64_t start = on_target ? target : w.base; + if (start < change.hi && start + w.span > change.lo) { + hit = true; + break; + } + } + } + if (hit) out.push_back(std::uint32_t(slot)); + } + return out; + } + // apply_slot_changes: the slots looked at (index entries) and fixed again. Each answer is also compared with the + // walk; a difference is kept until consistent() reports it. std::uint64_t looked = 0; std::vector touched; + std::size_t walk_differs = 0; // touched() answers that differed from the walk void apply() { + const std::vector walked = walk(changes); const std::uint64_t before = records.looked_at(); records.touched(changes.data(), changes.size(), touched); looked = records.looked_at() - before; + if (touched != walked) { + if (!walk_differs) + std::fprintf(stderr, "touched() names %zu slots, a walk of every half %zu\n", touched.size(), + walked.size()); + ++walk_differs; + } changes.clear(); for (const std::uint32_t slot : touched) fix(slot); } // Every slot as a full re-resolution would leave it: the copy the walk this replaced would have produced. bool consistent() const { + if (walk_differs) return false; for (std::size_t slot = 0; slot < slots.size(); ++slot) for (unsigned half = 0; half < 2; ++half) { const Words& w = slots[slot][half]; @@ -326,13 +365,56 @@ int differential() { std::fprintf(stderr, "round %d\n", round); return 1; } + // A half is held at most once in each index, so the buckets held are at most twice the halves recorded. + if (m.records.buckets() > 2 * m.records.recorded()) { + std::fprintf(stderr, "round %d: %zu index buckets held for %zu halves recorded\n", round, + m.records.buckets(), m.records.recorded()); + return 1; + } } EXPECT(m.records.recorded() > 0); // The model's address space is a few MiB, so most changes touch most of it: this case checks results, not cost. - std::printf("differential: 400 rounds, copy equal to a full re-resolution after each; %llu entries looked at, " - "%llu slots fixed again, %zu halves recorded at the end\n", + std::printf("differential: 400 rounds, copy equal to a full re-resolution and touched() to a walk of every half " + "after each; %llu entries looked at, %llu slots fixed again, %zu halves recorded and %zu index " + "buckets held at the end\n", static_cast(looked), static_cast(touched), - m.records.recorded()); + m.records.recorded(), m.records.buckets()); + return 0; +} + +// A half that moves to another granule leaves its old bucket. Slot 0's counter half waits at a new 1 MiB step 200,001 +// times (data the title keeps in a slot reads as a V# with a new base whenever it changes), and slot 1's buffer half +// resolves into a new step as often, so both indexes see it: the buckets held stay those of the two live halves, and +// none is left once both slots are cleared. The lookups give what they gave before. +int buckets_follow_live_halves() { + ConsoleHeapSlotRecords records; + records.reset(16); + constexpr std::uint64_t kMoves = 200001; + for (std::uint64_t i = 0; i < kMoves; ++i) { + records.set(0, 1, ConsoleHeapSlotRecords::waiting, i << 20, 4096, 0); + records.set(1, 0, ConsoleHeapSlotRecords::resolved, (i << 20) + 0x800, 0x100, kArena + (i << 20)); + } + const std::size_t held = records.buckets(); + // The last ranges are found, every earlier one names nothing. + constexpr std::uint64_t last = (kMoves - 1) << 20; + std::vector out; + const SlotChange now[] = {{SlotChange::source_gone, last, last + 0x1000}, + {SlotChange::target_gone, kArena + last, kArena + last + 0x100}}; + records.touched(now, 1, out); + EXPECT(out.size() == 2 && out[0] == 0 && out[1] == 1); + records.touched(now + 1, 1, out); + EXPECT(out.size() == 1 && out[0] == 1); + const SlotChange before[] = {{SlotChange::source_gone, 0, last}, {SlotChange::target_gone, kArena, kArena + last}, + {SlotChange::source_added, 0, last}}; + records.touched(before, 3, out); + EXPECT(out.empty()); + records.clear(0); + records.clear(1); + std::printf("buckets: %llu moves of two halves: %zu index buckets held for the 2 live halves, %zu once both slots " + "are cleared\n", + static_cast(kMoves), held, records.buckets()); + EXPECT(held <= 2 * 2); + EXPECT(records.recorded() == 0 && records.buckets() == 0); return 0; } @@ -341,6 +423,7 @@ int differential() { int main() { if (release_looks_at_its_slots_only()) return 1; if (cases()) return 1; + if (buckets_follow_live_halves()) return 1; if (differential()) return 1; std::printf("console_heap_slot_records_test: ok\n"); return 0; From fc07a0f6c5423620da633c8958bf1742a20fda8f Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:39:24 +0100 Subject: [PATCH 09/49] mem probe: on native Windows a vmmap line shows the process's memory by kind (RT-MEM-PROBE-WINDOWS) LEONIDA_MEM_PROBE's smaps line reads /proc//smaps through Wine's Z: drive. Native Windows has no such entry, so there the line only said "no /proc entry names gta6rt", and the log had no breakdown of the process's own memory on the platform most testers run. Where no /proc entry is found, the probe now prints in its place [rt] mem-probe vmmap t= (, regions): private commit C MiB (peak P), working set W MiB (private V, peak Q); committed T MiB by kind: title A (n regions), pe-private B (n regions), pe-image C (n regions), pe-section D (n regions), vk-mapped E (n regions); reserved R MiB; largest private allocations MiB: 0x... N, ... The counters come from GetProcessMemoryInfo with the PROCESS_MEMORY_COUNTERS_EX2 size (the private working set, Windows 10 21H2 and later), falling back to the _EX size. The kinds come from a VirtualQuery walk over the user address space with the smaps line's title and vk_mapped ranges; the rest of a committed region is named by its type. A region is cut at the ranges' edges, so a reservation the title commits only part of counts in each kind it reaches. The walk's time is in the line: 131 203 regions take about 75 ms here. Diagnostic only: it runs on the probe's own thread, and with LEONIDA_MEM_PROBE unset nothing runs. Under Wine with a /proc entry the smaps line is printed as before. - src/mem_probe.h: VmTally (the classifier: regions and ranges in, committed bytes and region counts per kind out), process_counters, walk_address_space, vmmap_text and sample_vmmap; sample() prints the vmmap line when proc_dir() finds no /proc entry. - runtime/README.md: LEONIDA_MEM_PROBE's row names the vmmap line. Test: mem_probe_vmmap_test (CPU, Windows). Synthetic regions cut at unsorted, overlapping title ranges and a vk_mapped range give the expected bytes and region counts per kind; the line's text; a walk of the test process sees 64 MiB it commits as pe-private and in the commit charge, or as title memory inside a title range, and a 16 MiB section view as pe-section, or as vk-mapped inside a vk_mapped range; a 4 GiB reservation with 65 536 committed pages is walked and timed. It does not build on d44285197, where the native sampler does not exist. --- runtime/CMakeLists.txt | 11 ++ runtime/README.md | 2 +- runtime/src/mem_probe.h | 220 ++++++++++++++++++++++++++ runtime/test/mem_probe_vmmap_test.cpp | 188 ++++++++++++++++++++++ 4 files changed, 420 insertions(+), 1 deletion(-) create mode 100644 runtime/test/mem_probe_vmmap_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..49ec6d10f3 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -4816,6 +4816,17 @@ if(TARGET Vulkan::Headers) target_compile_options(memory_breakdown_test PRIVATE /W4 /permissive- /utf-8) endif() add_test(NAME memory_breakdown COMMAND memory_breakdown_test) + # The mem probe's vmmap line, its reading of the process on native Windows (src/mem_probe.h): the classifier over + # synthetic regions and ranges, and walks of this process around memory it commits and maps. + if(WIN32) + add_executable(mem_probe_vmmap_test test/mem_probe_vmmap_test.cpp) + target_link_libraries(mem_probe_vmmap_test PRIVATE Vulkan::Headers psapi) + target_compile_definitions(mem_probe_vmmap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + if(MSVC) + target_compile_options(mem_probe_vmmap_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME mem_probe_vmmap COMMAND mem_probe_vmmap_test) + endif() # The address guard's page table (src/address_guard.h; docs/d3d12_vulkan.md, "Address guard"). add_executable(address_guard_test test/address_guard_test.cpp) if(WIN32 AND MSVC) diff --git a/runtime/README.md b/runtime/README.md index cdce0a811d..bc69029ee5 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -366,7 +366,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_INPUT_TRACE` | unset | `1` (diagnostic, the GameInput shim built without SDL3) logs the title's reading calls on the scripted pad: the first 128, then each one with a button down and every 1000th. Details in [docs/gameinput.md](../docs/gameinput.md#scripted-input-without-sdl3). | | `LEONIDA_LOG_ALLOCINFO` | unset | *Diagnostic.* `1` logs every device slot 25 call (`GetResourceAllocationInfo`) with its thread, description and sizes (`shims/d3d12_xs_device.cpp`). | | `LEONIDA_LOG_EXE_PIPELINES` | unset | *Diagnostic.* When set, one line per distinct graphics pipeline that uses a program translated from the executable's inline containers. | -| `LEONIDA_MEM_PROBE` | unset | *Diagnostic.* ``: every that many seconds the memory probe (`src/mem_probe.h`) logs `[rt] mem-probe t=` (live pipelines, shader modules and `VkDeviceMemory` per memory type), `[rt] mem-probe breakdown t=` (the same allocated bytes by consumer: the arena with its reserved, bound and in-use MiB, geometry copies, title windows and shadows, upload heaps, staging, texture blocks, sampled textures, render targets and depth, and `other`, which add up to the allocated total; `src/memory_breakdown.h`) and `[rt] mem-probe smaps` (the process's resident memory by kind). | +| `LEONIDA_MEM_PROBE` | unset | *Diagnostic.* ``: every that many seconds the memory probe (`src/mem_probe.h`) logs `[rt] mem-probe t=` (live pipelines, shader modules and `VkDeviceMemory` per memory type), `[rt] mem-probe breakdown t=` (the same allocated bytes by consumer: the arena with its reserved, bound and in-use MiB, geometry copies, title windows and shadows, upload heaps, staging, texture blocks, sampled textures, render targets and depth, and `other`, which add up to the allocated total; `src/memory_breakdown.h`) and `[rt] mem-probe smaps` (the process's resident memory by kind, read from `/proc` under Wine). On native Windows, which has no `/proc`, `[rt] mem-probe vmmap` takes the smaps line's place: the private commit, working set (and private working set where Windows reports it) and their peaks, then the committed MiB of a `VirtualQuery` walk over the address space by the same kinds (title memory, other PE private memory, PE images, PE sections, memory the Vulkan driver mapped for `vkMapMemory`) with their region counts, the reserved MiB and the four largest private allocations; the walk's time is in the line. | | `LEONIDA_MEM_PROBE_CACHE` | unset | *Diagnostic.* `1` adds the pipeline cache's size to the memory probe's report; the driver serializes the whole cache to answer. | | `LEONIDA_TEXTURE_PROBE` | unset | *Diagnostic.* Logs a `[rt] texture-probe` line for every shader resource view of a texture in the title's memory. | | `LEONIDA_LOCAL_DIAGNOSTICS` | unset | *Diagnostic.* `1` turns on the boot diagnostics that write to stderr from the draw, clear, present and descriptor paths (the lines tagged `present-probe`, `fsdraw`, `heap-probe`, `desc-probe` and `PresentX diag`; `src/local_diagnostics.h`). They follow a frame of the title from its draws to the window and cost a lock and a line per draw, so they are off by default. The full-screen draw targets that `LEONIDA_CAPTURE_SOURCE` reads back are only collected with it. | diff --git a/runtime/src/mem_probe.h b/runtime/src/mem_probe.h index f8c573da49..4821b2f3ec 100644 --- a/runtime/src/mem_probe.h +++ b/runtime/src/mem_probe.h @@ -13,11 +13,20 @@ // bound and in-use bytes, geometry copies, title windows and shadows, upload heaps, staging, // texture blocks, sampled textures, render targets and depth, and other, which add up to the // allocated bytes of the t= line. +// [rt] mem-probe vmmap: in place of the smaps line where there is no /proc (native Windows): the commit charge and +// working set (GetProcessMemoryInfo), and the committed bytes of a VirtualQuery walk over the +// user address space by the smaps line's kinds (title memory, other PE private memory, PE +// images, PE sections, memory the Vulkan driver mapped for us), with the reserved bytes and +// the largest private allocations. // The Vulkan counts come from wrapping the runtime's own function table (install()); helpers that load their own // pointers (depth24, predicate, xdxr, swapchain) are not counted: they create a handful of objects. #include +#include #include +#ifdef _MSC_VER +#pragma comment(lib, "psapi.lib") +#endif #include "memory_breakdown.h" @@ -30,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -501,6 +511,211 @@ inline std::string read_rollup() { return out; } +// ---- native Windows: the address space by VirtualQuery, classified ---- +// One committed region as VirtualQuery reports it. +struct VmRegion { + std::uint64_t base = 0, size = 0; + std::uint64_t allocation = 0; // AllocationBase: the VirtualAlloc or the view the region belongs to + std::uint32_t type = 0; // MEM_IMAGE, MEM_MAPPED or MEM_PRIVATE +}; + +// Sorted, with overlapping and touching ranges joined, so that a region can be cut at the ranges' edges. +inline Ranges joined(Ranges ranges) { + std::sort(ranges.begin(), ranges.end()); + Ranges out; + for (const auto& range : ranges) { + if (range.second <= range.first) continue; + if (!out.empty() && range.first <= out.back().second) + out.back().second = (std::max)(out.back().second, range.second); + else + out.push_back(range); + } + return out; +} + +// The committed bytes by the smaps line's kinds, with the same title and vk_mapped ranges: the part of a region inside +// a title range is title memory, the part inside a vk_mapped range is memory the Vulkan driver mapped for us, and the +// rest is named by the region's type. The smaps line names a mapping by its first address; here a region is cut at +// the ranges' edges instead, so a reservation the title commits only part of counts once in each kind it reaches. +class VmTally { +public: + VmTally(Ranges title, Ranges vk_mapped) : title_(joined(std::move(title))), vk_mapped_(joined(std::move(vk_mapped))) {} + + void add(const VmRegion& region) { + bool counted[b_count] = {}; + const std::uint64_t end = region.size > UINT64_MAX - region.base ? UINT64_MAX : region.base + region.size; + for (std::uint64_t at = region.base; at < end;) { + bool inside = false; + std::uint64_t next = piece(title_, at, end, inside); + int bucket = b_title; + if (!inside) { + next = piece(vk_mapped_, at, next, inside); + bucket = inside ? b_vk_mapped : type_bucket(region.type); + } + committed[bucket] += next - at; + if (!counted[bucket]) { + counted[bucket] = true; + ++regions[bucket]; + } + if (bucket == b_pe_private) private_by_allocation_[region.allocation] += next - at; + at = next; + } + } + + std::uint64_t total() const { + std::uint64_t sum = 0; + for (const std::uint64_t bytes : committed) sum += bytes; + return sum; + } + + // The n allocations with the most committed private bytes outside the title and vk_mapped ranges, largest first: + // (bytes, allocation base). + std::vector> largest_private(std::size_t n) const { + std::vector> ranked; + ranked.reserve(private_by_allocation_.size()); + for (const auto& [allocation, bytes] : private_by_allocation_) ranked.push_back({bytes, allocation}); + const std::size_t keep = (std::min)(n, ranked.size()); + std::partial_sort(ranked.begin(), ranked.begin() + std::ptrdiff_t(keep), ranked.end(), + [](const auto& a, const auto& b) { return a.first > b.first; }); + ranked.resize(keep); + return ranked; + } + + std::uint64_t committed[b_count] = {}; + std::uint64_t regions[b_count] = {}; // the regions that put bytes into each kind + +private: + static int type_bucket(std::uint32_t type) { + if (type == MEM_IMAGE) return b_pe_image; + if (type == MEM_MAPPED) return b_pe_mapped; + return b_pe_private; + } + // From `at`, the end (at most `end`) of the piece that lies wholly inside one of `ranges` or wholly outside them. + static std::uint64_t piece(const Ranges& ranges, std::uint64_t at, std::uint64_t end, bool& inside) { + const auto it = std::upper_bound(ranges.begin(), ranges.end(), std::make_pair(at, UINT64_MAX)); + if (it != ranges.begin() && at < std::prev(it)->second) { + inside = true; + return (std::min)(end, std::prev(it)->second); + } + inside = false; + return it == ranges.end() ? end : (std::min)(end, it->first); + } + + Ranges title_, vk_mapped_; + std::map private_by_allocation_; +}; + +// The process's commit charge and working set. PrivateUsage and PagefileUsage are the same figure on Windows 8 and +// later; Wine fills only PagefileUsage (src/memory_figures.h), so the larger of the two is the charge. +struct ProcessCounters { + bool read = false; // GetProcessMemoryInfo answered + bool private_working_set_reported = false; // it took the PROCESS_MEMORY_COUNTERS_EX2 size + std::uint64_t private_commit = 0, peak_commit = 0, working_set = 0, peak_working_set = 0; + std::uint64_t private_working_set = 0; // 0 where the system does not report it +}; + +// PROCESS_MEMORY_COUNTERS_EX2's layout. The SDK declares it only for NTDDI_WIN10_CU and later, and MinGW's headers may +// not at all; Windows 10 21H2 and later fill it, an older system refuses its size. +struct MemoryCountersEx2 { + PROCESS_MEMORY_COUNTERS_EX ex; + SIZE_T private_working_set; + ULONG64 shared_commit; +}; +static_assert(sizeof(MemoryCountersEx2) == sizeof(PROCESS_MEMORY_COUNTERS_EX) + 2 * sizeof(ULONG64), + "PROCESS_MEMORY_COUNTERS_EX2 is PROCESS_MEMORY_COUNTERS_EX and two more 64-bit fields"); + +inline ProcessCounters process_counters() { + MemoryCountersEx2 counters{}; + counters.ex.cb = sizeof counters; + ProcessCounters out; + out.private_working_set_reported = GetProcessMemoryInfo( + GetCurrentProcess(), reinterpret_cast(&counters), sizeof counters) != FALSE; + if (!out.private_working_set_reported) { + counters = {}; + counters.ex.cb = sizeof counters.ex; + if (!GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&counters.ex), + sizeof counters.ex)) + return out; + } + out.read = true; + out.private_commit = (std::max)(std::uint64_t(counters.ex.PrivateUsage), std::uint64_t(counters.ex.PagefileUsage)); + out.peak_commit = counters.ex.PeakPagefileUsage; + out.working_set = counters.ex.WorkingSetSize; + out.peak_working_set = counters.ex.PeakWorkingSetSize; + out.private_working_set = counters.private_working_set; + return out; +} + +// Walks the user address space (GetSystemInfo's bounds) with VirtualQuery: every committed region goes to the tally, +// and the reserved bytes are summed. Returns how many regions it walked, free ones included. +inline std::uint64_t walk_address_space(VmTally& tally, std::uint64_t& reserved) { + SYSTEM_INFO system{}; + GetSystemInfo(&system); + const auto last = reinterpret_cast(system.lpMaximumApplicationAddress); + std::uint64_t walked = 0; + for (auto at = reinterpret_cast(system.lpMinimumApplicationAddress); at <= last;) { + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(reinterpret_cast(at), ®ion, sizeof region)) break; + const auto base = reinterpret_cast(region.BaseAddress); + ++walked; + if (region.State == MEM_COMMIT) + tally.add({base, region.RegionSize, reinterpret_cast(region.AllocationBase), region.Type}); + else if (region.State == MEM_RESERVE) + reserved += region.RegionSize; + if (base + region.RegionSize <= at) break; // no progress: stop rather than loop + at = base + region.RegionSize; + } + return walked; +} + +inline std::string vmmap_text(double t, double ms, std::uint64_t walked, const ProcessCounters& counters, + const VmTally& tally, std::uint64_t reserved) { + char item[256]; + std::snprintf(item, sizeof item, "[rt] mem-probe vmmap t=%.0fs (%.0f ms, %llu regions): ", t, ms, + (unsigned long long)walked); + std::string text = item; + if (counters.read) { + char private_ws[32] = "n/a"; + if (counters.private_working_set) + std::snprintf(private_ws, sizeof private_ws, "%.0f", mib(counters.private_working_set)); + std::snprintf(item, sizeof item, + "private commit %.0f MiB (peak %.0f), working set %.0f MiB (private %s, peak %.0f); ", + mib(counters.private_commit), mib(counters.peak_commit), mib(counters.working_set), private_ws, + mib(counters.peak_working_set)); + text += item; + } else { + text += "process counters n/a; "; + } + std::snprintf(item, sizeof item, "committed %.0f MiB by kind:", mib(tally.total())); + text += item; + const int kinds[] = {b_title, b_pe_private, b_pe_image, b_pe_mapped, b_vk_mapped}; + for (const int b : kinds) { + std::snprintf(item, sizeof item, "%s %s %.0f (%llu regions)", b == kinds[0] ? "" : ",", bucket_name(b), + mib(tally.committed[b]), (unsigned long long)tally.regions[b]); + text += item; + } + std::snprintf(item, sizeof item, "; reserved %.0f MiB; largest private allocations MiB:", mib(reserved)); + text += item; + const auto largest = tally.largest_private(4); + for (std::size_t i = 0; i < largest.size(); ++i) { + std::snprintf(item, sizeof item, "%s 0x%llx %.0f", i ? "," : "", (unsigned long long)largest[i].second, + mib(largest[i].first)); + text += item; + } + if (largest.empty()) text += " none"; + return text; +} + +// The vmmap line of this process now. It takes the title and vk_mapped ranges the smaps line would use. +inline std::string sample_vmmap(double t, const Ranges& title, const Ranges& vk_mapped) { + const std::uint64_t t0 = now_ns(); + const ProcessCounters counters = process_counters(); + VmTally tally(title, vk_mapped); + std::uint64_t reserved = 0; + const std::uint64_t walked = walk_address_space(tally, reserved); + return vmmap_text(t, double(now_ns() - t0) / 1e6, walked, counters, tally, reserved); +} + // What the device adds to the line: pipeline cache bytes, arena use, title memory ranges. struct DeviceFacts { std::function describe; // one text fragment @@ -590,6 +805,11 @@ inline void sample(const DeviceFacts& facts) { .c_str()); Ranges title = facts.title_ranges ? facts.title_ranges() : Ranges{}; std::sort(title.begin(), title.end()); + // Native Windows has no /proc to read: the vmmap line takes the same kinds from the Win32 API there. + if (proc_dir().empty()) { + std::fprintf(stderr, "%s\n", sample_vmmap(t, title, vk_mapped).c_str()); + return; + } Usage usage[b_count]; std::string top_files, error; const std::uint64_t t0 = now_ns(); diff --git a/runtime/test/mem_probe_vmmap_test.cpp b/runtime/test/mem_probe_vmmap_test.cpp new file mode 100644 index 0000000000..f9cac8af57 --- /dev/null +++ b/runtime/test/mem_probe_vmmap_test.cpp @@ -0,0 +1,188 @@ +// leonida::mem_probe's vmmap line (src/mem_probe.h, LEONIDA_MEM_PROBE=): on native Windows there is no +// /proc//smaps to read, so the probe walks the address space with VirtualQuery and sums the committed bytes by the +// smaps line's kinds. The classifier cuts synthetic regions at the title and vk_mapped ranges and names the rest by +// their type; a walk of this process sees 64 MiB it commits as PE private memory, or as title memory inside a title +// range, and a mapped view as a PE section, or as memory the Vulkan driver mapped inside a vk_mapped range. A walk +// over a 4 GiB reservation with 65 536 committed pages prints how long it takes. No GPU, no device. +#include "../src/mem_probe.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +namespace mp = leonida::mem_probe; +constexpr std::uint64_t kMiB = 1 << 20; +constexpr std::uint64_t kKiB = 1 << 10; + +bool contains(const std::string& text, const char* part) { return text.find(part) != std::string::npos; } + +std::uint64_t walk(mp::VmTally& tally) { + std::uint64_t reserved = 0; + return mp::walk_address_space(tally, reserved); +} + +// Synthetic regions: the part inside a title range is title memory, the part inside a vk_mapped range is the driver's, +// the rest goes by the region's type, and a region cut by a range counts once in each kind it reaches. The title ranges +// come unsorted and overlapping, as a caller may hand them. +int classifier() { + const mp::Ranges title = {{0x30000000, 0x30100000}, {0x10000000, 0x18000000}, {0x17000000, 0x20000000}}; + const mp::Ranges vk_mapped = {{0x40000000, 0x40200000}}; + mp::VmTally t(title, vk_mapped); + t.add({0x10000000, 64 * kMiB, 0x10000000, MEM_PRIVATE}); // all title + t.add({0x1FF00000, 2 * kMiB, 0x1FF00000, MEM_PRIVATE}); // 1 MiB title, then 1 MiB private + t.add({0x2FF00000, 3 * kMiB, 0x2FF00000, MEM_MAPPED}); // 1 MiB section, 1 MiB title, 1 MiB section + t.add({0x40000000, 2 * kMiB, 0x40000000, MEM_MAPPED}); // all vk_mapped + t.add({0x401F0000, 128 * kKiB, 0x401F0000, MEM_PRIVATE}); // 64 KiB vk_mapped, then 64 KiB private + t.add({0x140000000, 3 * kMiB, 0x140000000, MEM_IMAGE}); + t.add({0x50000000, 5 * kMiB, 0x50000000, MEM_MAPPED}); + t.add({0x60000000, 1 * kMiB, 0x60000000, MEM_PRIVATE}); // one allocation in two regions + t.add({0x60100000, 7 * kMiB, 0x60000000, MEM_PRIVATE}); + EXPECT(t.committed[mp::b_title] == 66 * kMiB && t.regions[mp::b_title] == 3); + EXPECT(t.committed[mp::b_pe_private] == 9 * kMiB + 64 * kKiB && t.regions[mp::b_pe_private] == 4); + EXPECT(t.committed[mp::b_pe_mapped] == 7 * kMiB && t.regions[mp::b_pe_mapped] == 2); + EXPECT(t.committed[mp::b_vk_mapped] == 2 * kMiB + 64 * kKiB && t.regions[mp::b_vk_mapped] == 2); + EXPECT(t.committed[mp::b_pe_image] == 3 * kMiB && t.regions[mp::b_pe_image] == 1); + std::uint64_t sum = 0; + for (int b = 0; b < mp::b_count; ++b) sum += t.committed[b]; + EXPECT(sum == 87 * kMiB + 128 * kKiB); // every byte of every region, once + EXPECT(t.total() == sum); + const auto largest = t.largest_private(2); + EXPECT(largest.size() == 2); + EXPECT(largest[0].first == 8 * kMiB && largest[0].second == 0x60000000); + EXPECT(largest[1].first == 1 * kMiB && largest[1].second == 0x1FF00000); + // Without ranges every byte goes by its type. + mp::VmTally bare({}, {}); + bare.add({0x10000000, 64 * kMiB, 0x10000000, MEM_PRIVATE}); + bare.add({0x40000000, 2 * kMiB, 0x40000000, MEM_MAPPED}); + EXPECT(bare.committed[mp::b_pe_private] == 64 * kMiB && bare.committed[mp::b_pe_mapped] == 2 * kMiB); + EXPECT(bare.committed[mp::b_title] == 0 && bare.committed[mp::b_vk_mapped] == 0); + return 0; +} + +// The text: the walk's time and size, the process counters, the committed MiB of every kind with its regions, the +// reserved bytes and the largest private allocations; "n/a" where the system did not report the private working set. +int text() { + mp::VmTally t({{0x10000000, 0x20000000}}, {{0x40000000, 0x40200000}}); + t.add({0x10000000, 64 * kMiB, 0x10000000, MEM_PRIVATE}); + t.add({0x40000000, 2 * kMiB, 0x40000000, MEM_MAPPED}); + t.add({0x60000000, 8 * kMiB, 0x60000000, MEM_PRIVATE}); + t.add({0x140000000, 3 * kMiB, 0x140000000, MEM_IMAGE}); + t.add({0x50000000, 5 * kMiB, 0x50000000, MEM_MAPPED}); + mp::ProcessCounters counters; + counters.read = true; + counters.private_commit = 2048 * kMiB; + counters.peak_commit = 4096 * kMiB; + counters.working_set = 1024 * kMiB; + counters.peak_working_set = 1536 * kMiB; + counters.private_working_set = 512 * kMiB; + const std::string line = mp::vmmap_text(12.0, 3.0, 100, counters, t, 640 * kMiB); + std::fprintf(stderr, "%s\n", line.c_str()); + EXPECT(line.rfind("[rt] mem-probe vmmap t=12s (3 ms, 100 regions): private commit 2048 MiB (peak 4096), working " + "set 1024 MiB (private 512, peak 1536); committed 82 MiB by kind: title 64 (1 regions), " + "pe-private 8 (1 regions), pe-image 3 (1 regions), pe-section 5 (1 regions), vk-mapped 2 (1 " + "regions); reserved 640 MiB; largest private allocations MiB: 0x60000000 8", + 0) == 0); + counters.private_working_set = 0; + EXPECT(contains(mp::vmmap_text(12.0, 3.0, 100, counters, t, 0), "(private n/a, peak 1536)")); + EXPECT(contains(mp::vmmap_text(12.0, 3.0, 100, mp::ProcessCounters{}, t, 0), + "(3 ms, 100 regions): process counters n/a; committed 82 MiB")); + return 0; +} + +// This process: 64 MiB it commits shows up as PE private memory and in the commit charge, as title memory when a +// title range covers it, and a 16 MiB view of a pagefile-backed section as a PE section, or as vk-mapped memory when a +// vk_mapped range covers it. +int live() { + const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr; + const mp::ProcessCounters counters_before = mp::process_counters(); + mp::VmTally before({}, {}); + EXPECT(walk(before) > 0); + EXPECT(before.committed[mp::b_pe_image] > 0); // this executable and its DLLs + + auto* block = static_cast(VirtualAlloc(nullptr, 64 * kMiB, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(block); + std::memset(block, 1, 64 * kMiB); // in the working set too + const std::uint64_t base = reinterpret_cast(block); + mp::VmTally after({}, {}); + walk(after); + const mp::ProcessCounters counters_after = mp::process_counters(); + std::fprintf(stderr, "pe-private %.0f -> %.0f MiB, private commit %.0f -> %.0f MiB, private working set %.0f MiB\n", + mp::mib(before.committed[mp::b_pe_private]), mp::mib(after.committed[mp::b_pe_private]), + mp::mib(counters_before.private_commit), mp::mib(counters_after.private_commit), + mp::mib(counters_after.private_working_set)); + EXPECT(after.committed[mp::b_pe_private] >= before.committed[mp::b_pe_private] + 64 * kMiB); + EXPECT(counters_before.read && counters_after.read); + EXPECT(counters_after.private_commit >= counters_before.private_commit + 64 * kMiB); + EXPECT(counters_after.working_set > 0 && counters_after.peak_working_set >= counters_after.working_set); + if (!wine && counters_after.private_working_set_reported) EXPECT(counters_after.private_working_set > 0); + bool listed = false; + for (const auto& [bytes, allocation] : after.largest_private(4)) + if (allocation == base && bytes == 64 * kMiB) listed = true; + EXPECT(listed); + + mp::VmTally titled({{base, base + 64 * kMiB}}, {}); + walk(titled); + EXPECT(titled.committed[mp::b_title] == 64 * kMiB && titled.regions[mp::b_title] == 1); + + HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(16 * kMiB), nullptr); + EXPECT(section); + void* view = MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, 0); + EXPECT(view); + const std::uint64_t view_base = reinterpret_cast(view); + mp::VmTally mapped({}, {}); + walk(mapped); + EXPECT(mapped.committed[mp::b_pe_mapped] >= after.committed[mp::b_pe_mapped] + 16 * kMiB); + mp::VmTally driver({}, {{view_base, view_base + 16 * kMiB}}); + walk(driver); + EXPECT(driver.committed[mp::b_vk_mapped] == 16 * kMiB && driver.regions[mp::b_vk_mapped] == 1); + + UnmapViewOfFile(view); + CloseHandle(section); + VirtualFree(block, 0, MEM_RELEASE); + return 0; +} + +// A big, fragmented address space: 4 GiB reserved with one page committed every 64 KiB gives 65 536 committed regions +// between as many reserved ones. The walk counts them all and prints how long it took, then the whole line. +int big_address_space() { + const std::uint64_t span = 4ull << 30, step = 64 * kKiB, page = 4 * kKiB; + auto* base = static_cast(VirtualAlloc(nullptr, span, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(base); + for (std::uint64_t offset = 0; offset < span; offset += step) + EXPECT(VirtualAlloc(base + offset, page, MEM_COMMIT, PAGE_READWRITE)); + mp::VmTally tally({}, {}); + std::uint64_t reserved = 0; + const auto t0 = std::chrono::steady_clock::now(); + const std::uint64_t walked = mp::walk_address_space(tally, reserved); + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + std::fprintf(stderr, "walk: %llu regions in %.1f ms, %llu private regions, %.0f MiB reserved\n", + (unsigned long long)walked, ms, (unsigned long long)tally.regions[mp::b_pe_private], mp::mib(reserved)); + EXPECT(walked >= 2 * (span / step)); + EXPECT(tally.regions[mp::b_pe_private] >= span / step); + EXPECT(reserved >= span - (span / step) * page); + const auto largest = tally.largest_private(1); + EXPECT(!largest.empty() && largest[0].second == reinterpret_cast(base) && + largest[0].first == (span / step) * page); + std::fprintf(stderr, "%s\n", mp::sample_vmmap(0.0, {}, {}).c_str()); + VirtualFree(base, 0, MEM_RELEASE); + return 0; +} + +} // namespace + +int main() { + if (int r = classifier()) return r; + if (int r = text()) return r; + if (int r = live()) return r; + if (int r = big_address_space()) return r; + std::fprintf(stderr, "mem_probe_vmmap: ok\n"); + return 0; +} From 0da68876c26a7770834e55d4fb11b0661a53dc89 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:44:43 +0100 Subject: [PATCH 10/49] d3d12: a shim's scratch stays alive until the submission that used it has completed (RT-REHYDRATE-SCRATCH-TICKET) RehydrateRaytracingAccelerationStructureBatched2X makes its own scratch buffer when the title passes ScratchAccelerationStructureData = 0 (the retail title does) and hands it to the list with hold_until_reset. The list released it at its Reset or release, which D3D12 allows as soon as ExecuteCommandLists returns. In the default synchronous submit mode nothing else held it, and a default-heap buffer's arena range is free the moment the buffer is destroyed, so the next DEFAULT buffer of that size could get the range, and be zeroed by the CPU, while the build still ran. ExecuteCommandLists now also gives the queue the objects its lists hold through hold_until_reset (keep_lists), and a batch submitted at once keeps them until its submission has completed; drain_pins releases them as it releases the fences. Held batches and LEONIDA_SUBMIT_ASYNC already kept them, with the lists' pipeline states (pin_lists). A list without such objects costs one size check. The rehydrate is the only user of hold_until_reset. xbox_bvh_builder_test: a rehydrate without the title's scratch is executed, the list is Reset at once on another allocator (a second list is released), and a DEFAULT buffer of the scratch's size is made before any Signal. On d44285197 it got the scratch's own VA and the sentinels the lists held were already released (3 of 33 checks failed); now its range is elsewhere, and the sentinels go once the submission has completed. --- runtime/shims/d3d12_com.cpp | 36 ++++++++- runtime/shims/d3d12_com.h | 11 +-- runtime/src/vulkan_backend.h | 20 +++-- runtime/test/xbox_bvh_builder_test.cpp | 100 ++++++++++++++++++++++++- 4 files changed, 153 insertions(+), 14 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4a61ffadbc..1c9c225730 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -225,8 +225,14 @@ class GraphicsCommandList final // The pipeline states and root signatures the recording names (it holds a reference to each until Reset), and // the objects a shim handed it with hold_until_reset. const std::vector& pinned() const { return held_; } + // The objects a shim handed it with hold_until_reset (also in pinned()), which ExecuteCommandLists keeps until + // the submission has completed: the application may Reset or release the list as soon as the call returns. + const std::vector& kept() const { return kept_; } // rt::d3d12::hold_until_reset: an object the recording uses that its caller does not keep (a shim's own scratch). - void hold_for_recording(IUnknown* object) { hold(object); } + void hold_for_recording(IUnknown* object) { + if (std::find(kept_.begin(), kept_.end(), object) == kept_.end()) kept_.push_back(object); + hold(object); + } bool needs_all_sampled_views() const { if (directly_indexed_) return true; for (const auto& command : list_.commands()) { @@ -1621,6 +1627,9 @@ class GraphicsCommandList final // layout it reads and the pipeline ExecuteCommandLists looks up still exist. (Keeping them alive while the GPU // runs the submission stays the application's job, as in D3D12.) std::vector held_; + // The part of held_ a shim handed the list (hold_until_reset). Nothing else keeps those alive while the GPU runs + // the submission (CommandQueue::keep_lists). No references of its own: held_ has them. + std::vector kept_; // A bundle keeps its state calls and draws instead of applying them: it has no render targets, viewport or root // signature of its own to resolve them against, and what it sets belongs to the list that executes it. @@ -1656,6 +1665,7 @@ class GraphicsCommandList final void release_held() { for (IUnknown* object : held_) object->Release(); held_.clear(); + kept_.clear(); } void set_pipeline(ID3D12PipelineState* state) { @@ -2365,6 +2375,27 @@ class CommandQueue final return objects; } + // What a batch submitted at once keeps alive until its submission has completed on the GPU: the shim's own + // objects its lists use (hold_until_reset). The lists release them at their Reset or release, which D3D12 allows + // as soon as ExecuteCommandLists returns, and a default-heap buffer's arena range is free again the moment the + // buffer is destroyed. Null when no list has any, which is every list without a shim's scratch. + static std::shared_ptr keep_lists(const std::vector& lists) { + std::size_t count = 0; + for (const GraphicsCommandList* list : lists) count += list->kept().size(); + if (!count) return nullptr; + auto objects = std::shared_ptr>(new std::vector, [](auto* kept) { + for (IUnknown* object : *kept) object->Release(); + delete kept; + }); + objects->reserve(count); + for (const GraphicsCommandList* list : lists) + for (IUnknown* object : list->kept()) { + object->AddRef(); + objects->push_back(object); + } + return objects; + } + // A D3D12 queue holds the fences it waits on and signals until the work has been submitted. static leonida::VulkanQueue::PinFn fence_pin(ID3D12Fence* fence) { return [fence]() -> std::shared_ptr { @@ -2535,7 +2566,8 @@ class CommandQueue final return; } } - last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); + last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }, + [&graphics] { return keep_lists(graphics); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); if (last_result_ != leonida::ReplayResult::success) std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists failed: %s; nothing was submitted\n", diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 2c948ff3d3..86a6b66e13 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -665,11 +665,12 @@ void set_global_realtime_privilege_override_for_test(int state); bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& back); // Makes `list` hold a reference to `object` until its next Reset or its release, as it holds the pipeline states it -// names: for an object only the recording uses, such as a shim's own scratch buffer. A list is Reset once it has -// been executed (or a held batch, src/queue_holds.h, keeps it pinned until it has run), and a resource released -// after its submission is destroyed through the device's deferred queue once that submission has retired, so the -// object outlives every GPU use the recording makes of it. False when `list` is not one of this module's command -// lists or `object` is null. +// names: for an object only the recording uses, such as a shim's own scratch buffer. D3D12 lets the application +// Reset or release a list as soon as ExecuteCommandLists returns, while the GPU still runs it, so each execution of +// the list also keeps the object until that submission has completed (a held batch, src/queue_holds.h, until it +// has run and then until its submission has completed). That is what keeps a default-heap buffer's arena range +// from being handed out again under a build that still uses it: the range is free the moment the buffer is +// destroyed. False when `list` is not one of this module's command lists or `object` is null. bool hold_until_reset(ID3D12GraphicsCommandList* list, IUnknown* object); // A copy of the commands `list` has recorded so far, for tests of what a bundle puts into its parent. False when diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 858ba46bec..5b5a9ccaaf 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -2747,12 +2747,15 @@ class VulkanQueue : private QueueHolds::Holder { // held instead, and the call succeeds: the batch is replayed by the thread that submits the Signal (or the CPU // Signal), which is also where its errors are reported (stderr, and take_held_failure()). // - // `pin`, called only when the batch is held, returns what has to stay alive until the batch has run: the COM layer - // passes the pipeline states and root signatures the lists named (the application may release them and Reset - // the lists as soon as the call returns). + // `pin`, called only when the batch is held (or queued for the worker, LEONIDA_SUBMIT_ASYNC), returns what has to + // stay alive until the batch has run: the COM layer passes the pipeline states and root signatures the lists + // named (the application may release them and Reset the lists as soon as the call returns). `keep`, called when + // the batch is submitted at once, returns what has to stay alive until that submission has completed on the GPU, + // or null: the COM layer passes the objects a shim gave the lists for their recording alone (a scratch buffer). + // A held or queued batch has those in what `pin` returned, which is kept until its submission has completed too. using PinFn = std::function()>; - ReplayResult execute(std::span lists, const PinFn& pin = {}) { + ReplayResult execute(std::span lists, const PinFn& pin = {}, const PinFn& keep = {}) { pipeline_wait::note_submission(); // big compute warm-ups are left to their first use while the title submits auto* diagnostics = context_.device_fault(); const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0; @@ -2766,10 +2769,11 @@ class VulkanQueue : private QueueHolds::Holder { enqueue(std::move(call)); return ReplayResult::success; } - return execute_sync(lists, pin, execute_call); + return execute_sync(lists, pin, execute_call, keep); } - ReplayResult execute_sync(std::span lists, const PinFn& pin, std::uint64_t execute_call) { + ReplayResult execute_sync(std::span lists, const PinFn& pin, std::uint64_t execute_call, + const PinFn& keep = {}) { ReplayResult result = ReplayResult::success; bool held = false; std::vector> retired; // destroyed after state_mutex_ is released @@ -2777,6 +2781,10 @@ class VulkanQueue : private QueueHolds::Holder { std::lock_guard state(state_mutex_); if (!must_hold()) { result = execute_now(lists, execute_call); + if (std::shared_ptr kept = keep ? keep() : nullptr) { + std::vector> pins{std::move(kept)}; + retire_pins(pins, submitted_); // released by drain_pins once this submission has completed + } } else if (context_.is_device_lost()) { result = queue_unsupported(__LINE__); } else { diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp index 8334143fd7..09276de37d 100644 --- a/runtime/test/xbox_bvh_builder_test.cpp +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -7,7 +7,9 @@ // an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream // is accepted, rehydration rebuilds from geometry with S_OK (with the title's scratch, with none, and two elements of // one batch without scratch, which the shim gives regions of their own; their structures go to check-build too) and -// refuses a source-only element, and builders are released. +// refuses a source-only element, the scratch the shim makes (and an object a list holds through hold_until_reset) +// outlives a Reset or release of the list right after ExecuteCommandLists until that submission has completed, and +// builders are released. // // xbox_bvh_builder_test the shim // xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered @@ -18,6 +20,7 @@ #include "../shims/shims.h" #include "../src/xdxr_descs.h" +#include #include #include #include @@ -26,6 +29,7 @@ #include #include #include +#include #include namespace rt::shims { @@ -52,6 +56,22 @@ template struct Ref { T** put() { return &p; } }; +// An object only a recording uses, as a shim's own scratch is, handed to a list with hold_until_reset. It counts its +// references and is never freed, so a check can read when the layer let it go. +struct Sentinel final : IUnknown { + std::atomic refs{1}; + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (iid != __uuidof(IUnknown)) return E_NOINTERFACE; + AddRef(); + *out = this; + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; } + ULONG STDMETHODCALLTYPE Release() override { return --refs; } +}; + int fail(const char* what, HRESULT hr = S_OK) { std::fprintf(stderr, "FAIL: %s (hr 0x%08lx)\n", what, static_cast(hr)); return 1; @@ -522,6 +542,84 @@ int main(int argc, char** argv) { : "the batch's first element (its own scratch region) is written for check-build"); } + // ---- the shim's scratch outlives a Reset of the list until the submission that used it has completed ---- + // D3D12 lets the title Reset a list as soon as ExecuteCommandLists returns (only its allocator waits for the GPU), + // and the title rehydrates with ScratchAccelerationStructureData = 0. The scratch the shim made for the build must + // not go back to the arena before the build has run: the next DEFAULT buffer of its size would get its range and + // be zeroed by the CPU while the GPU still uses it. A list released right after the call makes the same promise. + { + Ref next_allocator, other_allocator; + Ref other_list; + Ref kept_as, kept_rb; + if (FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(next_allocator.put()))) || + FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(other_allocator.put()))) || + FAILED(hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, other_allocator.p, nullptr, + IID_PPV_ARGS(other_list.put()))) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, + kept_as.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, kept_rb.put()))) + return fail("kept-scratch lists or buffers", hr); + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for kept scratch"); + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC kept_desc = zero_scratch_desc; + kept_desc.DestAccelerationStructureData = kept_as->GetGPUVirtualAddress(); + check(rehydrate(builder, list.p, 1, &kept_desc, &source) == S_OK, + "a rehydrate without the title's scratch is recorded for the Reset check"); + // The build's scratch is the one buffer the shim made for this call (one element: its region starts there). + UINT64 scratch_va = 0; + std::vector commands; + if (rt::d3d12::recorded_commands(list.p, commands)) + for (const auto& command : commands) + if (const auto* build = std::get_if(&command)) + scratch_va = build->scratch_va; + const UINT64 scratch_bytes = (blas_info.ScratchDataSizeInBytes + 255) / 256 * 256; + Sentinel reset_sentinel, release_sentinel; + check(scratch_va && rt::d3d12::hold_until_reset(list.p, &reset_sentinel) && + rt::d3d12::hold_until_reset(other_list.p, &release_sentinel), + "the build has the shim's scratch, and both lists hold a sentinel"); + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(kept_rb.p, 0, kept_as.p, 0, blas_info.ResultDataMaxSizeInBytes); + if (FAILED(list->Close()) || FAILED(other_list->Close())) return fail("Close for kept scratch"); + ID3D12CommandList* lists[] = {list.p, other_list.p}; + queue->ExecuteCommandLists(2, lists); + // At once, before any Signal: the one list is Reset on another allocator, the other released. + if (FAILED(list->Reset(next_allocator.p, nullptr))) return fail("Reset right after ExecuteCommandLists"); + other_list->Release(); + other_list.p = nullptr; + Ref probe; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_bytes, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + uav, probe.put()))) + return fail("probe buffer", hr); + const UINT64 probe_va = probe->GetGPUVirtualAddress(); + std::printf("scratch VA 0x%llx, a DEFAULT buffer of its 0x%llx bytes made after the Reset at VA 0x%llx\n", + static_cast(scratch_va), static_cast(scratch_bytes), + static_cast(probe_va)); + check(probe_va + scratch_bytes <= scratch_va || scratch_va + scratch_bytes <= probe_va, + "a DEFAULT buffer made right after the Reset does not get the range of the scratch the submission uses"); + check(reset_sentinel.refs.load() > 1, "an object a list holds outlives the list's Reset after the call"); + check(release_sentinel.refs.load() > 1, "and the list's release after the call"); + // The queue lets go of what a submission kept on its next call after that submission has completed: a + // Signal once the build's fence is reached, and one more, waited for, so that its release has run also + // when the queue's calls run on a worker (LEONIDA_SUBMIT_ASYNC). + const bool settled = SUCCEEDED(list->Close()) && [&] { + for (int i = 0; i < 2; ++i) { + if (FAILED(queue->Signal(fence.p, ++fence_value))) return false; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(fence_value, event)) && + WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + if (!done) return false; + } + return SUCCEEDED(device->GetDeviceRemovedReason()); + }(); + if (!settled) return fail("the kept-scratch submission did not complete"); + check(header_units(kept_rb.p) > 0, "the structure rehydrated with the kept scratch was built"); + check(reset_sentinel.refs.load() == 1 && release_sentinel.refs.load() == 1, + "both objects are released once the submission has completed"); + } + // ---- the destructor releases the builder ---- destruct(builder); destruct(builder); // a second destruction of the same storage is ignored From 9ebbc49a171e6122df9c71cbce1335bd41de0076 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:45:25 +0100 Subject: [PATCH 11/49] d3d12: the PSOs of one program share its code-base copy in the arena (RT-FSSM-ARENA-SHARE) A compute or graphics PSO whose shader reads its code base (s_getpc_b64 and the constant tables in its own program) copies that program into the GPU address arena, which has a fixed size (256 MiB by default, at most 4095 MiB). Each PSO made its own copy, so N PSOs of one program held N copies of the same bytes until they were released. The device now keeps one copy per program, keyed by the SHA-256 the PSO found the program's translation by (fssm_sha256, or fspx_code_sha256 for a kind-6 program), which is the hash of the bytes copied. The first PSO makes the copy, the others take a reference, and the last one returns it to the arena when that PSO is deleted: the same point a PSO's own copy was returned, after any build of it a compile worker was running. Compute entries whose index has no uses_code_base key are still copied, as before. LEONIDA_SHARE_CODE_BASE=0 gives every PSO a copy of its own, as before (runtime/README.md). d3d12_code_base_share_test creates four compute PSOs of one program, others of programs with and without a code base or with no uses_code_base key, and two graphics PSOs whose pixel shader reads its code base. It checks the arena's shader bytes and each PSO's code base VA and bytes through two read-only test hooks (arena_shader_bytes, pipeline_code_base). Without the sharing it fails: four PSOs of a 4004-byte program held 16016 bytes. d3d12_code_base_per_pso runs it with LEONIDA_SHARE_CODE_BASE=0. --- docs/d3d12_vulkan.md | 3 +- runtime/CMakeLists.txt | 13 + runtime/README.md | 1 + runtime/shims/d3d12_com.h | 6 + runtime/shims/d3d12_vulkan_device.cpp | 100 ++++++- runtime/test/d3d12_code_base_share_test.cpp | 282 ++++++++++++++++++++ 6 files changed, 399 insertions(+), 6 deletions(-) create mode 100644 runtime/test/d3d12_code_base_share_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e843d8debc..fe2b76eb10 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -916,7 +916,8 @@ The compute path, end to end: - Shader-visible descriptor heaps also live in it: the CPU handle is its host mapping and the GPU handle is the VA, so descriptor bytes the application writes itself are what shaders load. - Upload and readback buffers keep their own memory, and their VA is their device address minus the heap base. - - Shader programs (FSSM blobs) are copied in as the code base. + - Shader programs (FSSM blobs) are copied in as the code base, once per program: the PSOs made from one program + share its copy, which goes back to the arena with the last of them (`LEONIDA_SHARE_CODE_BASE`). - **`CreateRootSignature`** parses the blob with `parse_rts0` and keeps each parameter's place in two layouts, both the console's (one dword per table; section 3.5, D3D-448): `pack_stage(Stage::Pixel)` for the graphics bind point (from s8; a signature past s31 there keeps `pack()`'s s0 layout, logged) and `pack_stage(Stage::Compute)` for the diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..cccffb47b1 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -4118,6 +4118,19 @@ if(TARGET Vulkan::Headers) # the thread (d3d12_compile_teardown_test). set_tests_properties(d3d12_pso_validation PROPERTIES SKIP_RETURN_CODE 77 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # The arena copy of a program that shaders read their code base from: one per program, shared by its PSOs. + add_executable(d3d12_code_base_share_test test/d3d12_code_base_share_test.cpp ${LEONIDA_TEST_CS} + ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_PS}) + target_link_libraries(d3d12_code_base_share_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_code_base_share_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" + LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}") + target_compile_options(d3d12_code_base_share_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_code_base_share COMMAND d3d12_code_base_share_test) + # LEONIDA_SHARE_CODE_BASE=0: a copy for every PSO, as before. + add_test(NAME d3d12_code_base_per_pso COMMAND d3d12_code_base_share_test --per-pso) + set_tests_properties(d3d12_code_base_per_pso PROPERTIES ENVIRONMENT "LEONIDA_SHARE_CODE_BASE=0") + set_tests_properties(d3d12_code_base_share d3d12_code_base_per_pso PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) # Conservative raster Tier 1, with geometric coverage bounds and host D3D12 references. set(LEONIDA_CONSERVATIVE_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_conservative.spv) set(LEONIDA_CONSERVATIVE_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative.spv) diff --git a/runtime/README.md b/runtime/README.md index cdce0a811d..6ec9cdc415 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -328,6 +328,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w |---|---|---| | `LEONIDA_LAZY_PIPELINES` | on | Graphics pipelines are built at their first draw. `0` builds each at `CreatePipelineState`, as before; the title creates far more pipelines at startup than it draws with. | | `LEONIDA_LAZY_COMPUTE` | on | Compute pipelines are built at the first dispatch that names them, or earlier by the warm-up thread. `0` builds each at `CreateComputePipelineState`. | +| `LEONIDA_SHARE_CODE_BASE` | on | The copy of a shader program that shaders read their code base from (`s_getpc_b64` and the constant tables in the program) is made once in the GPU address arena for all the PSOs of that program, compute and graphics, and goes back to the arena when the last of them is released. `0` gives every PSO a copy of its own, as before. | | `LEONIDA_ASYNC_MIN_BYTES` | unset | ``, with `LEONIDA_ASYNC_PIPELINES=1`: only a pipeline of n bytes of SPIR-V or more (compute: its module; graphics: all its stages) is built asynchronously, its draws or dispatches skipped until the compile worker has it; a smaller one is built where it is needed, as with asynchronous builds off, so small lighting and post programs are not skipped while the large ray-tracing ones compile. Unset or `0`: every pipeline is asynchronous. Text that is not a decimal number is ignored, with a log line. ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md), "Only the large ones asynchronous") | | `LEONIDA_ASYNC_MIN_BYTES_GRAPHICS` | unset | ``, with `LEONIDA_ASYNC_PIPELINES=1`: the threshold of `LEONIDA_ASYNC_MIN_BYTES` for graphics and mesh pipelines only (all their stages), so a draw can wait for a different size than a dispatch. `0`: every graphics pipeline is asynchronous (its draws skipped until built) while compute keeps `LEONIDA_ASYNC_MIN_BYTES`. Unset: graphics take `LEONIDA_ASYNC_MIN_BYTES`, as before the variable. Text that is not a decimal number is ignored, with a log line. ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md), "Only the large ones asynchronous") | | `LEONIDA_COMPUTE_WARMUP_MAX_BYTES` | `1048576` | The largest SPIR-V module, in bytes, the background warm-up thread (`LEONIDA_COMPUTE_WARMUP`) builds ahead of its first dispatch. Larger modules wait for that dispatch. | diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 2c948ff3d3..789fa8277d 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -393,6 +393,9 @@ bool device_sparse_buffer_tiles(ID3D12Device* device); // The size in bytes of the device's GPU address arena, or 0 without one. For tests. std::uint64_t device_arena_size(ID3D12Device* device); +// The bytes of the device's GPU address arena that hold shader programs now: the copies pipelines read their code +// base from. 0 without an arena. For tests. +std::uint64_t arena_shader_bytes(ID3D12Device* device); // Copies `bytes` of the device's GPU address arena at console VA `va` (what shaders read there: a heap's GPU copy, // the null slots after it) into `out`. False without an arena or when the range is not inside it. For tests. bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes); @@ -606,6 +609,9 @@ bool pipeline_stage_words(ID3D12PipelineState* pipeline, std::vector code_copies; // by the program's SHA-256, guarded by code_copy_mutex + + static bool share_code_copies() { + static const bool share = [] { + wchar_t v[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_SHARE_CODE_BASE", v, 2) == 1 && v[0] == L'0'); + }(); + return share; + } + + // Gives `offset` the console VA of a copy of `code`; false when the arena has no room for one. `key` is cleared + // when the copy is the PSO's own; code_copy_release takes the key as this left it. + bool code_copy_acquire(std::string& key, std::span code, VkDeviceSize& offset) { + if (!share_code_copies()) key.clear(); + if (key.empty()) { + if (!arena_allocate(code.size(), 256, offset, arena_shader)) return false; + std::memcpy(arena.mapped + offset, code.data(), code.size()); + return true; + } + std::lock_guard lock(code_copy_mutex); + const auto [it, made] = code_copies.try_emplace(key); + CodeCopy& copy = it->second; + if (made) { + if (!arena_allocate(code.size(), 256, copy.offset, arena_shader)) { + code_copies.erase(it); + return false; + } + std::memcpy(arena.mapped + copy.offset, code.data(), code.size()); + copy.bytes = code.size(); + } + ++copy.users; + offset = copy.offset; + return true; + } + + void code_copy_release(const std::string& key, VkDeviceSize offset, VkDeviceSize bytes) { + if (key.empty()) { + arena_release(offset, bytes, arena_shader); + return; + } + std::lock_guard lock(code_copy_mutex); + const auto it = code_copies.find(key); + if (it == code_copies.end() || --it->second.users) return; + arena_release(it->second.offset, it->second.bytes, arena_shader); + code_copies.erase(it); + } + // Console descriptor heaps (Xbox slot 14, docs/d3d12_vulkan.md section 3.4). The title gives the heap's address // itself: memory of its own, at a console VA the shaders would reach as heap_base + VA, past the arena. It fills // the heap through Create*View and CopyDescriptors, and also by writing 32-byte descriptor records into that @@ -12005,7 +12065,7 @@ class PipelineState final for (const auto& [unbound, built] : variants_) vk.vkDestroyPipeline(dev, built, nullptr); if (graphics_.layout) vk.vkDestroyPipelineLayout(dev, graphics_.layout, nullptr); modules_.clear(); - if (code_bytes_) device_.arena_release(code_base_, code_bytes_, DeviceState::arena_shader); + if (code_bytes_) device_.code_copy_release(code_key_, code_base_, code_bytes_); --live_pipeline_state_count; } @@ -12165,6 +12225,12 @@ class PipelineState final const std::vector& subgroup_requests() const { return native_owner_ ? native_owner_->subgroup_requests() : subgroup_requests_; } + // The program copy its shaders read their code base from: the console VA replay pushes, and its bytes (0: none). + std::uint64_t code_copy_va() const { + if (native_owner_) return native_owner_->code_copy_va(); + return is_graphics_ ? graphics_.code_base : pipeline_.code_base; + } + VkDeviceSize code_copy_bytes() const { return native_owner_ ? native_owner_->code_copy_bytes() : code_bytes_; } // A VS (+ GS) (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the // VS's input signature by semantic name and index: location = the element's register, the translator's rule @@ -12954,9 +13020,11 @@ class PipelineState final graphics_.estimate = leonida::large_module_estimate(spirv_bytes); if (code_stage) { + // One copy per program, shared with the other PSOs of it (DeviceState::code_copy_acquire): the entry's + // key is the SHA-256 of these bytes, which the lookup above matched. + code_key_ = code_stage->entry->fssm_sha256; VkDeviceSize offset = 0; - if (!device_.arena_allocate(code_stage->fssm.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY; - std::memcpy(device_.arena.mapped + offset, code_stage->fssm.data(), code_stage->fssm.size()); + if (!device_.code_copy_acquire(code_key_, code_stage->fssm, offset)) return E_OUTOFMEMORY; code_bytes_ = code_stage->fssm.size(); code_base_ = offset; graphics_.code_base = offset; @@ -13127,8 +13195,11 @@ class PipelineState final // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). if (entry->uses_code_base || !entry->code_base_known) { const auto& code = program.bytes; - if (!device_.arena_allocate(code.size(), 256, code_base_, DeviceState::arena_shader)) return E_OUTOFMEMORY; - std::memcpy(device_.arena.mapped + code_base_, code.data(), code.size()); + // One copy per program, shared with the other PSOs of it (DeviceState::code_copy_acquire): the entry's + // key is the SHA-256 of these bytes, which program_candidates matched. + code_key_ = program.kind == leonida::ComputeProgram::Kind::fssm ? entry->fssm_sha256 + : entry->fspx_code_sha256; + if (!device_.code_copy_acquire(code_key_, code, code_base_)) return E_OUTOFMEMORY; code_bytes_ = code.size(); pipeline_.code_base = code_base_; } @@ -13808,6 +13879,7 @@ class PipelineState final } VkDeviceSize code_base_ = 0; VkDeviceSize code_bytes_ = 0; + std::string code_key_; // the program's key in DeviceState::code_copies; empty when the copy is this PSO's own bool registered_ = false; bool unregistered_ = false; // taken out of the context's registry (unregister) bool is_graphics_ = false; @@ -21838,6 +21910,14 @@ bool pipeline_stage_words(ID3D12PipelineState* pipeline, std::vector(pipeline); + if (!p || !p->code_copy_bytes()) return false; + va = p->code_copy_va(); + bytes = p->code_copy_bytes(); + return true; +} + bool write_placed_buffer_view(ID3D12Device* device, bool unordered, const void* view, std::uint64_t address, std::uint64_t width, D3D12_CPU_DESCRIPTOR_HANDLE destination) { Device* d = Device::from(device); @@ -22131,6 +22211,16 @@ std::uint64_t device_arena_size(ID3D12Device* device) { return d ? d->state().arena.size : 0; } +std::uint64_t arena_shader_bytes(ID3D12Device* device) { + if (!device) return 0; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + if (!real) real = device; + Device* d = Device::from(real); + if (!d) return 0; + std::lock_guard lock(d->state().arena.mutex); + return d->state().arena.use_in_use[DeviceState::arena_shader]; +} + ImageMemoryStats image_memory_stats(ID3D12Device* device) { if (!device) return {}; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); diff --git a/runtime/test/d3d12_code_base_share_test.cpp b/runtime/test/d3d12_code_base_share_test.cpp new file mode 100644 index 0000000000..2f9298b5af --- /dev/null +++ b/runtime/test/d3d12_code_base_share_test.cpp @@ -0,0 +1,282 @@ +// The arena copies of the programs shaders read their code base from (s_getpc_b64 and the constant tables in the +// shader's own FSSM program, docs/design.md): the PSOs made from one program share one copy, which lives while any of +// them does. Through the Vulkan device alone, with hand-built programs and GLSL modules written to the translator's +// contract: +// - four compute PSOs of program A (uses_code_base: true) take A's bytes of the arena once, and all four read their +// code base at the same console VA, where A's bytes are; +// - a PSO of program B takes B's bytes at another VA; one of program C, whose index entry has no uses_code_base key +// (an index from before the key, whose shader may read its code base), takes C's; one of program D +// (uses_code_base: false) takes none; +// - two graphics PSOs whose pixel shader is program E (uses_code_base: true), with different blend states, take E's +// bytes once; +// - releasing three of the four A PSOs keeps A's copy, its bytes intact, for the fourth; releasing that one returns +// A's bytes, and a new A PSO makes a new copy. +// With --per-pso (LEONIDA_SHARE_CODE_BASE=0) every PSO has a copy of its own, as before the copies were shared. +// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_CS_SPV +#error "LEONIDA_TEST_CS_SPV must name the compiled compute test shader" +#endif +#if !defined(LEONIDA_TEST_VS_FULLSCREEN_SPV) || !defined(LEONIDA_TEST_PS_SPV) +#error "LEONIDA_TEST_VS_FULLSCREEN_SPV and LEONIDA_TEST_PS_SPV must name the compiled draw test shaders" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; + +namespace { + +// An FSSM program of `words` dwords after the magic, each distinct, so two programs of one seed and size are equal +// and any other two differ. +std::vector program(std::uint32_t seed, std::uint32_t words) { + std::vector out = {'F', 'S', 'S', 'M'}; + for (std::uint32_t i = 0; i < words; ++i) put32(out, seed + i); + return out; +} + +// A copy's console VA and bytes, or {0, 0} when the PSO has none. +struct Copy { + std::uint64_t va = 0, bytes = 0; +}; +Copy copy_of(ID3D12PipelineState* pso) { + Copy c; + if (!rt::d3d12::pipeline_code_base(pso, c.va, c.bytes)) return {}; + return c; +} + +// True when the arena holds `expected` at `va`. +bool arena_holds(ID3D12Device* device, std::uint64_t va, const std::vector& expected) { + std::vector got(expected.size()); + return rt::d3d12::read_arena(device, va, got.data(), got.size()) && got == expected; +} + +// A released PSO whose pipeline a compile worker is building (the warm-up thread builds compute ones ahead of their +// first dispatch) is deleted when that build returns (PipelineState::last_release), and its copy goes with it. Waits +// up to 60 s for the PSOs not yet deleted to be `live`. +bool settle(long live) { + for (int i = 0; i < 6000 && rt::d3d12::live_pipeline_states() != live; ++i) Sleep(10); + return rt::d3d12::live_pipeline_states() == live; +} + +std::string entry(const char* name, const char* stage, const std::vector& fssm, const char* extra) { + return std::string("\"") + name + "\": {\"stage\": \"" + stage + "\", \"fssm_sha256\": \"" + + leonida::sha256_hex(fssm) + "\", \"bindings\": [], \"push_constant_bytes\": 144" + extra + "}"; +} + +} // namespace + +int main(int argc, char** argv) { + const bool per_pso = argc == 2 && std::strcmp(argv[1], "--per-pso") == 0; + if (argc != 1 && !per_pso) { + std::fputs("usage: d3d12_code_base_share_test [--per-pso]\n", stderr); + return 2; + } + if (per_pso) { + char value[4] = {}; + if (GetEnvironmentVariableA("LEONIDA_SHARE_CODE_BASE", value, sizeof value) != 1 || value[0] != '0') { + std::fputs("--per-pso needs LEONIDA_SHARE_CODE_BASE=0\n", stderr); + return 2; + } + } + + // The programs, of distinct sizes so each count below has one reading, and the index that maps them to modules. + const auto a = program(0x41000000u, 1000), b = program(0x42000000u, 600), c = program(0x43000000u, 300), + d = program(0x44000000u, 200), e = program(0x45000000u, 500), vs = program(0x56000000u, 8); + const testfiles::ScratchDir scratch("leonida_code_base_share_test"); + const auto& library = scratch.path(); + // The pipeline cache and journal of the warm-up's builds go to the scratch folder, not the working directory. + if (!GetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", nullptr, 0)) + EXPECT(SetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", (library / "cache").c_str())); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_a.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_b.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_c.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_d.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_FULLSCREEN_SPV), library / "vs_e.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_e.spv")); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{" << entry("cs_a", "cs", a, ", \"local_size\": [64, 1, 1], \"uses_code_base\": true") << ",\n " + << entry("cs_b", "cs", b, ", \"local_size\": [64, 1, 1], \"uses_code_base\": true") << ",\n " + << entry("cs_c", "cs", c, ", \"local_size\": [64, 1, 1]") << ",\n " + << entry("cs_d", "cs", d, ", \"local_size\": [64, 1, 1], \"uses_code_base\": false") << ",\n " + << entry("vs_e", "vs", vs, ", \"input_signature\": []") << ",\n " + << entry("ps_e", "ps", e, ", \"outputs\": [0], \"uses_code_base\": true") << "}"; + index.close(); + EXPECT(index); + } + // The index as the runtime reads it: C's entry has no uses_code_base key, so its use is not known. + { + leonida::ShaderLibrary check; + EXPECT(check.load(library.string())); + const auto* entry_c = check.find("cs", leonida::sha256_hex(c)); + EXPECT(entry_c && !entry_c->code_base_known && !entry_c->uses_code_base); + const auto* entry_d = check.find("cs", leonida::sha256_hex(d)); + EXPECT(entry_d && entry_d->code_base_known && !entry_d->uses_code_base); + } + + { + vktest::Device vk; + vk.request_buffer_device_address = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(status == vktest::DeviceStatus::ready); + if (!vk.buffer_device_address) { + std::puts("SKIP: the device lacks bufferDeviceAddress, which the GPU address arena needs"); + return 77; + } + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.buffer_device_address = vk.buffer_device_address; + info.subgroup = vk.subgroup; + info.shader_dir = library.string(); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + if (rt::d3d12::device_push_constants_need_fallback(device.p)) { + std::printf("SKIP: the PSOs need 144 push-constant bytes and this GPU has %u\n", + rt::d3d12::device_max_push_constants_size(device.p)); + return 77; + } + EXPECT(rt::d3d12::device_arena_size(device.p) > 0); + EXPECT(rt::d3d12::live_pipeline_states() == 0); // settle() counts this test's PSOs only + const std::uint64_t before = rt::d3d12::arena_shader_bytes(device.p); + const auto used = [&] { return rt::d3d12::arena_shader_bytes(device.p) - before; }; + + // Root signatures: one root UAV for compute; two constants and a root CBV for the draw shaders. + D3D12_ROOT_PARAMETER uav{}; + uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC compute_root_desc{}; + compute_root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + compute_root_desc.Desc_1_0 = {1, &uav, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + D3D12_ROOT_PARAMETER draw_params[2] = {}; + draw_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + draw_params[0].Constants = {0, 0, 2}; + draw_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + draw_params[1].Descriptor = {1, 0}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC draw_root_desc{}; + draw_root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + draw_root_desc.Desc_1_0 = {2, draw_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + Ref compute_root, draw_root; + for (auto [desc, root] : {std::pair{&compute_root_desc, &compute_root}, std::pair{&draw_root_desc, &draw_root}}) { + const auto blob = serialize_root_signature(*desc); + EXPECT(!blob.empty()); + EXPECT(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root->p)))); + } + + const auto container_a = shader_container(a), container_b = shader_container(b), + container_c = shader_container(c), container_d = shader_container(d), + container_e = shader_container(e), container_vs = shader_container(vs); + const auto make_compute = [&](const std::vector& container, Ref& pso) { + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = compute_root.p; + desc.CS = {container.data(), container.size()}; + return SUCCEEDED(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso.p))) && pso.p; + }; + const auto make_graphics = [&](bool blend, Ref& pso) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = draw_root.p; + desc.VS = {container_vs.data(), container_vs.size()}; + desc.PS = {container_e.data(), container_e.size()}; + auto& target = desc.BlendState.RenderTarget[0]; + target.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + if (blend) { + target.BlendEnable = TRUE; + target.SrcBlend = target.SrcBlendAlpha = D3D12_BLEND_ONE; + target.DestBlend = target.DestBlendAlpha = D3D12_BLEND_ONE; + target.BlendOp = target.BlendOpAlpha = D3D12_BLEND_OP_ADD; + } + desc.SampleMask = 0xffffffff; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + return SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p))) && pso.p; + }; + const std::uint64_t copies = per_pso ? 4 : 1; // of A while four PSOs of it live + const std::uint64_t draw_copies = per_pso ? 2 : 1; + + // Four PSOs of A: one copy of A's bytes, at one VA, which all four push as their code base. + Ref pso_a[4]; + for (auto& pso : pso_a) EXPECT(make_compute(container_a, pso)); + std::printf("4 compute PSOs of one %zu-byte program: %llu bytes of the arena hold program copies\n", a.size(), + static_cast(used())); + EXPECT(used() == copies * a.size()); + const Copy first = copy_of(pso_a[0].p); + EXPECT(first.bytes == a.size()); + for (const auto& pso : pso_a) { + const Copy copy = copy_of(pso.p); + EXPECT(copy.bytes == a.size() && arena_holds(device.p, copy.va, a)); + EXPECT(per_pso ? (&pso == &pso_a[0] || copy.va != first.va) : copy.va == first.va); + } + + // B: a copy of its own, elsewhere. C: copied too, since its entry does not say. D: no copy. + Ref pso_b, pso_c, pso_d; + EXPECT(make_compute(container_b, pso_b) && make_compute(container_c, pso_c) && make_compute(container_d, pso_d)); + const Copy copy_b = copy_of(pso_b.p), copy_c = copy_of(pso_c.p); + EXPECT(copy_b.bytes == b.size() && copy_b.va != first.va && arena_holds(device.p, copy_b.va, b)); + EXPECT(copy_c.bytes == c.size() && arena_holds(device.p, copy_c.va, c)); + EXPECT(copy_of(pso_d.p).bytes == 0); + EXPECT(used() == copies * a.size() + b.size() + c.size()); + + // Two graphics PSOs whose pixel shader reads its code base: one copy of E's bytes (one per PSO with --per-pso), + // none of the VS's. + Ref draw[2]; + EXPECT(make_graphics(false, draw[0]) && make_graphics(true, draw[1])); + const Copy draw_copy = copy_of(draw[0].p), draw_copy2 = copy_of(draw[1].p); + EXPECT(draw_copy.bytes == e.size() && arena_holds(device.p, draw_copy.va, e)); + EXPECT(draw_copy2.bytes == e.size() && arena_holds(device.p, draw_copy2.va, e)); + EXPECT(per_pso ? draw_copy2.va != draw_copy.va : draw_copy2.va == draw_copy.va); + EXPECT(used() == copies * a.size() + b.size() + c.size() + draw_copies * e.size()); + draw[0].reset(); + EXPECT(settle(8) && arena_holds(device.p, draw_copy2.va, e)); + draw[1].reset(); + EXPECT(settle(7) && used() == copies * a.size() + b.size() + c.size()); + + // Three of A's PSOs go: the fourth keeps its copy, A's bytes still where it reads them. + const Copy last = copy_of(pso_a[3].p); + for (int i = 0; i < 3; ++i) pso_a[i].reset(); + EXPECT(settle(4) && used() == a.size() + b.size() + c.size()); + EXPECT(copy_of(pso_a[3].p).va == last.va && arena_holds(device.p, last.va, a)); + // The last one goes: A's bytes are returned to the arena. + pso_a[3].reset(); + EXPECT(settle(3) && used() == b.size() + c.size()); + // A new PSO of A makes a new copy, which holds A's bytes. + Ref again; + EXPECT(make_compute(container_a, again)); + EXPECT(used() == a.size() + b.size() + c.size() && arena_holds(device.p, copy_of(again.p).va, a)); + again.reset(); + pso_b.reset(); + pso_c.reset(); + pso_d.reset(); + EXPECT(settle(0) && used() == 0); + std::printf("%s: 4 PSOs of one program held %llu copies, 2 graphics PSOs %llu; all bytes returned\n", + per_pso ? "per PSO (LEONIDA_SHARE_CODE_BASE=0)" : "shared", static_cast(copies), + static_cast(draw_copies)); + } + EXPECT(vktest::validation_error_count() == 0); // includes device teardown + std::puts("d3d12_code_base_share_test: PASS"); + return 0; +} From 0711e4d22c62ed94ecfd85b25330905e90cbd7ed Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:46:33 +0100 Subject: [PATCH 12/49] d3d12: a title vertex or index view keeps only a buffer that covers it (RT-TITLE-BUFFER-FALLBACK) make_title_buffer makes a buffer over the title's pages the way slot 133 does: the pages imported, or a shadow copied from them. When both fail (no import, the arena full, no host-visible memory left), create_at_host_address still answers S_OK with an ordinary DEFAULT buffer that has neither the title's VA nor its bytes. make_title_buffer only checked FAILED(hr), so it kept that buffer until the device went and counted it against LEONIDA_TITLE_BUFFERS_MB. The view stayed uncovered, so the next IASetVertexBuffers or IASetIndexBuffer of the same view made another one (each with its own memory, zero fill and device reference), until the cap was used up; after that no new title view was resolved for the rest of the session, even once the memory was back. A buffer is now kept and counted only when the context knows a buffer at the view's address afterwards (knows_buffer_va over the backed prefix, as the check before it). Otherwise it is released, and its range is remembered for a second (refused_title_ranges_, by start, pruned of expired entries at 256), so the binds in between return without trying again. A range whose buffer could not be made at all is remembered the same way. d3d12_title_buffer_fallback_test fills a 16 MiB arena, refuses host-visible allocations behind the instance-proc pointer it hands the layer and runs with LEONIDA_SLOT133_IMPORT=0, then binds one 2 MiB title view 16 times as vertex and index views. Before: 16 buffers kept, 32 buffers of the view's size created. Now: none kept, 2 created (by the first bind), and after the retry delay one more try, still nothing kept. --- runtime/CMakeLists.txt | 9 + runtime/README.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 37 ++- .../test/d3d12_title_buffer_fallback_test.cpp | 217 ++++++++++++++++++ 4 files changed, 261 insertions(+), 4 deletions(-) create mode 100644 runtime/test/d3d12_title_buffer_fallback_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..5377ebfb63 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2983,6 +2983,15 @@ if(TARGET Vulkan::Headers) set_tests_properties(xbox_linear_texture_map PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30 ENVIRONMENT "LEONIDA_LINEAR_MAP_FIRST=1") set_tests_properties(d3d12_xmem_placed PROPERTIES SKIP_RETURN_CODE 77) + # A vertex or index view of title memory that can be neither imported nor shadowed keeps no stand-in buffer and is + # tried again after a delay, not at every bind. + add_executable(d3d12_title_buffer_fallback_test test/d3d12_title_buffer_fallback_test.cpp) + target_link_libraries(d3d12_title_buffer_fallback_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_title_buffer_fallback_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_title_buffer_fallback_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_title_buffer_fallback COMMAND d3d12_title_buffer_fallback_test) + set_tests_properties(d3d12_title_buffer_fallback PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 + ENVIRONMENT "LEONIDA_SLOT133_IMPORT=0;LEONIDA_ARENA_MB=16") # Fences and timing (D3D-30): multiple-fence waits, clock calibration, adapter LUID, custom heap properties. add_executable(d3d12_fence_timing_test test/d3d12_fence_timing_test.cpp) diff --git a/runtime/README.md b/runtime/README.md index cdce0a811d..ed31c1a5b9 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -351,7 +351,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TITLE_TEXTURE_FILL_MB` | `32` | How many MiB of changed textures one pass fills again; the rest waits for the next pass. | | `LEONIDA_TEXTURE_HASH_BUDGET_US` | `400` | Microseconds a pass may spend hashing before it stops at a texture boundary. `0` leaves the byte budget alone to bound it. | | `LEONIDA_TEXTURE_SWEEP_BUDGET_US` | `400` | Microseconds a pass may spend on residency checks and uploads between textures. | -| `LEONIDA_TITLE_BUFFERS_MB` | `512` | The most memory, in MiB, of buffers made over the title's own memory for vertex and index views that name it. | +| `LEONIDA_TITLE_BUFFERS_MB` | `512` | The most memory, in MiB, of buffers made over the title's own memory for vertex and index views that name it. Only a buffer that covers its view (the pages imported or shadowed) is kept and counted; a view whose pages got neither is tried again a second later. | | `LEONIDA_TITLE_BUFFER_COVERAGE` | on | Such a view counts as covered only when a known buffer spans all its bytes. `0` asks for the first byte only. | | `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh, as before unchanged generations were skipped. | | `LEONIDA_STRICT_REPLAY` | unset | *Diagnostic.* `1` makes a draw or dispatch with an unresolvable resource fail its command list (`src/vulkan_replay.h`); by default it is dropped and logged. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 748d6144a5..100575c183 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -19608,7 +19608,8 @@ class Device final // TitleVaAliases::want_buffer: a vertex or index view names `va` in the title's own memory and no buffer covers // it. A buffer over the 64 KiB-aligned committed pages around it is made the way slot 133 makes one (the pages // imported, or a shadow copied from them before every submission) and kept until the device goes, up to - // LEONIDA_TITLE_BUFFERS_MB (512 by default). + // LEONIDA_TITLE_BUFFERS_MB (512 by default). Only a buffer that covers the view is kept; a range that got none is + // not tried again for a second (refused_title_ranges_). void make_title_buffer(std::uint64_t va, std::uint64_t bytes) { if (!&context()) return; static const bool check_size = [] { @@ -19648,6 +19649,13 @@ class Device final } // If the request runs into an uncommitted page or the size limit, reuse its backed prefix. if (end <= va || (check_size && state_.context->knows_buffer_va(va, end - va))) return; + // The title binds the same views draw after draw: a range whose buffer could not be made a moment ago waits + // for its retry time instead of being tried (and its buffers made and let go) at every bind. + const auto now = std::chrono::steady_clock::now(); + if (const auto refused = refused_title_ranges_.find(start); refused != refused_title_ranges_.end()) { + if (end <= refused->second.end && now < refused->second.retry) return; + refused_title_ranges_.erase(refused); + } if (title_buffer_bytes_ + (end - start) > cap) { log_once("vertex or index data in the title's memory is past LEONIDA_TITLE_BUFFERS_MB, left unresolved; MiB so far:", int(title_buffer_bytes_ >> 20)); @@ -19665,8 +19673,24 @@ class Device final const HRESULT hr = create_at_host_address(reinterpret_cast(static_cast(start)), desc, 0xFFFFFFFFu, __uuidof(ID3D12Resource), reinterpret_cast(&made), nullptr); - if (FAILED(hr) || !made) { - log_once("a buffer over the title's memory for a vertex or index view could not be made; HRESULT", int(hr)); + // When the pages can be neither imported nor shadowed, slot 133 answers with an ordinary DEFAULT buffer that + // has neither the title's VA nor its bytes (create_at_host_address). It does not cover the view, so keeping it + // would only hold its memory until the device goes and make another at the next bind of the same view, until + // LEONIDA_TITLE_BUFFERS_MB is used up. It is let go, and the range is tried again a second later, when the + // memory may be back. + const bool kept = SUCCEEDED(hr) && made && state_.context->knows_buffer_va(va, check_size ? end - va : 1); + if (!kept) { + if (SUCCEEDED(hr) && made) + log_once("a buffer over the title's memory for a vertex or index view could get neither an import nor " + "a shadow, so none is kept; KiB", + int((end - start) >> 10)); + else + log_once("a buffer over the title's memory for a vertex or index view could not be made; HRESULT", + int(hr)); + if (made) made->Release(); + if (refused_title_ranges_.size() >= 256) + std::erase_if(refused_title_ranges_, [&](const auto& refused) { return refused.second.retry <= now; }); + refused_title_ranges_[start] = {end, now + std::chrono::seconds(1)}; return; } title_buffers_.push_back(made); @@ -19682,6 +19706,13 @@ class Device final std::mutex title_buffer_mutex_; std::vector title_buffers_; // kept: the title's views name their addresses frame after frame std::uint64_t title_buffer_bytes_ = 0; + // Ranges [start, end) that got no buffer, by start, with when they may be tried again. Under title_buffer_mutex_; + // the entries past their time are dropped once there are 256. + struct RefusedTitleRange { + std::uint64_t end; + std::chrono::steady_clock::time_point retry; + }; + std::map refused_title_ranges_; HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear) { diff --git a/runtime/test/d3d12_title_buffer_fallback_test.cpp b/runtime/test/d3d12_title_buffer_fallback_test.cpp new file mode 100644 index 0000000000..9a6c380dbb --- /dev/null +++ b/runtime/test/d3d12_title_buffer_fallback_test.cpp @@ -0,0 +1,217 @@ +// A vertex or index view that names the title's own memory gets a buffer made over those pages (make_title_buffer, +// TitleVaAliases::want_buffer), the way slot 133 makes one: the pages imported, or a shadow copied from them. When +// neither can be made, slot 133's last resort is an ordinary DEFAULT buffer, which has neither the title's VA nor its +// bytes. A view must not keep such a buffer: it does not cover the view, so the next IASetVertexBuffers of the same +// view would make another, each holding device memory and a device reference until the device goes, until +// LEONIDA_TITLE_BUFFERS_MB is used up and no new title view is resolved for the rest of the session. +// - The arena is filled first (LEONIDA_ARENA_MB=16, so a few 1 MiB buffers do it) and host-visible allocations are +// refused (the test wraps vkAllocateMemory behind the instance-proc pointer it hands the layer), with +// LEONIDA_SLOT133_IMPORT=0: no import and no shadow can be made, but a device-local DEFAULT buffer can. +// - The same 2 MiB view of title memory bound 16 times, as vertex and index views, keeps no buffer (every buffer +// made over title memory holds a device reference, and the device's count does not grow) and is tried once (the +// buffers of its size created by the first bind are all there are). +// - Once the retry delay has passed, the next bind tries the view again (as many buffers of its size created as by +// the first bind) and the binds after it do not, and still nothing is kept. +// Needs a device-local memory type that is not host-visible (skipped otherwise). Synthetic data only. Set +// LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../src/title_va_alias.h" + +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +// The Vulkan calls the layer makes, seen through the function pointers it loads. +PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; +PFN_vkGetDeviceProcAddr real_device_proc = nullptr; +PFN_vkAllocateMemory real_allocate = nullptr; +PFN_vkCreateBuffer real_create_buffer = nullptr; +VkPhysicalDeviceMemoryProperties memory{}; +std::atomic refuse_host_visible{false}; +std::atomic watched_size{0}; +std::atomic watched_buffers{0}; // buffers of watched_size created + +VKAPI_ATTR VkResult VKAPI_CALL allocate(VkDevice device, const VkMemoryAllocateInfo* info, + const VkAllocationCallbacks* allocator, VkDeviceMemory* out) { + if (refuse_host_visible.load() && info->memoryTypeIndex < memory.memoryTypeCount && + (memory.memoryTypes[info->memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + return real_allocate(device, info, allocator, out); +} + +VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice device, const VkBufferCreateInfo* info, + const VkAllocationCallbacks* allocator, VkBuffer* buffer) { + if (info->size == watched_size.load()) ++watched_buffers; + return real_create_buffer(device, info, allocator, buffer); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) { + if (std::strcmp(name, "vkAllocateMemory") == 0) { + real_allocate = reinterpret_cast(real_device_proc(device, name)); + return real_allocate ? reinterpret_cast(&allocate) : nullptr; + } + if (std::strcmp(name, "vkCreateBuffer") == 0) { + real_create_buffer = reinterpret_cast(real_device_proc(device, name)); + return real_create_buffer ? reinterpret_cast(&create_buffer) : nullptr; + } + return real_device_proc(device, name); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetDeviceProcAddr") == 0) { + real_device_proc = reinterpret_cast(real_instance_proc(instance, name)); + return real_device_proc ? reinterpret_cast(&device_proc) : nullptr; + } + return real_instance_proc(instance, name); +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return desc; +} + +// The device's reference count: every buffer the device keeps over title memory holds one. +ULONG references(ID3D12Device* device) { + device->AddRef(); + return device->Release(); +} + +} // namespace + +int main() { + vktest::Device vk; + if (!vk.create()) return 77; + real_instance_proc = vk.instance_proc; + reinterpret_cast( + vk.instance_proc(vk.instance, "vkGetPhysicalDeviceMemoryProperties"))(vk.physical, &memory); + bool device_only = false; + for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) + device_only |= (memory.memoryTypes[i].propertyFlags & + (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) == + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + if (!device_only) { + std::fprintf(stderr, "SKIP: every device-local memory type is host-visible\n"); + return 77; + } + + constexpr UINT title_bytes = 2u << 20; + auto& aliases = leonida::title_va_aliases(); + void* pages = VirtualAlloc(nullptr, title_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(pages); + const auto title_va = reinterpret_cast(pages); + aliases.add_title_memory(title_va, title_bytes); + int result = 0; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = &instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.buffer_device_address = true; + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + const std::uint64_t arena = rt::d3d12::device_arena_size(device.p); + if (!arena) { + std::fprintf(stderr, "SKIP: the device has no GPU address arena\n"); + result = 77; + } else { + // Fill the arena: a 1 MiB buffer that is not given an arena VA found no room there, so a 2 MiB shadow + // will not find any either. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC filler_desc = buffer_desc(1u << 20); + std::vector> fillers(arena >> 20); + bool full = false; + for (auto& filler : fillers) { + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &filler_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&filler.p)))); + if ((full = filler->GetGPUVirtualAddress() >= arena)) break; + } + EXPECT(full); + + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + const D3D12_VERTEX_BUFFER_VIEW vertices{title_va, title_bytes, 16}; + const D3D12_INDEX_BUFFER_VIEW indices{title_va, title_bytes, DXGI_FORMAT_R16_UINT}; + const auto bind = [&](unsigned i) { + if (i & 1) list->IASetIndexBuffer(&indices); + else list->IASetVertexBuffers(0, 1, &vertices); + }; + + // No import, no shadow: nothing over the title's pages is kept, and the view is tried once. + const ULONG before = references(device.p); + watched_size = title_bytes; + refuse_host_visible = true; + bind(0); + const unsigned first = watched_buffers.load(); + for (unsigned i = 1; i < 16; ++i) bind(i); + const ULONG refused = references(device.p); + const unsigned tried = watched_buffers.load(); + std::printf("16 binds with no import or shadow: %lu buffers kept, %u buffers of the view's size created " + "(%u by the first bind)\n", + refused - before, tried, first); + EXPECT(first >= 1); + EXPECT(refused == before); + EXPECT(tried == first); + EXPECT(aliases.shader_va(title_va) == title_va); + + // After the retry delay the next bind tries the view again, once. Host-visible memory is still refused + // here: a buffer the device keeps over title memory holds a reference to it, so the device would never be + // destroyed, and its Vulkan objects would be reported as leaked under the validation layer. + Sleep(1500); + bind(0); + const unsigned retried = watched_buffers.load(); + for (unsigned i = 1; i < 8; ++i) bind(i); + const unsigned again = watched_buffers.load(); + refuse_host_visible = false; + const ULONG after = references(device.p); + std::printf("after the retry delay: %u buffers of the view's size created by the next bind, %u by 7 " + "further binds, %lu buffers kept\n", + retried - tried, again - retried, after - before); + EXPECT(retried == tried + first); + EXPECT(again == retried); + EXPECT(after == before); + EXPECT(SUCCEEDED(list->Close())); + } + } + aliases.remove_title_memory(title_va); + VirtualFree(pages, 0, MEM_RELEASE); + if (vk.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", vk.validation_errors()); + return 1; + } + if (!result) std::printf("ok\n"); + return result; +} From e95d5fa4cac088b89f72fae405013c4c661b0457 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:50:06 +0100 Subject: [PATCH 13/49] d3d12: a shape whose shared zero image could not be made is tried again (RT-ZERO-IMAGES-RETRY) A sampled BC texture placed on the title's memory waits for memory of its own, and its views name one shared, zeroed image of its exact shape (DeviceState::zero_sampled_image). When that image could not be made (create_texture failed, as it does under VRAM pressure, or the image lost its host-transfer usage after its memory was refused), the shape was stored as null in zero_images for the device's life: every later placement of it took memory of its own at once, for the rest of the session, even after the pressure had passed. Such a failure is now remembered in zero_image_retry with a time a second later: placements of the shape before then do not try again (each try makes an image and asks for its memory), and the first one after it does. A shape whose image would pass the 256 MiB the shared images may take still stays null: those images are never released, so it stays past the limit. d3d12_zero_image_retry_test refuses the next vkCreateImage of one BC1 shape behind the instance-proc pointer it hands the layer (the shared image, made before the placement's own), on a device without host image copies so that the shape takes a shared image at all. Before: after the delay a third placement still had memory of its own (one image of the shape made for it). Now it is shared (two made: the shared image and its own). --- runtime/CMakeLists.txt | 7 + runtime/shims/d3d12_vulkan_device.cpp | 22 ++- runtime/test/d3d12_zero_image_retry_test.cpp | 157 +++++++++++++++++++ 3 files changed, 183 insertions(+), 3 deletions(-) create mode 100644 runtime/test/d3d12_zero_image_retry_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..799d2aeffc 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2967,6 +2967,13 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_existing_heap_write_watch COMMAND d3d12_existing_heap_test) set_tests_properties(d3d12_existing_heap_write_watch PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_WRITE_WATCH=1") + # A placed BC texture's shape whose shared zero image could not be made gets one at a later placement. + add_executable(d3d12_zero_image_retry_test test/d3d12_zero_image_retry_test.cpp) + target_link_libraries(d3d12_zero_image_retry_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_zero_image_retry_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_zero_image_retry_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_zero_image_retry COMMAND d3d12_zero_image_retry_test) + set_tests_properties(d3d12_zero_image_retry PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) # Slot 133 on untouched xmem physical pages: committed through the pages hook, then imported. xmem.cpp and # registry.cpp are compiled in, as xmem_test does, to reach the registered XMem* exports. add_executable(d3d12_xmem_placed_test test/d3d12_xmem_placed_test.cpp shims/xmem.cpp shims/registry.cpp) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 748d6144a5..0eb6445a8d 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -7725,7 +7725,9 @@ struct DeviceState { std::unordered_map pending_image_keys; using ZeroShape = std::tuple; std::mutex zero_image_mutex; - std::map zero_images; + std::map zero_images; // null: past the 256 MiB the shared images may take + // Shapes whose image could not be made, with when to try again (zero_sampled_image). Under zero_image_mutex. + std::map zero_image_retry; std::atomic zero_image_bytes{0}; VkImage zero_sampled_image(const D3D12_RESOURCE_DESC&, const Format&, VkDeviceSize); std::multimap image_keys; // by the texture's address @@ -10757,13 +10759,27 @@ VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Form const ZeroShape key{d.Format, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels}; std::lock_guard lock(zero_image_mutex); if (auto it = zero_images.find(key); it != zero_images.end()) return it->second ? it->second->image() : VK_NULL_HANDLE; + // A shape whose image could not be made is tried again a second later. Under VRAM pressure create_texture fails, + // or its image loses host-transfer usage: a shape left without an image for good would have every later placement + // of it take memory of its own for the rest of the session, and one tried at every placement would make an image + // and ask for its memory each time. + const auto now = std::chrono::steady_clock::now(); + if (auto it = zero_image_retry.find(key); it != zero_image_retry.end()) { + if (now < it->second) return VK_NULL_HANDLE; + zero_image_retry.erase(it); + } constexpr VkDeviceSize limit = 256ull << 20; const auto used = zero_image_bytes.load(std::memory_order_relaxed); if (used >= limit || bytes > limit - used) return VK_NULL_HANDLE; const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; auto* zero = new Resource(*this, d, heap, D3D12_HEAP_FLAG_NONE); - if (FAILED(zero->create_texture(format)) || (copy_memory_to_image && !zero->host_initialized_image()) || - zero->image_backing_bytes() > limit - used) { + if (FAILED(zero->create_texture(format)) || (copy_memory_to_image && !zero->host_initialized_image())) { + zero->Release(); + zero_image_retry[key] = now + std::chrono::seconds(1); + return VK_NULL_HANDLE; + } + // The shared images are never released, so a shape past the limit stays past it. + if (zero->image_backing_bytes() > limit - used) { zero->Release(); zero_images.emplace(key, nullptr); return VK_NULL_HANDLE; diff --git a/runtime/test/d3d12_zero_image_retry_test.cpp b/runtime/test/d3d12_zero_image_retry_test.cpp new file mode 100644 index 0000000000..964473a4f3 --- /dev/null +++ b/runtime/test/d3d12_zero_image_retry_test.cpp @@ -0,0 +1,157 @@ +// A sampled BC texture the title places on its own memory (Xbox device slot 133) waits for memory of its own until +// the title writes it or a command uses it; until then its views name one shared, zeroed image of its exact shape +// (DeviceState::zero_sampled_image), kept for the device's life. Under VRAM pressure that image cannot always be made +// (vkCreateImage or its memory refused). Such a shape must get its shared image at a later placement once the memory is +// back, not stay without one for the whole session, every placement of it taking memory of its own at once. +// - A control shape gets its shared image (the placement has no memory of its own), or the test is skipped. +// - The test wraps vkCreateImage behind the instance-proc pointer it hands the layer and refuses the next image of +// the shape under test: that is the shared image, made before the placement's own. That placement, and one right +// after it, have memory of their own: the shape is not tried again at every placement. +// - After the retry delay, a third placement of the shape gets its shared image (no memory of its own): two images +// of the shape are made for it, the shared one and the placement's. +// The device has no host image copies, so a placement takes the shared image whatever its driver allows for host-copy +// images (d3d12_existing_heap's shared slot-133 BC images do the same). Needs the bindless set (skipped otherwise). +// Synthetic data only. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" + +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +constexpr UINT width = 64, height = 48; // the shape under test; no other image of the test has this extent + +// The Vulkan calls the layer makes, seen through the function pointers it loads. +PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; +PFN_vkGetDeviceProcAddr real_device_proc = nullptr; +PFN_vkCreateImage real_create_image = nullptr; +std::atomic refuse_next{false}; +std::atomic shape_images{0}, refused{0}; // vkCreateImage calls for the shape under test, and refusals + +VKAPI_ATTR VkResult VKAPI_CALL create_image(VkDevice device, const VkImageCreateInfo* info, + const VkAllocationCallbacks* allocator, VkImage* image) { + if (info->extent.width == width && info->extent.height == height) { + ++shape_images; + if (refuse_next.exchange(false)) { + ++refused; + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + } + return real_create_image(device, info, allocator, image); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) { + if (std::strcmp(name, "vkCreateImage") == 0) { + real_create_image = reinterpret_cast(real_device_proc(device, name)); + return real_create_image ? reinterpret_cast(&create_image) : nullptr; + } + return real_device_proc(device, name); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetDeviceProcAddr") == 0) { + real_device_proc = reinterpret_cast(real_instance_proc(instance, name)); + return real_device_proc ? reinterpret_cast(&device_proc) : nullptr; + } + return real_instance_proc(instance, name); +} + +D3D12_RESOURCE_DESC bc1(UINT w, UINT h) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = w; + desc.Height = h; + desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_BC1_UNORM; + return desc; +} + +// A placement waiting on the shared zero image has no memory of its own yet. +bool shared(ID3D12Resource* texture) { return !rt::d3d12::vulkan_memory_flags(texture); } + +} // namespace + +int main() { + vktest::Device vk; + if (!vk.create()) return 77; + real_instance_proc = vk.instance_proc; + void* pages = VirtualAlloc(nullptr, 4 * 65536, MEM_RESERVE, PAGE_NOACCESS); + EXPECT(pages); + const auto at = [&](unsigned i) { return static_cast(pages) + i * 65536; }; + int result = 0; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = &instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + Ref control, first, second, third; + const D3D12_RESOURCE_DESC control_desc = bc1(32, 32), desc = bc1(width, height); + if (!rt::d3d12::bindless_set_layout(device.p)) { + std::fprintf(stderr, "SKIP: the device has no bindless set\n"); + result = 77; + } else if (FAILED(rt::d3d12::create_buffer_at_host_address(device.p, at(0), control_desc, 0, + IID_PPV_ARGS(&control.p))) || + !shared(control.p)) { + std::fprintf(stderr, "SKIP: a placed BC texture does not take a shared zero image on this device\n"); + result = 77; + } else { + // The shared image of the shape is refused: the first placement, and the next one, get memory of their own. + refuse_next = true; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, at(1), desc, 0, + IID_PPV_ARGS(&first.p)))); + EXPECT(refused == 1); + const unsigned by_first = shape_images.load(); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, at(2), desc, 0, + IID_PPV_ARGS(&second.p)))); + const unsigned by_second = shape_images.load() - by_first; + std::printf("shared image refused: placements %s and %s; %u and %u images of the shape made for them\n", + shared(first.p) ? "shared" : "with memory of their own", + shared(second.p) ? "shared" : "with memory of their own", by_first, by_second); + EXPECT(!shared(first.p)); + EXPECT(!shared(second.p)); + EXPECT(by_second == 1); + + // After the retry delay the shape is tried again, and the placement gets the shared image. + Sleep(1500); + const unsigned before_third = shape_images.load(); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, at(3), desc, 0, + IID_PPV_ARGS(&third.p)))); + const unsigned by_third = shape_images.load() - before_third; + std::printf("after the retry delay: placement %s; %u images of the shape made for it\n", + shared(third.p) ? "shared" : "with memory of their own", by_third); + EXPECT(shared(third.p)); + EXPECT(by_third == 2); + } + } + VirtualFree(pages, 0, MEM_RELEASE); + if (vk.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", vk.validation_errors()); + return 1; + } + if (!result) std::printf("ok\n"); + return result; +} From cf93f49fc419abb872166924f77f6b2567167c88 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:06:47 +0100 Subject: [PATCH 14/49] d3d12: the kept-scratch test waits until the queue has released what it kept, and a failed call keeps nothing (RT-REHYDRATE-SCRATCH-TICKET) The queue lets go of what a submission kept in the first of its calls that finds the submission completed, after that call's own submission. With LEONIDA_SUBMIT_ASYNC that call runs on the worker, so the fence of its Signal can be reached before the release has run, and the test's last check read the sentinels too early: it failed in 2 of 20 runs with LEONIDA_SUBMIT_ASYNC=4. The test now signals and waits until both sentinels are released, up to eight more Signals. The worker runs the calls in order, so a release has finished by the time the next Signal's fence is reached. The sentinels are static, so a late release, or one at teardown after a failed step returned early, never touches a frame that has ended. execute_sync asks for the lists' kept objects only when the call succeeded. A failed call submitted nothing of the lists, and on a lost device the references would otherwise stay in pin_queue_ until the queue is destroyed. pin_lists and keep_lists take their references through one helper, reference_lists. --- runtime/shims/d3d12_com.cpp | 37 +++++++++++------------- runtime/src/vulkan_backend.h | 4 ++- runtime/test/xbox_bvh_builder_test.cpp | 40 ++++++++++++++------------ 3 files changed, 42 insertions(+), 39 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 1c9c225730..c2a5f8ef51 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -2363,16 +2363,7 @@ class CommandQueue final // are not held (a D3D12 application keeps them until the fence it signals; the docs, section 4.4, list this), // except a shim's own the recording uses (hold_until_reset), which are pinned with them. static std::shared_ptr pin_lists(const std::vector& lists) { - auto objects = std::shared_ptr>(new std::vector, [](auto* held) { - for (IUnknown* object : *held) object->Release(); - delete held; - }); - for (const GraphicsCommandList* list : lists) - for (IUnknown* object : list->pinned()) { - object->AddRef(); - objects->push_back(object); - } - return objects; + return reference_lists(lists, &GraphicsCommandList::pinned); } // What a batch submitted at once keeps alive until its submission has completed on the GPU: the shim's own @@ -2380,20 +2371,26 @@ class CommandQueue final // as soon as ExecuteCommandLists returns, and a default-heap buffer's arena range is free again the moment the // buffer is destroyed. Null when no list has any, which is every list without a shim's scratch. static std::shared_ptr keep_lists(const std::vector& lists) { - std::size_t count = 0; - for (const GraphicsCommandList* list : lists) count += list->kept().size(); - if (!count) return nullptr; - auto objects = std::shared_ptr>(new std::vector, [](auto* kept) { - for (IUnknown* object : *kept) object->Release(); - delete kept; + for (const GraphicsCommandList* list : lists) + if (!list->kept().empty()) return reference_lists(lists, &GraphicsCommandList::kept); + return nullptr; + } + + // Takes a reference to each object that `objects` returns for each list. They are released when the last copy of + // the result goes. + static std::shared_ptr reference_lists( + const std::vector& lists, + const std::vector& (GraphicsCommandList::*objects)() const) { + auto references = std::shared_ptr>(new std::vector, [](auto* held) { + for (IUnknown* object : *held) object->Release(); + delete held; }); - objects->reserve(count); for (const GraphicsCommandList* list : lists) - for (IUnknown* object : list->kept()) { + for (IUnknown* object : (list->*objects)()) { object->AddRef(); - objects->push_back(object); + references->push_back(object); } - return objects; + return references; } // A D3D12 queue holds the fences it waits on and signals until the work has been submitted. diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 5b5a9ccaaf..b27fac0204 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -2781,7 +2781,9 @@ class VulkanQueue : private QueueHolds::Holder { std::lock_guard state(state_mutex_); if (!must_hold()) { result = execute_now(lists, execute_call); - if (std::shared_ptr kept = keep ? keep() : nullptr) { + // A failed call submitted nothing of the lists, so there is nothing to keep them for. + std::shared_ptr kept = result == ReplayResult::success && keep ? keep() : nullptr; + if (kept) { std::vector> pins{std::move(kept)}; retire_pins(pins, submitted_); // released by drain_pins once this submission has completed } diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp index 09276de37d..6ad7662fda 100644 --- a/runtime/test/xbox_bvh_builder_test.cpp +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -575,7 +575,9 @@ int main(int argc, char** argv) { if (const auto* build = std::get_if(&command)) scratch_va = build->scratch_va; const UINT64 scratch_bytes = (blas_info.ScratchDataSizeInBytes + 255) / 256 * 256; - Sentinel reset_sentinel, release_sentinel; + // Static, so a release that comes after this block (the queue's worker, or the teardown after a failed step + // returns early) still finds the object. + static Sentinel reset_sentinel, release_sentinel; check(scratch_va && rt::d3d12::hold_until_reset(list.p, &reset_sentinel) && rt::d3d12::hold_until_reset(other_list.p, &release_sentinel), "the build has the shim's scratch, and both lists hold a sentinel"); @@ -600,24 +602,26 @@ int main(int argc, char** argv) { "a DEFAULT buffer made right after the Reset does not get the range of the scratch the submission uses"); check(reset_sentinel.refs.load() > 1, "an object a list holds outlives the list's Reset after the call"); check(release_sentinel.refs.load() > 1, "and the list's release after the call"); - // The queue lets go of what a submission kept on its next call after that submission has completed: a - // Signal once the build's fence is reached, and one more, waited for, so that its release has run also - // when the queue's calls run on a worker (LEONIDA_SUBMIT_ASYNC). - const bool settled = SUCCEEDED(list->Close()) && [&] { - for (int i = 0; i < 2; ++i) { - if (FAILED(queue->Signal(fence.p, ++fence_value))) return false; - HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(fence_value, event)) && - WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; - if (event) CloseHandle(event); - if (!done) return false; - } - return SUCCEEDED(device->GetDeviceRemovedReason()); - }(); - if (!settled) return fail("the kept-scratch submission did not complete"); + // The queue lets go of what a submission kept in the first of its calls that finds the submission completed, + // after that call's own submission. On the queue's worker (LEONIDA_SUBMIT_ASYNC) the release can therefore + // still be running when the fence of that call's Signal is reached. The worker runs the calls in order, so it + // has finished by the time the fence of the next Signal is reached. After the Signal the build needs, the + // loop signals and waits until both objects are released, a few Signals at most. + const auto signal_and_wait = [&] { + if (FAILED(queue->Signal(fence.p, ++fence_value))) return false; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(fence_value, event)) && + WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + return done; + }; + const auto released = [] { return reset_sentinel.refs.load() == 1 && release_sentinel.refs.load() == 1; }; + bool settled = SUCCEEDED(list->Close()) && signal_and_wait(); + for (int i = 0; settled && !released() && i < 8; ++i) settled = signal_and_wait(); + if (!settled || FAILED(device->GetDeviceRemovedReason())) + return fail("the kept-scratch submission did not complete"); check(header_units(kept_rb.p) > 0, "the structure rehydrated with the kept scratch was built"); - check(reset_sentinel.refs.load() == 1 && release_sentinel.refs.load() == 1, - "both objects are released once the submission has completed"); + check(released(), "both objects are released once the submission has completed"); } // ---- the destructor releases the builder ---- From 6ce683aef0f5e8e6d3ec26bf258c819ac458d8a6 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:15:28 +0100 Subject: [PATCH 15/49] d3d12: no stand-in buffer is made for a refused title view, and refused views make one try a second in all (RT-TITLE-BUFFER-FALLBACK) The previous commit let go of the ordinary DEFAULT buffer that slot 133 answers with when a view's pages can be neither imported nor shadowed, but every retry still made one: vkCreateBuffer, a dedicated device-local allocation of up to 64 MiB (the arena being full is why the shadow failed), a zero fill, then a deferred free. That happened once a second for each refused range while the pressure lasted, under memory_mutex(), where the title's own allocations wait. create_at_host_address now takes ordinary_fallback (true by default, so slot 133 keeps its stand-in); make_title_buffer passes false and gets the shadow's HRESULT back instead. A buffer that does not cover the view is still let go. The retry was also per range: a title binding many views of one refused pool made one full try per distinct start per second. Now, after a refusal no range is tried for a second (title_buffer_retry_), and a range refused again waits twice as long as its last wait, up to 64 s, so one that keeps failing does not take every second's try from ranges that could get a buffer. Both checks come before the page walk, so a held-back bind makes no VirtualQuery call. d3d12_title_buffer_fallback_test now fills the arena with 64 KiB buffers, counts device-local allocations of a view's size while host-visible ones are refused, and binds a second view right after the first is refused and again later. With the previous commit: 2 device-local allocations (one per view) and the second view tried at once. Now: none, the second view held back for that second, and the first view, refused a second time, waits 2 s. --- runtime/CMakeLists.txt | 4 +- runtime/README.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 70 ++++++--- .../test/d3d12_title_buffer_fallback_test.cpp | 141 ++++++++++++------ 4 files changed, 145 insertions(+), 72 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 5377ebfb63..1b10cdee51 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2983,8 +2983,8 @@ if(TARGET Vulkan::Headers) set_tests_properties(xbox_linear_texture_map PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30 ENVIRONMENT "LEONIDA_LINEAR_MAP_FIRST=1") set_tests_properties(d3d12_xmem_placed PROPERTIES SKIP_RETURN_CODE 77) - # A vertex or index view of title memory that can be neither imported nor shadowed keeps no stand-in buffer and is - # tried again after a delay, not at every bind. + # A vertex or index view of title memory that can be neither imported nor shadowed gets no stand-in buffer and is + # tried again after a delay, not at every bind; after a refusal no other view is tried for that second either. add_executable(d3d12_title_buffer_fallback_test test/d3d12_title_buffer_fallback_test.cpp) target_link_libraries(d3d12_title_buffer_fallback_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_title_buffer_fallback_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) diff --git a/runtime/README.md b/runtime/README.md index ed31c1a5b9..e2cb238023 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -351,7 +351,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TITLE_TEXTURE_FILL_MB` | `32` | How many MiB of changed textures one pass fills again; the rest waits for the next pass. | | `LEONIDA_TEXTURE_HASH_BUDGET_US` | `400` | Microseconds a pass may spend hashing before it stops at a texture boundary. `0` leaves the byte budget alone to bound it. | | `LEONIDA_TEXTURE_SWEEP_BUDGET_US` | `400` | Microseconds a pass may spend on residency checks and uploads between textures. | -| `LEONIDA_TITLE_BUFFERS_MB` | `512` | The most memory, in MiB, of buffers made over the title's own memory for vertex and index views that name it. Only a buffer that covers its view (the pages imported or shadowed) is kept and counted; a view whose pages got neither is tried again a second later. | +| `LEONIDA_TITLE_BUFFERS_MB` | `512` | The most memory, in MiB, of buffers made over the title's own memory for vertex and index views that name it. Only a buffer that covers its view (the pages imported or shadowed) is made, kept and counted. After a view whose pages got neither, no view is tried for a second, and a view refused again waits twice as long as the last time, up to 64 s. | | `LEONIDA_TITLE_BUFFER_COVERAGE` | on | Such a view counts as covered only when a known buffer spans all its bytes. `0` asks for the first byte only. | | `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh, as before unchanged generations were skipped. | | `LEONIDA_STRICT_REPLAY` | unset | *Diagnostic.* `1` makes a draw or dispatch with an unresolvable resource fail its command list (`src/vulkan_replay.h`); by default it is dropped and logged. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 100575c183..bc7bfb452c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -19608,8 +19608,9 @@ class Device final // TitleVaAliases::want_buffer: a vertex or index view names `va` in the title's own memory and no buffer covers // it. A buffer over the 64 KiB-aligned committed pages around it is made the way slot 133 makes one (the pages // imported, or a shadow copied from them before every submission) and kept until the device goes, up to - // LEONIDA_TITLE_BUFFERS_MB (512 by default). Only a buffer that covers the view is kept; a range that got none is - // not tried again for a second (refused_title_ranges_). + // LEONIDA_TITLE_BUFFERS_MB (512 by default). Only a buffer that covers the view is made and kept. After a range + // got none, no range is tried for a second (title_buffer_retry_), and a range refused again waits twice as long + // as the last time, up to 64 s (refused_title_ranges_). void make_title_buffer(std::uint64_t va, std::uint64_t bytes) { if (!&context()) return; static const bool check_size = [] { @@ -19635,9 +19636,23 @@ class Device final const bool set = getenv_s(&length, text, "LEONIDA_TITLE_BUFFERS_MB") == 0 && length > 1; return (set ? std::strtoull(text, nullptr, 10) : 512ull) << 20; }(); + // The title binds the same views draw after draw, and many views of one pool when its pages are refused. Each + // try asks for an import and a shadow, and their memory, under memory_mutex(), where the title's own + // allocations wait. So after a refusal no range is tried for a second, whichever range it is, and a range + // refused before waits its own time too, which doubles at each refusal: one that keeps failing (its pages + // cannot be imported, and no shadow of its size fits) does not take every second's try from ranges that + // could get a buffer. Both are checked before the page walk below (its VirtualQuery calls), which only + // shortens `asked`. + const auto now = std::chrono::steady_clock::now(); + if (now < title_buffer_retry_) return; constexpr std::uint64_t align = 65536, most = 64ull << 20; const std::uint64_t start = std::max(va & ~(align - 1), lo); - std::uint64_t end = std::min(hi, (va + std::clamp(bytes, 1, most) + align - 1) & ~(align - 1)); + const std::uint64_t asked = + std::min(hi, (va + std::clamp(bytes, 1, most) + align - 1) & ~(align - 1)); + const auto refused = refused_title_ranges_.find(start); + if (refused != refused_title_ranges_.end() && asked <= refused->second.end && now < refused->second.retry) + return; + std::uint64_t end = asked; for (std::uint64_t at = start; at < end;) { // the committed, readable part only MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(reinterpret_cast(static_cast(at)), ®ion, sizeof(region)) || @@ -19649,13 +19664,6 @@ class Device final } // If the request runs into an uncommitted page or the size limit, reuse its backed prefix. if (end <= va || (check_size && state_.context->knows_buffer_va(va, end - va))) return; - // The title binds the same views draw after draw: a range whose buffer could not be made a moment ago waits - // for its retry time instead of being tried (and its buffers made and let go) at every bind. - const auto now = std::chrono::steady_clock::now(); - if (const auto refused = refused_title_ranges_.find(start); refused != refused_title_ranges_.end()) { - if (end <= refused->second.end && now < refused->second.retry) return; - refused_title_ranges_.erase(refused); - } if (title_buffer_bytes_ + (end - start) > cap) { log_once("vertex or index data in the title's memory is past LEONIDA_TITLE_BUFFERS_MB, left unresolved; MiB so far:", int(title_buffer_bytes_ >> 20)); @@ -19670,29 +19678,35 @@ class Device final desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; ID3D12Resource* made = nullptr; + // When the pages can be neither imported nor shadowed, slot 133 answers with an ordinary DEFAULT buffer that + // has neither the title's VA nor its bytes. It would not cover the view: kept, it would hold its memory until + // the device goes, and another would be made at the next bind of the same view, until + // LEONIDA_TITLE_BUFFERS_MB is used up. So it is not asked for (the shadow's failure comes back instead), and + // a buffer that still does not cover the view is let go. const HRESULT hr = create_at_host_address(reinterpret_cast(static_cast(start)), desc, 0xFFFFFFFFu, __uuidof(ID3D12Resource), - reinterpret_cast(&made), nullptr); - // When the pages can be neither imported nor shadowed, slot 133 answers with an ordinary DEFAULT buffer that - // has neither the title's VA nor its bytes (create_at_host_address). It does not cover the view, so keeping it - // would only hold its memory until the device goes and make another at the next bind of the same view, until - // LEONIDA_TITLE_BUFFERS_MB is used up. It is let go, and the range is tried again a second later, when the - // memory may be back. + reinterpret_cast(&made), nullptr, false); const bool kept = SUCCEEDED(hr) && made && state_.context->knows_buffer_va(va, check_size ? end - va : 1); if (!kept) { if (SUCCEEDED(hr) && made) - log_once("a buffer over the title's memory for a vertex or index view could get neither an import nor " - "a shadow, so none is kept; KiB", + log_once("a buffer over the title's memory for a vertex or index view does not cover it, so it is not " + "kept; KiB", int((end - start) >> 10)); else log_once("a buffer over the title's memory for a vertex or index view could not be made; HRESULT", int(hr)); if (made) made->Release(); + constexpr std::chrono::steady_clock::duration first = std::chrono::seconds(1), + longest = std::chrono::seconds(64); + const auto delay = + refused != refused_title_ranges_.end() ? std::min(refused->second.delay * 2, longest) : first; if (refused_title_ranges_.size() >= 256) - std::erase_if(refused_title_ranges_, [&](const auto& refused) { return refused.second.retry <= now; }); - refused_title_ranges_[start] = {end, now + std::chrono::seconds(1)}; + std::erase_if(refused_title_ranges_, [&](const auto& range) { return range.second.retry <= now; }); + refused_title_ranges_[start] = {asked, now + delay, delay}; + title_buffer_retry_ = now + first; return; } + if (refused != refused_title_ranges_.end()) refused_title_ranges_.erase(refused); title_buffers_.push_back(made); title_buffer_bytes_ += end - start; if (title_buffers_.size() <= 8 || !(title_buffers_.size() & (title_buffers_.size() - 1))) @@ -19706,16 +19720,21 @@ class Device final std::mutex title_buffer_mutex_; std::vector title_buffers_; // kept: the title's views name their addresses frame after frame std::uint64_t title_buffer_bytes_ = 0; - // Ranges [start, end) that got no buffer, by start, with when they may be tried again. Under title_buffer_mutex_; - // the entries past their time are dropped once there are 256. + // Ranges [start, end) that got no buffer, by start (`end` as asked, before the page walk), with when they may be + // tried again and how long they waited last. Under title_buffer_mutex_; the entries past their time are dropped + // once there are 256. struct RefusedTitleRange { std::uint64_t end; std::chrono::steady_clock::time_point retry; + std::chrono::steady_clock::duration delay; }; std::map refused_title_ranges_; + std::chrono::steady_clock::time_point title_buffer_retry_{}; // no range is tried before then (a refusal's second) + // `ordinary_fallback` false: a buffer whose pages can be neither imported nor shadowed fails with the shadow's + // HRESULT instead of being an ordinary DEFAULT buffer (make_title_buffer). HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, - void** out, const D3D12_CLEAR_VALUE* clear) { + void** out, const D3D12_CLEAR_VALUE* clear, bool ordinary_fallback = true) { constexpr auto method = "Xbox CreatePlacedResourceX (device slot 133)"; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // A texture cannot be placed on the title's pages (the PC GPU does not sample the console layout): it gets @@ -19835,8 +19854,11 @@ class Device final } // No memory for the shadow either: the boot goes on with an ordinary DEFAULT buffer of the same // description, as #6915's stand-in did. The title gets a resource, but neither its VA nor its writes at - // `address` reach it. + // `address` reach it. make_title_buffer asks for no such buffer: it would not cover the view it is made + // for, and making it would only take device-local memory, under the pressure that refused the shadow, + // to be let go at once. resource->Release(); + if (!ordinary_fallback) return d3d12_trace::result(method, shadow); log_once("a title-placed buffer (device slot 133) could neither import its pages nor get a shadow, so it " "is an ordinary buffer the title's writes do not reach; HRESULT", int(shadow)); diff --git a/runtime/test/d3d12_title_buffer_fallback_test.cpp b/runtime/test/d3d12_title_buffer_fallback_test.cpp index 9a6c380dbb..4c5571109d 100644 --- a/runtime/test/d3d12_title_buffer_fallback_test.cpp +++ b/runtime/test/d3d12_title_buffer_fallback_test.cpp @@ -3,15 +3,20 @@ // neither can be made, slot 133's last resort is an ordinary DEFAULT buffer, which has neither the title's VA nor its // bytes. A view must not keep such a buffer: it does not cover the view, so the next IASetVertexBuffers of the same // view would make another, each holding device memory and a device reference until the device goes, until -// LEONIDA_TITLE_BUFFERS_MB is used up and no new title view is resolved for the rest of the session. -// - The arena is filled first (LEONIDA_ARENA_MB=16, so a few 1 MiB buffers do it) and host-visible allocations are -// refused (the test wraps vkAllocateMemory behind the instance-proc pointer it hands the layer), with -// LEONIDA_SLOT133_IMPORT=0: no import and no shadow can be made, but a device-local DEFAULT buffer can. +// LEONIDA_TITLE_BUFFERS_MB is used up and no new title view is resolved for the rest of the session. Nor is such a +// buffer made only to be let go: it would take device-local memory at every try, under the pressure that refused the +// shadow. +// - The arena is filled first (LEONIDA_ARENA_MB=16, filled with 64 KiB buffers, so no slice is left for a shadow) +// and host-visible allocations are refused (the test wraps vkAllocateMemory behind the instance-proc pointer it +// hands the layer), with LEONIDA_SLOT133_IMPORT=0: no import and no shadow can be made, but a device-local DEFAULT +// buffer could. // - The same 2 MiB view of title memory bound 16 times, as vertex and index views, keeps no buffer (every buffer -// made over title memory holds a device reference, and the device's count does not grow) and is tried once (the -// buffers of its size created by the first bind are all there are). -// - Once the retry delay has passed, the next bind tries the view again (as many buffers of its size created as by -// the first bind) and the binds after it do not, and still nothing is kept. +// made over title memory holds a device reference, and the device's count does not grow) and is tried once: one +// buffer of its size is created, the shadow's, and no device-local memory of its size is allocated. +// - A second, 512 KiB view bound right after that refusal is not tried: after a refusal no range is tried for a +// second, whichever range it is. +// - After that second the first view is tried again, once, and refused again. 1.5 s later the second view is tried, +// but the first is not: a range refused again waits twice as long. After that it is tried once more. // Needs a device-local memory type that is not host-visible (skipped otherwise). Synthetic data only. Set // LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. #include "vk_test_device.h" @@ -32,6 +37,9 @@ namespace { template struct Ref { T* p = nullptr; + Ref() = default; + Ref(const Ref&) = delete; // a copy would release the same interface twice + Ref& operator=(const Ref&) = delete; ~Ref() { reset(); } void reset() { if (p) p->Release(); @@ -40,6 +48,8 @@ struct Ref { T* operator->() const { return p; } }; +constexpr UINT large_bytes = 2u << 20, small_bytes = 512u << 10; // the two views; no other buffer has these sizes + // The Vulkan calls the layer makes, seen through the function pointers it loads. PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; PFN_vkGetDeviceProcAddr real_device_proc = nullptr; @@ -47,20 +57,24 @@ PFN_vkAllocateMemory real_allocate = nullptr; PFN_vkCreateBuffer real_create_buffer = nullptr; VkPhysicalDeviceMemoryProperties memory{}; std::atomic refuse_host_visible{false}; -std::atomic watched_size{0}; -std::atomic watched_buffers{0}; // buffers of watched_size created +std::atomic large_buffers{0}, small_buffers{0}; // buffers of each view's size created +std::atomic device_allocations{0}; // device-local allocations of at least the smaller view's size, made + // while host-visible ones are refused VKAPI_ATTR VkResult VKAPI_CALL allocate(VkDevice device, const VkMemoryAllocateInfo* info, const VkAllocationCallbacks* allocator, VkDeviceMemory* out) { - if (refuse_host_visible.load() && info->memoryTypeIndex < memory.memoryTypeCount && - (memory.memoryTypes[info->memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) - return VK_ERROR_OUT_OF_DEVICE_MEMORY; + if (refuse_host_visible.load() && info->memoryTypeIndex < memory.memoryTypeCount) { + const VkMemoryPropertyFlags flags = memory.memoryTypes[info->memoryTypeIndex].propertyFlags; + if (flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) return VK_ERROR_OUT_OF_DEVICE_MEMORY; + if ((flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && info->allocationSize >= small_bytes) ++device_allocations; + } return real_allocate(device, info, allocator, out); } VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice device, const VkBufferCreateInfo* info, const VkAllocationCallbacks* allocator, VkBuffer* buffer) { - if (info->size == watched_size.load()) ++watched_buffers; + if (info->size == large_bytes) ++large_buffers; + if (info->size == small_bytes) ++small_buffers; return real_create_buffer(device, info, allocator, buffer); } @@ -120,11 +134,13 @@ int main() { return 77; } - constexpr UINT title_bytes = 2u << 20; + // Title memory of 4 MiB: the large view is its first 2 MiB, the small one starts 3 MiB in (another range). + constexpr UINT title_bytes = 4u << 20; auto& aliases = leonida::title_va_aliases(); void* pages = VirtualAlloc(nullptr, title_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); EXPECT(pages); const auto title_va = reinterpret_cast(pages); + const auto small_va = title_va + (3u << 20); aliases.add_title_memory(title_va, title_bytes); int result = 0; { @@ -143,11 +159,11 @@ int main() { std::fprintf(stderr, "SKIP: the device has no GPU address arena\n"); result = 77; } else { - // Fill the arena: a 1 MiB buffer that is not given an arena VA found no room there, so a 2 MiB shadow - // will not find any either. + // Fill the arena: a 64 KiB buffer (its placement alignment) that is not given an arena VA found no room + // there, so no shadow will find any either. const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - const D3D12_RESOURCE_DESC filler_desc = buffer_desc(1u << 20); - std::vector> fillers(arena >> 20); + const D3D12_RESOURCE_DESC filler_desc = buffer_desc(64u << 10); + std::vector> fillers(arena >> 16); bool full = false; for (auto& filler : fillers) { EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &filler_desc, @@ -163,46 +179,81 @@ int main() { IID_PPV_ARGS(&allocator.p)))); EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))); - const D3D12_VERTEX_BUFFER_VIEW vertices{title_va, title_bytes, 16}; - const D3D12_INDEX_BUFFER_VIEW indices{title_va, title_bytes, DXGI_FORMAT_R16_UINT}; - const auto bind = [&](unsigned i) { - if (i & 1) list->IASetIndexBuffer(&indices); - else list->IASetVertexBuffers(0, 1, &vertices); + const D3D12_VERTEX_BUFFER_VIEW large_vertices{title_va, large_bytes, 16}; + const D3D12_INDEX_BUFFER_VIEW large_indices{title_va, large_bytes, DXGI_FORMAT_R16_UINT}; + const D3D12_VERTEX_BUFFER_VIEW small_vertices{small_va, small_bytes, 16}; + const D3D12_INDEX_BUFFER_VIEW small_indices{small_va, small_bytes, DXGI_FORMAT_R16_UINT}; + const auto bind_large = [&](unsigned times) { + for (unsigned i = 0; i < times; ++i) { + if (i & 1) list->IASetIndexBuffer(&large_indices); + else list->IASetVertexBuffers(0, 1, &large_vertices); + } + return large_buffers.load(); + }; + const auto bind_small = [&](unsigned times) { + for (unsigned i = 0; i < times; ++i) { + if (i & 1) list->IASetIndexBuffer(&small_indices); + else list->IASetVertexBuffers(0, 1, &small_vertices); + } + return small_buffers.load(); }; - // No import, no shadow: nothing over the title's pages is kept, and the view is tried once. + // No import, no shadow: nothing over the title's pages is kept, and the view is tried once, with no + // device-local stand-in made for it. The other view, bound right after, is not tried. const ULONG before = references(device.p); - watched_size = title_bytes; refuse_host_visible = true; - bind(0); - const unsigned first = watched_buffers.load(); - for (unsigned i = 1; i < 16; ++i) bind(i); + const unsigned first = bind_large(1); + const unsigned tried = bind_large(15); + const unsigned small_held = bind_small(8); const ULONG refused = references(device.p); - const unsigned tried = watched_buffers.load(); std::printf("16 binds with no import or shadow: %lu buffers kept, %u buffers of the view's size created " - "(%u by the first bind)\n", - refused - before, tried, first); - EXPECT(first >= 1); + "(%u by the first bind), %u device-local allocations of its size; 8 binds of another view " + "right after: %u buffers of its size created\n", + refused - before, tried, first, device_allocations.load(), small_held); EXPECT(refused == before); + EXPECT(device_allocations == 0); + EXPECT(first == 1); EXPECT(tried == first); + EXPECT(small_held == 0); EXPECT(aliases.shader_va(title_va) == title_va); - // After the retry delay the next bind tries the view again, once. Host-visible memory is still refused - // here: a buffer the device keeps over title memory holds a reference to it, so the device would never be - // destroyed, and its Vulkan objects would be reported as leaked under the validation layer. + // After the second, the large view is tried again, once, and refused again. Host-visible memory is still + // refused here and below: a buffer the device keeps over title memory holds a reference to it, so the + // device would never be destroyed, and its Vulkan objects would be reported as leaked under the + // validation layer. + Sleep(1500); + const unsigned retried = bind_large(1); + const unsigned again = bind_large(7); + std::printf("after a second: %u buffers of the view's size created by the next bind, %u by 7 further " + "binds\n", + retried - tried, again - retried); + EXPECT(retried == tried + 1); + EXPECT(again == retried); + + // 1.5 s after that second refusal the other view is tried (no range waits for the device any more), but + // the large view is not: refused twice, it waits 2 s. + Sleep(1500); + const unsigned waited = bind_large(8); + const unsigned small_tried = bind_small(8); + std::printf("1.5 s later: %u buffers of the large view's size created by 8 binds, %u of the other " + "view's by 8 binds\n", + waited - again, small_tried - small_held); + EXPECT(waited == again); + EXPECT(small_tried == small_held + 1); + + // Once its 2 s have passed (and the other view's refusal is a second old), the large view is tried again. Sleep(1500); - bind(0); - const unsigned retried = watched_buffers.load(); - for (unsigned i = 1; i < 8; ++i) bind(i); - const unsigned again = watched_buffers.load(); + const unsigned third = bind_large(8); refuse_host_visible = false; const ULONG after = references(device.p); - std::printf("after the retry delay: %u buffers of the view's size created by the next bind, %u by 7 " - "further binds, %lu buffers kept\n", - retried - tried, again - retried, after - before); - EXPECT(retried == tried + first); - EXPECT(again == retried); + std::printf("1.5 s later: %u buffers of the large view's size created by 8 binds; %lu buffers kept, %u " + "device-local allocations of a view's size in all\n", + third - waited, after - before, device_allocations.load()); + EXPECT(third == waited + 1); EXPECT(after == before); + EXPECT(device_allocations == 0); + EXPECT(aliases.shader_va(title_va) == title_va); + EXPECT(aliases.shader_va(small_va) == small_va); EXPECT(SUCCEEDED(list->Close())); } } From 9d8d111be9d00207fac6def9e75750bc0b5f38ac Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:24:01 +0100 Subject: [PATCH 16/49] d3d12: a slot-70 image's pages are looked at only under a change with a range, a few images a pass (RT-SLOT70-OWNED-RETIRE) title_memory_map::changed() with no range records [0, UINTPTR_MAX). On Windows, xmem records one for each run of pages it commits for a DirectStorage transfer, and one for every MEM_RELEASE. The refresh pass took such a change for a change over every owned image. It then walked the pages of each with VirtualQuery, under the registry lock, on the title's submitting thread, nearly every pass of a streaming load. A look costs about 0.5 us here, so 60,000 images would cost about 30 ms a pass. A change anywhere now marks no image: it says that something changed, not where. title_free_impl records a whole release over the range that allocation_extent finds before the free, so a released pool is still found. It falls back to a change anywhere when the walk stopped early. A pass visits at most LEONIDA_TITLE_IMAGE_CHECKS (128) of the images that may be retired, from where the last pass stopped. A candidate not reached keeps its mark. A slot-133 texture covers owned images only with the layout of the title's XG computer, or with the one its first slot-70 view gives it. The guess from its description (Layout 0) can be larger than what the title placed. The census line counts the images that a view named again after a newer texture covered them. The test hooks are now owned_title_images and owned_title_image, and the predicate is now owned_image_retirement_on. d3d12_title_image_retire adds four checks. A change anywhere with 13 images makes 0 looks (13 before). A change over 12 images makes 4 looks a pass with LEONIDA_TITLE_IMAGE_CHECKS=4 (12 in one pass before). A guessed slot-133 layout covers nothing until a view names the texture. An image never filled stays when its pages go. The new d3d12_title_image_idle (LEONIDA_TITLE_IMAGE_IDLE_MS=500) checks the idle time for both reasons, and that a view of an image whose pages went keeps it until a later change over them. xmem_test checks the range a whole release records. All of them fail on d44285197. --- docs/d3d12_vulkan.md | 15 +- runtime/CMakeLists.txt | 8 +- runtime/README.md | 3 +- runtime/shims/d3d12_com.h | 11 +- runtime/shims/d3d12_vulkan_device.cpp | 93 ++++-- runtime/shims/xmem.cpp | 12 +- runtime/test/d3d12_existing_heap_test.cpp | 362 ++++++++++++++++------ runtime/test/xmem_test.cpp | 13 + 8 files changed, 390 insertions(+), 127 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 88955502de..ea236454ec 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3568,9 +3568,18 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv with its pages; two textures over the same bytes that views keep naming both stay. Its T# keys go at once and the image 3 s later, as for an address given another description. A later view of the address makes it again: a T# names the title address, so descriptors the title kept find the new image once it is filled; until then, and for - an address no view names again, they sample the fallback. The title textures census line counts the retirements - under a newer texture and with their pages gone. `LEONIDA_TITLE_IMAGE_RETIRE=0` keeps the images as before. - `d3d12_title_image_retire` covers it without game files. + an address no view names again, they sample the fallback. A slot-133 texture covers an image with the layout of + the title's XG computer of its shape, or with the one its first slot-70 view gives it; the guess from its + description (Layout 0) can be larger than what the title placed, and covers nothing. A view that names an image + whose pages went keeps it, until a later change over its pages finds them still gone. Pages are looked at only + after a change with a range: xmem records a change anywhere for each run of pages it commits for a DirectStorage + transfer on Windows, and it names no image's pages. A whole release (`VirtualFree` with `MEM_RELEASE` and no size) + records the range of the reservation. A look walks the pages with VirtualQuery on the title's submitting thread, + so a pass visits at most `LEONIDA_TITLE_IMAGE_CHECKS` (128) of the images that may go, from where the last one + stopped. The title textures census line counts the retirements under a newer texture and with their pages gone, + and the images a view named again after a newer texture covered them (overlapping textures both in use). + `LEONIDA_TITLE_IMAGE_RETIRE=0` keeps the images as before. `d3d12_title_image_retire` and `d3d12_title_image_idle` + cover it without game files. - With `LEONIDA_TITLE_PARTIAL_MIPS=1`, such a texture can be filled before all its pages are readable. The XG layout of a 2D texture of one slice stores its mips from the smallest to the largest, so the mips from `m` on are the first `mip_chain_bytes(layout, m)` bytes from its base (`xg_xs_layout.h`; checked in `xg_xs_test` for tiled, diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 862d26d4fe..6ba141784d 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2959,10 +2959,14 @@ if(TARGET Vulkan::Headers) # LEONIDA_TEXTURE_REFRESH_ASYNC=1 (set by the test itself): a mapped plane's first submission reads its bytes. add_test(NAME d3d12_mapped_plane_async COMMAND d3d12_existing_heap_test --mapped-plane-async) set_tests_properties(d3d12_mapped_plane_async PROPERTIES SKIP_RETURN_CODE 77) - # LEONIDA_TITLE_IMAGE_IDLE_MS=0 (set by the test itself): the images made for slot-70 views of textures a streaming - # title places at ever new addresses of the same memory stay at the textures still there. + # LEONIDA_TITLE_IMAGE_IDLE_MS=0 and LEONIDA_TITLE_IMAGE_CHECKS=4 (set by the test itself): the images made for + # slot-70 views of textures a streaming title places at ever new addresses of the same memory stay at the textures + # still there, and a pass looks at the pages of a few of them, only of those under a change it knows the range of. add_test(NAME d3d12_title_image_retire COMMAND d3d12_existing_heap_test --title-image-retire) set_tests_properties(d3d12_title_image_retire PROPERTIES SKIP_RETURN_CODE 77) + # LEONIDA_TITLE_IMAGE_IDLE_MS=500 (set by the test itself): such an image goes only after that long unnamed. + add_test(NAME d3d12_title_image_idle COMMAND d3d12_existing_heap_test --title-image-idle) + set_tests_properties(d3d12_title_image_idle PROPERTIES SKIP_RETURN_CODE 77) # The same with write watching off: the guarded cases only, the concurrent writers among them. add_test(NAME d3d12_existing_heap_no_write_watch COMMAND d3d12_existing_heap_test) set_tests_properties(d3d12_existing_heap_no_write_watch PROPERTIES SKIP_RETURN_CODE 77 diff --git a/runtime/README.md b/runtime/README.md index d0bcda1e36..e20474b8fe 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -400,8 +400,9 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TITLE_TEXTURE_FILL_MS` | `8` | Milliseconds one pass over the textures filled from the title's memory may spend filling; a texture already started is finished. `0` removes the time limit and leaves `LEONIDA_TITLE_TEXTURE_FILL_MB` to bound the pass. | | `LEONIDA_TITLE_PARTIAL_MIPS` | unset | `1`: a 2D texture of one slice the title keeps in its own memory, whose larger mips are not readable, is filled from the first mip that is when its last slot-70 view starts there or later. Views that start above keep the fallback until a later fill has their mips. Unset, a texture waits for all its mips. | | `LEONIDA_TITLE_PARTIAL_MIPS_MB` | `2048` | With `LEONIDA_TITLE_PARTIAL_MIPS=1`, the image memory the textures filled in part may hold, in MiB: each has memory for all its mips. A texture past it keeps the fallback. | -| `LEONIDA_TITLE_IMAGE_RETIRE` | on | An image the layer made for device slot 70 views of a texture in the title's memory is retired, with its bindless index, once a texture made or placed (slot 133) after its last view covers some of its bytes, or once none of its pages has been committed for `LEONIDA_TITLE_IMAGE_IDLE_MS`, and no slot 70 view has named it for that long. A title that streams places its textures at ever new addresses, and each such image stayed for the device's life. A later view of the address makes the image again, with the same T#. The title textures census line counts the retirements by reason. `0` keeps an image until its address gets another description or a slot-133 texture, as before. ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md), "When a slot-70 image goes") | +| `LEONIDA_TITLE_IMAGE_RETIRE` | on | An image the layer made for device slot 70 views of a texture in the title's memory is retired, with its bindless index, once a texture made or placed (slot 133, with the layout of the title's XG computer or of a slot 70 view) after its last view covers some of its bytes, or once none of its pages has been committed for `LEONIDA_TITLE_IMAGE_IDLE_MS`, and no slot 70 view has named it for that long. A title that streams places its textures at ever new addresses, and each such image stayed for the device's life. A later view of the address makes the image again, with the same T#. The title textures census line counts the retirements by reason. `0` keeps an image until its address gets another description or a slot-133 texture, as before. ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md), "When a slot-70 image goes") | | `LEONIDA_TITLE_IMAGE_IDLE_MS` | `2000` | With `LEONIDA_TITLE_IMAGE_RETIRE` on: how long, in milliseconds, an image a newer texture covers must have gone without a slot 70 view, and one whose pages went must have stayed without them, before it is retired. `0` retires it at the next submission. | +| `LEONIDA_TITLE_IMAGE_CHECKS` | `128` | With `LEONIDA_TITLE_IMAGE_RETIRE` on: how many of the images that may be retired one pass over the title's textures visits, from where the last pass stopped. A visit looks at the pages of an image under a map change with a range (a VirtualQuery walk, about a microsecond a call, on the title's submitting thread), so a change over a large pool that the title unloads is looked at over several passes. `0` visits all of them every pass. | | `LEONIDA_MAP_READBACK` | unset | `1` writes the GPU's texels of a small render or unordered-access target the title placed into the title's pages when the title maps it, so a CPU read of the target sees what the GPU rendered (the title reads its exposure statistics that way). Only a single-row, single-mip, single-layer, single-sample 2D target of at most 4 KiB a row; the copy waits for the GPU's work already submitted, and a page that is not writable is left as it is. Unset, the title reads its own pages, which the GPU never writes. | | `LEONIDA_SLOT133_IMPORT` | on | *Diagnostic.* `0` imports no title-placed buffer (device slot 133) as host memory: each takes the shadow-buffer fallback, so no GPU store can reach the title's memory through an import. | | `LEONIDA_ARENA_NULL_MB` | `0` | `n` (MiB) keeps the first `n` MiB of the descriptor arena, at `heap_base + 0`, zeroed and never allocated, and moves the zero page and the quad indices above it. A translated shader whose address arithmetic starts from a null base then reads or writes there instead of in a title buffer or the shared zero page. Ignored when it would take half of the arena or more; the device logs the region it made. | diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index fa405c0538..116685400a 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -350,14 +350,17 @@ TitleShadowWatch title_shadow_watch(ID3D12Device* device); // The device's registry of textures in the title's own memory now (write_placed_texture_view): the images it made for // slot-70 texture views and their image memory, the slot-133 textures in it, the made images retired since the device // was created (of them, those a newer texture over their bytes retired and those whose pages went), and how many -// retired images still wait for the GPU before their memory is freed. For tests. -struct TitleImages { +// retired images still wait for the GPU before their memory is freed. Then the made images that may be retired now, +// and, since the device was created, the looks at their pages and the images a view named again after a newer texture +// covered them. For tests. +struct OwnedTitleImages { std::uint64_t owned = 0, owned_bytes = 0, slot133 = 0, retired = 0, superseded = 0, gone = 0, waiting = 0; + std::uint64_t candidates = 0, looks = 0, named_again = 0; }; -TitleImages title_images(ID3D12Device* device); +OwnedTitleImages owned_title_images(ID3D12Device* device); // The image made for slot-70 texture views at `address`, with a reference added for the caller; null when the // registry holds none there. For tests. -ID3D12Resource* title_image(ID3D12Device* device, std::uint64_t address); +ID3D12Resource* owned_title_image(ID3D12Device* device, std::uint64_t address); // True when `device` has VK_KHR_acceleration_structure + VK_KHR_ray_query enabled. bool device_supports_ray_tracing(ID3D12Device* device); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index facb93fe81..b6954720b3 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -16376,10 +16376,12 @@ class Device final state_.index_texture(*entry); slot = std::move(entry); ++title_stats_.registered; - if (retire_owned_images()) { + if (owned_image_retirement_on()) { forget_owned_range(address); - // A texture the GPU writes has no layout here: what it covers is not known. - if (slot->layout_known && !slot->gpu_written) + // What it covers is known from the title's XG computer of its shape. A texture the GPU writes has no + // layout here, and a guessed one (Layout 0 of the description) may be larger than what the title + // placed, over its neighbours: those cover what a slot-70 view gives them (place_title_view). + if (slot->layout_from_xg && !slot->gpu_written) supersede_owned_images(address, slot->cpu, slot->layout.layout.size); } } @@ -16535,10 +16537,18 @@ class Device final // journal lost some changes, all are probed again, for whatever no change reports. constexpr auto kRetryAll = std::chrono::seconds(30); title_map_changes_.clear(); + owned_map_changes_.clear(); + const bool retire = owned_image_retirement_on(); std::uint64_t map_now = 0; bool map_all = !leonida::title_memory_map::changes_since( - title_map_generation_, map_now, 0, UINTPTR_MAX, - [&](std::uintptr_t from, std::uintptr_t to) { title_map_changes_.emplace_back(from, to); }); + title_map_generation_, map_now, 0, UINTPTR_MAX, [&](std::uintptr_t from, std::uintptr_t to) { + title_map_changes_.emplace_back(from, to); + // A change anywhere (title_memory_map::changed() with no range) says that something changed, not + // where: xmem records one for each run of pages it commits for a DirectStorage transfer on Windows. + // It names no owned image's pages. Taken for all of them, it would have nearly every pass of a + // streaming load look at the pages of every image. + if (retire && (from || to != UINTPTR_MAX)) owned_map_changes_.emplace_back(from, to); + }); title_map_generation_ = map_now; if (now - title_retry_all_ >= kRetryAll) map_all = true; if (map_all) title_retry_all_ = now; @@ -16546,10 +16556,13 @@ class Device final stats.map_ranges += title_map_changes_.size(); stats.map_all += map_all; // The owned images over these changes may have lost their pages (retire_idle_owned_images looks). Changes the - // journal lost are not looked for: such an image goes with the next change over it or a texture over it. - if (retire_owned_images()) - for (const auto& [from, to] : title_map_changes_) + // journal lost, and changes anywhere, are not looked for: such an image goes with the next change over its + // pages or a texture over its bytes. + if (retire) { + leonida::merge_title_writes(owned_map_changes_); + for (const auto& [from, to] : owned_map_changes_) owned_ranges_.overlapping(from, to, [&](std::uint64_t key) { retire_candidates_[key] = true; }); + } if (!written.empty() || overflow || map_all || !title_map_changes_.empty()) { stats.written_ranges += written.size(); leonida::merge_title_writes(written); @@ -16685,10 +16698,10 @@ class Device final for (Resource* r : release) r->Release(); } - // For tests (rt::d3d12::title_images, title_image). - TitleImages title_images() { + // For tests (rt::d3d12::owned_title_images, owned_title_image). + OwnedTitleImages owned_title_images() { std::lock_guard lock(state_.title_texture_mutex); - TitleImages out; + OwnedTitleImages out; for (const auto& [address, t] : state_.title_textures) { if (!t->resource) continue; if (!t->owned) { @@ -16702,9 +16715,12 @@ class Device final out.superseded = title_stats_.retired_superseded; out.gone = title_stats_.retired_gone; out.waiting = retired_title_textures_.size(); + out.candidates = retire_candidates_.size(); + out.looks = title_stats_.retire_looks; + out.named_again = title_stats_.superseded_named; return out; } - ID3D12Resource* title_image(std::uint64_t address) { + ID3D12Resource* owned_title_image(std::uint64_t address) { std::lock_guard lock(state_.title_texture_mutex); const auto it = state_.title_textures.find(address); if (it == state_.title_textures.end() || !it->second->owned || !it->second->resource) return nullptr; @@ -16720,8 +16736,9 @@ class Device final std::map refused; // why a view is a null view -> views std::uint64_t views = 0, null_views = 0, of_slot133 = 0, of_cache = 0, made = 0, retired = 0, registered = 0, refusals = 0, written_ranges = 0, unmaps = 0, unreadable = 0, pending_views = 0; - // Of the retired: under a newer texture, with their pages gone (retire_idle_owned_images). - std::uint64_t retired_superseded = 0, retired_gone = 0; + // Of the retired: under a newer texture, with their pages gone (retire_idle_owned_images). Looks at the pages + // of owned images there; owned images a view named again after a newer texture covered them. + std::uint64_t retired_superseded = 0, retired_gone = 0, retire_looks = 0, superseded_named = 0; std::uint64_t fills = 0, fill_bytes = 0, fill_failures = 0; // Fills of some mips only; textures whose first fill was one; those that got larger mips later; first fills // refused by LEONIDA_TITLE_PARTIAL_MIPS_MB. @@ -17004,6 +17021,8 @@ class Device final // be retired (a newer texture covers them, or their pages may have gone: true until a pass has looked at them). leonida::TitleTextureRangeIndex owned_ranges_; std::map retire_candidates_; + std::uint64_t retire_cursor_ = 0; // the candidate the next pass starts from + leonida::TitleWriteRanges owned_map_changes_; // scratch: this pass's map changes with a range std::vector title_tiled_, title_linear_; // scratch, under title_texture_mutex std::vector title_columns_; @@ -17098,6 +17117,7 @@ class Device final state_.index_texture(*t); t->layout_guessed = t->layout_from_xg = false; t->hashed = false; + if (owned_image_retirement_on()) supersede_owned_images(address, t->cpu, t->layout.layout.size); } else { refuse_title_view(why, d, address); // counted; the view of its image is still written } @@ -17121,6 +17141,7 @@ class Device final } else if (t) { ++title_stats_.of_cache; // Named again: in use, whatever covers its bytes now, and a view of a texture whose pages may come back. + title_stats_.superseded_named += t->superseded; t->named = std::chrono::steady_clock::now(); t->superseded = false; t->gone_since = {}; @@ -17229,7 +17250,7 @@ class Device final t->named = std::chrono::steady_clock::now(); state_.index_texture(*entry); state_.title_textures[address] = std::move(entry); - if (retire_owned_images()) { + if (owned_image_retirement_on()) { owned_ranges_.set(address, t->cpu, t->layout.layout.size); supersede_owned_images(address, t->cpu, t->layout.layout.size); } @@ -17255,10 +17276,13 @@ class Device final // view of it covers some of its bytes, or once no page of it has been committed for a while, when no slot-70 view // has named it for LEONIDA_TITLE_IMAGE_IDLE_MS (2000 by default): the bytes now hold another texture, or nothing, // as they would for its T# on the console. Two textures over the same bytes that views keep naming both stay. + // A slot-133 texture covers with its XG layout, or with the one a slot-70 view gives it, never with the guess from + // its description. Its pages are looked at after a title_memory_map change over them, not after a change anywhere. + // A view that names an image whose pages went keeps it, until a later change over them finds them still gone. // A view of a retired image's address makes it again (place_title_view): its T# names the title address // (Resource::place_at_title_address), so the copies of its descriptors the title kept find the new image once it // is filled. Until then, and for a T# whose address no view names again, a shader samples the fallback. - static bool retire_owned_images() { + static bool owned_image_retirement_on() { static const bool on = [] { const char* v = std::getenv("LEONIDA_TITLE_IMAGE_RETIRE"); return !v || std::strcmp(v, "0"); @@ -17272,6 +17296,13 @@ class Device final }()); return idle; } + static std::size_t owned_image_checks() { + static const std::size_t checks = [] { + const char* v = std::getenv("LEONIDA_TITLE_IMAGE_CHECKS"); + return v && *v ? std::size_t(std::strtoull(v, nullptr, 10)) : std::size_t(128); + }(); + return checks; + } // A texture at `key` now holds the title's bytes [cpu, cpu + size): the owned images at other keys over some of // them are superseded. One over exactly these bytes is the same texture named through the other view of a @@ -17300,16 +17331,29 @@ class Device final // is the view of a texture whose pages have not come yet, and stays). A superseded image goes once no view has // named it for the idle time, one whose pages went once they have been gone that long; the others stay // candidates. Its Release waits as every retired image's does (retired_title_textures_). + // A pass visits at most LEONIDA_TITLE_IMAGE_CHECKS of them (128 by default; 0: all), from where the last pass + // stopped. A look walks the pages with VirtualQuery, about a microsecond a call, and this runs under the registry + // lock on the title's submitting thread: a change over a large unloaded pool marks tens of thousands of images at + // once, and they are looked at over the following passes, a candidate not reached keeping its mark. void retire_idle_owned_images(std::chrono::steady_clock::time_point now) { const auto idle = owned_image_idle(); - for (auto it = retire_candidates_.begin(); it != retire_candidates_.end();) { + const std::size_t limit = owned_image_checks(); + std::size_t visits = limit ? std::min(limit, retire_candidates_.size()) : retire_candidates_.size(); + auto it = retire_candidates_.lower_bound(retire_cursor_); + for (; visits; --visits) { + if (it == retire_candidates_.end()) it = retire_candidates_.begin(); const std::uint64_t key = it->first; const auto entry = state_.title_textures.find(key); TitleTexture* t = entry == state_.title_textures.end() || !entry->second->owned || !entry->second->resource ? nullptr : entry->second.get(); if (t && std::exchange(it->second, false)) { - if (!t->fills || leonida::texture_memory_committed(std::uintptr_t(t->cpu), t->layout.layout.size)) + bool committed = !t->fills; + if (!committed) { + ++title_stats_.retire_looks; + committed = leonida::texture_memory_committed(std::uintptr_t(t->cpu), t->layout.layout.size); + } + if (committed) t->gone_since = {}; else if (t->gone_since == std::chrono::steady_clock::time_point{}) t->gone_since = now; @@ -17331,6 +17375,7 @@ class Device final state_.texture_ranges.erase(key); state_.title_textures.erase(entry); } + retire_cursor_ = it == retire_candidates_.end() ? 0 : it->first; } // LEONIDA_TITLE_PARTIAL_MIPS=1 (off by default). A slot-70 2D texture whose larger mips are not readable is filled from the @@ -17633,7 +17678,8 @@ class Device final std::fprintf(stderr, "[rt] d3d12: title textures (%s): %llu slot-70 texture views (%zu kinds), %llu of slot-133 textures, " "%llu of images made for them (%llu made, %llu over memory not readable yet, %llu retired: %llu " - "under a newer texture, %llu with their pages gone), %llu null views; registry %zu images " + "under a newer texture, %llu with their pages gone; %llu named again under a newer texture), %llu " + "null views; registry %zu images " "(%zu made, %zu slot 133 of %llu registered, %zu mapped, %zu filled); %llu fills %.1f MiB, %llu " "failed\n", when, static_cast(s.views), s.asked.size(), @@ -17641,6 +17687,7 @@ class Device final static_cast(s.made), static_cast(s.unreadable), static_cast(s.retired), static_cast(s.retired_superseded), static_cast(s.retired_gone), + static_cast(s.superseded_named), static_cast(s.null_views), state_.title_textures.size(), owned, slot133, static_cast(s.registered), mapped, filled, static_cast(s.fills), double(s.fill_bytes) / 1048576.0, @@ -22131,13 +22178,13 @@ TitleWindows title_windows(ID3D12Device* device) { windows.waiting = state.retired_windows.size(); return windows; } -TitleImages title_images(ID3D12Device* device) { +OwnedTitleImages owned_title_images(ID3D12Device* device) { auto* d = Device::from(device); - return d ? d->title_images() : TitleImages{}; + return d ? d->owned_title_images() : OwnedTitleImages{}; } -ID3D12Resource* title_image(ID3D12Device* device, std::uint64_t address) { +ID3D12Resource* owned_title_image(ID3D12Device* device, std::uint64_t address) { auto* d = Device::from(device); - return d ? d->title_image(address) : nullptr; + return d ? d->owned_title_image(address) : nullptr; } std::uint64_t title_shadow_trackers(ID3D12Device* device) { auto* d = Device::from(device); diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index fca6f6f474..85fa6042ed 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -2260,6 +2260,13 @@ BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) { const uintptr_t start = reinterpret_cast(address); uintptr_t release_end = 0; if (releases && address) allocation_extent(address, release_end); + // Whether [start, release_end) is all the release frees: allocation_extent stops after 4096 regions. + bool release_known = false; + if (release_end > start) { + MEMORY_BASIC_INFORMATION next{}; + release_known = !VirtualQuery(reinterpret_cast(release_end), &next, sizeof(next)) || + next.State == MEM_FREE || next.AllocationBase != address; + } uintptr_t decommit_end = 0; if ((free_type & MEM_DECOMMIT) && address) { decommit_end = size ? start + size : leonida::title_write_watch::end_of(start); @@ -2276,8 +2283,11 @@ BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) { } else { result = VirtualFree(address, size, free_type); } - // A release of size 0 frees the whole reservation, whose extent is not known here: a change anywhere. + // A release of size 0 frees the whole reservation: the range allocation_extent found before the free, so a reader + // whose pages are elsewhere (the D3D12 layer's textures and shadows) does not take every page for changed. Where + // that range is not known, a change anywhere. if (result && size) leonida::title_memory_map::changed(address, size); + else if (result && release_known) leonida::title_memory_map::changed(start, release_end); else if (result) leonida::title_memory_map::changed(); if (result && (free_type & MEM_DECOMMIT)) note_unwatched_change(address, size, 0, true); if (result && (free_type & MEM_RELEASE) && !(free_type & MEM_PRESERVE_PLACEHOLDER)) diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index bb271fff90..cbe3fb2641 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -1658,156 +1659,320 @@ int check_placed_view_map_changes(ID3D12Device* device) { return 0; } -// The images the layer makes for slot-70 texture views of the title's memory have a lifetime (the -// d3d12_title_image_retire test, with LEONIDA_TITLE_IMAGE_IDLE_MS=0). A streaming title places its textures at ever new -// addresses of the same memory: here 16 textures of 64 KiB, each 4 KiB after the one before, in one committed range. -// An image a newer texture covers, or whose pages have all gone, and that no view named since, is retired at the next -// submission; before, each address named kept its image, and its bindless index, for the device's life. An image a -// view names again after a newer texture covered it is kept (two views of the same bytes in use). A texture named -// again after its image was retired gets a new one with its texels, and the T# its first view wrote finds it again. -// A slot-133 texture the title places over an image's bytes retires it as a newer slot-70 texture does. -int check_title_image_retirement(ID3D12Device* device) { - const char* who = "slot-70 image retirement"; - if (!rt::d3d12::bindless_set_layout(device)) return 0; - constexpr UINT width = 256, height = 256; - constexpr SIZE_T texture_bytes = width * height, step = 4096, bytes = 1 << 20; - constexpr unsigned count = 16; - auto* pages = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - EXPECT(pages); +// What the slot-70 image checks below share: textures of 64 KiB the title writes into its memory and names through +// slot-70 views, submissions (the registry's refresh pass runs before each) and what the registry holds. +struct TitleImageBench { + static constexpr UINT width = 256, height = 256; + static constexpr SIZE_T texture_bytes = width * height; + const char* who = nullptr; + ID3D12Device* device = nullptr; GpuReader gpu; - EXPECT(!gpu.init(device, 4096)); D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - desc.Width = width; - desc.Height = height; - desc.DepthOrArraySize = desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Format = DXGI_FORMAT_R8_UNORM; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; - srv.Format = desc.Format; - srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - srv.Texture2D.MipLevels = 1; - srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - const auto va = [&](SIZE_T offset) { return reinterpret_cast(pages + offset); }; - // The title writes a texture's bytes, then names it. - const auto name = [&](SIZE_T offset, unsigned seed, leonida::gfx10::ImageWords& slot) { - for (SIZE_T i = 0; i < texture_bytes; ++i) pages[offset + i] = pattern_byte(i, seed); + rt::d3d12::OwnedTitleImages start{}; + + int init(ID3D12Device* d, const char* name) { + device = d; + who = name; + EXPECT(!gpu.init(device, 4096)); + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + srv.Format = desc.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + start = images(); + return 0; + } + // The title writes the bytes of the texture at `at` (unless `write` is false: it wrote them already, or the pages + // are not there), then names it. + bool name(std::uint8_t* at, unsigned seed, leonida::gfx10::ImageWords& slot, bool write = true) { + if (write) + for (SIZE_T i = 0; i < texture_bytes; ++i) at[i] = pattern_byte(i, seed); std::array resource{}; std::array words{}; std::memcpy(resource.data(), &desc, sizeof(desc)); std::memcpy(words.data(), &srv, sizeof(srv)); - return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), va(offset), + return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), + reinterpret_cast(at), {reinterpret_cast(slot.data())}); - }; - const auto index = [&](const leonida::gfx10::ImageWords& descriptor) { + } + bool index(const leonida::gfx10::ImageWords& descriptor) const { std::uint32_t key[8]; std::memcpy(key, descriptor.data(), sizeof(key)); return rt::d3d12::bindless_hash_lookup(device, key); - }; - // A submission: the registry's refresh pass runs before it. - ID3D12CommandList* lists[]{gpu.list.p}; - const auto submit = [&] { + } + int submit() { + ID3D12CommandList* lists[]{gpu.list.p}; gpu.queue->ExecuteCommandLists(1, lists); EXPECT_HR(gpu.queue->Signal(gpu.fence.p, ++gpu.fence_value), S_OK); EXPECT_HR(gpu.fence->SetEventOnCompletion(gpu.fence_value, gpu.done), S_OK); EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); return 0; - }; - // The image at `offset` holds the texels of `seed`. - const auto texels = [&](SIZE_T offset, unsigned seed) { + } + // The image at `at` holds the texels of `seed`. + int texels(std::uint8_t* at, unsigned seed) const { Ref image; - image.p = rt::d3d12::title_image(device, va(offset)); + image.p = rt::d3d12::owned_title_image(device, reinterpret_cast(at)); EXPECT(image.p); std::vector got(texture_bytes); EXPECT_HR(image->ReadFromSubresource(got.data(), width, UINT(texture_bytes), 0, nullptr), S_OK); for (SIZE_T i = 0; i < texture_bytes; ++i) if (got[i] != pattern_byte(i, seed)) { - std::fprintf(stderr, "%s: texel %zu of the image at +0x%zx is %u, expected %u\n", who, i, offset, - unsigned(got[i]), unsigned(pattern_byte(i, seed))); + std::fprintf(stderr, "%s: texel %zu of the image at %p is %u, expected %u\n", who, i, + static_cast(at), unsigned(got[i]), unsigned(pattern_byte(i, seed))); return 1; } return 0; - }; - const auto start = rt::d3d12::title_images(device); + } + rt::d3d12::OwnedTitleImages images() const { return rt::d3d12::owned_title_images(device); } + std::uint64_t owned() const { return images().owned - start.owned; } + std::uint64_t looks() const { return images().looks - start.looks; } + std::uint64_t gone() const { return images().gone - start.gone; } +}; + +// The images the layer makes for slot-70 texture views of the title's memory have a lifetime (the +// d3d12_title_image_retire test, with LEONIDA_TITLE_IMAGE_IDLE_MS=0 and LEONIDA_TITLE_IMAGE_CHECKS=4). A streaming +// title places its textures at ever new addresses of the same memory: here 16 textures of 64 KiB, each 4 KiB after +// the one before, in one committed range. An image a newer texture covers, or whose pages have all gone, and that no +// view named since, is retired at the next submission; before, each address named kept its image, and its bindless +// index, for the device's life. An image a view names again after a newer texture covered it is kept (two views of +// the same bytes in use). A texture named again after its image was retired gets a new one with its texels, and the +// T# its first view wrote finds it again. A slot-133 texture the title places over an image's bytes retires it once +// a slot-70 view gives it its layout, not with the guess from its description. An image never filled stays when its +// pages go. A change anywhere in the address space (title_memory_map::changed() with no range, which DirectStorage +// transfers record) does not make the pass look at every image's pages, and a change over many images has them +// looked at a few a pass. +int check_title_image_retirement(ID3D12Device* device) { + TitleImageBench b; + const char* who = "slot-70 image retirement"; + EXPECT(!b.init(device, who)); + constexpr SIZE_T texture_bytes = TitleImageBench::texture_bytes, step = 4096, bytes = 1 << 20; + constexpr unsigned count = 16, checks = 4; // LEONIDA_TITLE_IMAGE_CHECKS, set by main + auto* pages = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(pages); const auto room = rt::d3d12::bindless_room(device).images_2d; - const auto owned = [&] { return rt::d3d12::title_images(device).owned - start.owned; }; // 1. Sixteen textures over the same memory, one after the other: one image is left, the last one. leonida::gfx10::ImageWords first{}, slot{}; for (unsigned i = 0; i < count; ++i) { - EXPECT(name(i * step, i, i ? slot : first)); - if (!i) EXPECT(index(first)); // published at its fill... - EXPECT(!submit()); + EXPECT(b.name(pages + i * step, i, i ? slot : first)); + if (!i) EXPECT(b.index(first)); // published at its fill... + EXPECT(!b.submit()); } - EXPECT(!submit() && !submit()); - const auto streamed = rt::d3d12::title_images(device); + EXPECT(!b.submit() && !b.submit()); + const auto streamed = b.images(); std::printf("%s: %u textures named over the same memory: %llu images (%llu KiB), %llu retired, %llu of them under " "a newer texture; %u bindless 2D indices taken\n", - who, count, static_cast(streamed.owned - start.owned), - static_cast((streamed.owned_bytes - start.owned_bytes) >> 10), - static_cast(streamed.retired - start.retired), - static_cast(streamed.superseded - start.superseded), + who, count, static_cast(streamed.owned - b.start.owned), + static_cast((streamed.owned_bytes - b.start.owned_bytes) >> 10), + static_cast(streamed.retired - b.start.retired), + static_cast(streamed.superseded - b.start.superseded), room - rt::d3d12::bindless_room(device).images_2d); - EXPECT(streamed.owned - start.owned == 1); - EXPECT(streamed.owned_bytes - start.owned_bytes <= 2 * texture_bytes); - EXPECT(streamed.superseded - start.superseded == count - 1); + EXPECT(streamed.owned - b.start.owned == 1); + EXPECT(streamed.owned_bytes - b.start.owned_bytes <= 2 * texture_bytes); + EXPECT(streamed.superseded - b.start.superseded == count - 1); EXPECT(room - rt::d3d12::bindless_room(device).images_2d <= 1); - EXPECT(!index(first)); // ...so its T# finds nothing - EXPECT(!texels((count - 1) * step, count - 1)); + EXPECT(!b.index(first)); // ...so its T# finds nothing + EXPECT(!b.texels(pages + (count - 1) * step, count - 1)); // 2. The first texture named again: a new image with its texels, which the T# of its first view finds again. - EXPECT(name(0, 0, slot)); - EXPECT(!submit()); - EXPECT(owned() == 1 && !texels(0, 0)); - EXPECT(slot == first && index(first)); + EXPECT(b.name(pages, 0, slot)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && !b.texels(pages, 0)); + EXPECT(slot == first && b.index(first)); // 3. A view names it again after a newer texture covered half of it: both stay, at every submission. leonida::gfx10::ImageWords newer{}; - EXPECT(name(8 * step, 8, newer)); - EXPECT(name(0, 0, slot)); - EXPECT(!submit() && !submit()); - EXPECT(owned() == 2 && index(first) && index(newer)); + const auto named_again = b.images().named_again; + EXPECT(b.name(pages + 8 * step, 8, newer)); + EXPECT(b.name(pages, 0, slot)); + EXPECT(!b.submit() && !b.submit()); + EXPECT(b.owned() == 2 && b.index(first) && b.index(newer)); + EXPECT(b.images().named_again - named_again == 1); // 4. A third texture over both, named alone: it is the one image left. - EXPECT(name(12 * step, 12, slot)); - EXPECT(!submit()); - EXPECT(owned() == 1 && !index(first) && !index(newer) && index(slot) && !texels(12 * step, 12)); + EXPECT(b.name(pages + 12 * step, 12, slot)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && !b.index(first) && !b.index(newer) && b.index(slot) && !b.texels(pages + 12 * step, 12)); // 5. Its pages decommitted: no image is left. EXPECT(VirtualFree(pages, bytes, MEM_DECOMMIT) != FALSE); leonida::title_memory_map::changed(pages, bytes); - EXPECT(!submit()); - EXPECT(owned() == 0 && rt::d3d12::title_images(device).gone - start.gone == 1); + EXPECT(!b.submit()); + EXPECT(b.owned() == 0 && b.gone() == 1); // 6. The pages back, and a texture named there again: it has an image and its texels. EXPECT(VirtualAlloc(pages, bytes, MEM_COMMIT, PAGE_READWRITE) == pages); leonida::title_memory_map::changed(pages, bytes); - EXPECT(name(0, 0, slot)); - EXPECT(!submit()); - EXPECT(owned() == 1 && !texels(0, 0) && index(first)); + EXPECT(b.name(pages, 0, slot)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && !b.texels(pages, 0) && b.index(first)); - // 7. A slot-133 texture the title places over its bytes retires it too. + // 7. A slot-133 texture the title places over its bytes: the Layout 0 of its description is a guess, which may be + // larger than what the title placed, and covers nothing. A slot-70 view of it gives it its layout, and the image + // under it is retired. { Ref placed; - D3D12_RESOURCE_DESC placed_desc = desc; + D3D12_RESOURCE_DESC placed_desc = b.desc; placed_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages + 65536 - 2 * step, placed_desc, 0, - IID_PPV_ARGS(&placed.p)), S_OK); - EXPECT(!submit()); - EXPECT(owned() == 0 && !index(first)); + std::uint8_t* const at = pages + 65536 - 2 * step; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, at, placed_desc, 0, IID_PPV_ARGS(&placed.p)), S_OK); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && b.index(first)); + leonida::gfx10::ImageWords placed_view{}; + EXPECT(b.name(at, 7, placed_view)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 0 && !b.index(first)); + } + + // 8. A texture named before its pages came has an image never filled: it stays when a change over its pages + // finds none, and is filled once they come and a view names it again. + auto* hold = static_cast(VirtualAlloc(nullptr, texture_bytes, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(hold); + leonida::gfx10::ImageWords pending{}; + EXPECT(b.name(hold, 0, pending, false)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1); + leonida::title_memory_map::changed(hold, texture_bytes); + EXPECT(!b.submit() && !b.submit()); + EXPECT(b.owned() == 1 && b.gone() == 1); + EXPECT(VirtualAlloc(hold, texture_bytes, MEM_COMMIT, PAGE_READWRITE) == hold); + for (SIZE_T i = 0; i < texture_bytes; ++i) hold[i] = pattern_byte(i, 3); + leonida::title_memory_map::changed(hold, texture_bytes); + EXPECT(!b.submit()); + EXPECT(b.name(hold, 3, pending, false)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && !b.texels(hold, 3)); + + // 9. Twelve textures side by side, none over another, filled. + constexpr unsigned side = 12; + constexpr SIZE_T apart = 80 << 10; + auto* spread = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(spread); + std::vector views(side); + for (unsigned i = 0; i < side; ++i) EXPECT(b.name(spread + i * apart, 20 + i, views[i])); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 + side && b.images().candidates == 0); + // A change anywhere: no image is looked at, as no page of theirs is known to have changed. + const auto looks = b.looks(); + leonida::title_memory_map::changed(); + EXPECT(!b.submit()); + std::printf("%s: a change anywhere with %u images in the registry: %llu looks at their pages, %llu left to look " + "at\n", + who, 1 + side, static_cast(b.looks() - looks), + static_cast(b.images().candidates)); + EXPECT(b.looks() == looks && b.images().candidates == 0 && b.owned() == 1 + side); + // A change over all twelve: their pages are looked at, at most `checks` a pass, and all are still there. + leonida::title_memory_map::changed(spread, bytes); + for (unsigned pass = 0; pass * checks < side; ++pass) { + EXPECT(!b.submit()); + const auto seen = b.looks() - looks; + std::printf("%s: a change over %u images, pass %u: %llu looks at their pages\n", who, side, pass + 1, + static_cast(seen)); + EXPECT(seen == std::min(side, (pass + 1) * checks)); } + EXPECT(b.owned() == 1 + side && b.images().candidates == 0 && b.gone() == 1); + // Their pages decommitted: they go, a few a pass. + EXPECT(VirtualFree(spread, bytes, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(spread, bytes); + EXPECT(!b.submit()); + EXPECT(b.gone() == 1 + checks); + EXPECT(!b.submit() && !b.submit()); + EXPECT(b.owned() == 1 && b.gone() == 1 + side); + EXPECT(VirtualFree(hold, texture_bytes, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(hold, texture_bytes); + EXPECT(!b.submit()); + EXPECT(b.owned() == 0); // The retired images' memory is freed once no submission can still read them (3 s after their retirement). Sleep(3100); - EXPECT(!submit()); - const auto end = rt::d3d12::title_images(device); + EXPECT(!b.submit()); + const auto end = b.images(); std::printf("%s: %llu images retired in all (%llu under a newer texture, %llu with their pages gone), %llu still " "waiting for the GPU\n", - who, static_cast(end.retired - start.retired), - static_cast(end.superseded - start.superseded), - static_cast(end.gone - start.gone), static_cast(end.waiting)); - EXPECT(end.waiting == 0 && end.owned == start.owned); + who, static_cast(end.retired - b.start.retired), + static_cast(end.superseded - b.start.superseded), + static_cast(end.gone - b.start.gone), + static_cast(end.waiting)); + EXPECT(end.waiting == 0 && end.owned == b.start.owned); + VirtualFree(spread, 0, MEM_RELEASE); + VirtualFree(hold, 0, MEM_RELEASE); + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + +// The idle time of the slot-70 images (the d3d12_title_image_idle test, LEONIDA_TITLE_IMAGE_IDLE_MS=500). An image a +// newer texture covers stays while a view named it less than that long ago, and goes after; one a view names again in +// that time is no longer covered. An image whose pages went stays that long after the look that found them gone. A +// view that names it meanwhile keeps it, until a later change over its pages finds them still gone. +int check_title_image_idle(ID3D12Device* device) { + TitleImageBench b; + const char* who = "slot-70 image idle time"; + EXPECT(!b.init(device, who)); + using clock = std::chrono::steady_clock; + constexpr auto idle = std::chrono::milliseconds(500); // LEONIDA_TITLE_IMAGE_IDLE_MS, set by main + constexpr SIZE_T half = 32 << 10, bytes = 1 << 20, upper = bytes / 2; + auto* pages = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(pages); + const auto superseded = [&] { return b.images().superseded - b.start.superseded; }; + + // x and y, then a newer texture over the second half of each. + leonida::gfx10::ImageWords x{}, x2{}, y{}, y2{}; + const auto named = clock::now(); + EXPECT(b.name(pages, 1, x) && b.name(pages + half, 2, x2)); + EXPECT(b.name(pages + upper, 3, y) && b.name(pages + upper + half, 4, y2)); + EXPECT(!b.submit()); + if (clock::now() - named < idle) + EXPECT(b.owned() == 4 && superseded() == 0); + else + std::printf("%s: the first submission came after the idle time; its check is skipped\n", who); + // x named again: no longer covered. y, not named for longer than the idle time, goes. + Sleep(250); + EXPECT(b.name(pages, 1, x, false)); + Sleep(400); + EXPECT(!b.submit()); + EXPECT(b.owned() == 3 && superseded() == 1 && b.index(x) && !b.index(y)); + Sleep(600); + EXPECT(!b.submit()); + EXPECT(b.owned() == 3 && b.index(x) && b.index(x2) && b.index(y2)); + + // The pages of x and x2 decommitted: they stay for the idle time, then go. + EXPECT(VirtualFree(pages, upper, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(pages, upper); + const auto gone = clock::now(); + EXPECT(!b.submit()); + if (clock::now() - gone < idle) EXPECT(b.owned() == 3 && b.gone() == 0); + Sleep(700); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && b.gone() == 2 && b.index(y2)); + + // Those of y2 decommitted, and y2 named again before the idle time: it stays, while no change over its pages + // comes. A later one finds them still gone, and it goes the idle time after. + EXPECT(VirtualFree(pages + upper, upper, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(pages + upper, upper); + EXPECT(!b.submit()); + EXPECT(b.name(pages + upper + half, 4, y2, false)); + Sleep(700); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && b.gone() == 2); + leonida::title_memory_map::changed(pages + upper, upper); + EXPECT(!b.submit()); + Sleep(700); + EXPECT(!b.submit()); + EXPECT(b.owned() == 0 && b.gone() == 3); + std::printf("%s: %llu images retired under a newer texture and %llu with their pages gone, each after the idle " + "time\n", + who, static_cast(superseded()), static_cast(b.gone())); + // Their memory is freed 3 s after their retirement; an image still waiting at the end would keep the device. + Sleep(3100); + EXPECT(!b.submit()); + EXPECT(b.images().waiting == 0); VirtualFree(pages, 0, MEM_RELEASE); return 0; } @@ -2547,10 +2712,16 @@ int main(int argc, char** argv) { const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0; const bool async_plane = argc == 2 && std::strcmp(argv[1], "--mapped-plane-async") == 0; const bool image_retire = argc == 2 && std::strcmp(argv[1], "--title-image-retire") == 0; - if (argc != 1 && !prefix_only && !async_plane && !image_retire) return 2; + const bool image_idle = argc == 2 && std::strcmp(argv[1], "--title-image-idle") == 0; + if (argc != 1 && !prefix_only && !async_plane && !image_retire && !image_idle) return 2; if (async_plane) _putenv_s("LEONIDA_TEXTURE_REFRESH_ASYNC", "1"); // read once, at the device's first refresh - // An image no view named since a newer texture covered it, or since its pages went, goes at the next pass. - if (image_retire) _putenv_s("LEONIDA_TITLE_IMAGE_IDLE_MS", "0"); + // An image no view named since a newer texture covered it, or since its pages went, goes at the next pass; a pass + // visits at most 4 of those that may go. + if (image_retire) { + _putenv_s("LEONIDA_TITLE_IMAGE_IDLE_MS", "0"); + _putenv_s("LEONIDA_TITLE_IMAGE_CHECKS", "4"); + } + if (image_idle) _putenv_s("LEONIDA_TITLE_IMAGE_IDLE_MS", "500"); _putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0"); _putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0"); vktest::Device vk; @@ -2587,6 +2758,11 @@ int main(int argc, char** argv) { result += check_mapped_plane_first_use(staged.p); return result || vk.validation_errors() ? 1 : 0; } + if ((image_retire || image_idle) && !rt::d3d12::bindless_set_layout(ours.p)) return 77; + if (image_idle) { + const int result = check_title_image_idle(ours.p); + return result || vk.validation_errors() ? 1 : 0; + } if (image_retire) { int result = check_title_image_retirement(ours.p); auto no_host_copy = info; // the staged upload too diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 79f6554128..122b396c2a 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -2271,7 +2271,20 @@ void test_title_virtual_alloc() { generation = leonida::title_memory_map::generation(); check(free(gfx, 0x1000, MEM_DECOMMIT), "title VirtualFree decommits a page"); check(leonida::title_memory_map::generation() != generation, "title VirtualFree invalidates shadows"); + // A release takes no size: the map change it records is the reservation's own two regions (one page + // decommitted, the rest committed), not the whole address space, so a reader whose pages are elsewhere + // need not look at them again. + generation = leonida::title_memory_map::generation(); check(free(gfx, 0, MEM_RELEASE), "release the graphics allocation"); + const auto base = reinterpret_cast(gfx); + std::uint64_t now = 0; + bool released = false, elsewhere = false; + const auto note = [&](std::uintptr_t from, std::uintptr_t to) { + (from == base && to == base + 0x10000 ? released : elsewhere) = true; + }; + check(leonida::title_memory_map::changes_since(generation, now, 0, UINTPTR_MAX, note) && released && + !elsewhere, + "title VirtualFree of a whole reservation records the reservation's range as the map change"); } for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) { void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE); From 5f16ee1772751c64d808bcdb5fdb9370e1bb4a66 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:25:13 +0100 Subject: [PATCH 17/49] d3d12: a shape whose shared zero image keeps failing waits longer at each failure, up to 64 s (RT-ZERO-IMAGES-RETRY) The previous commit tried such a shape again a second after each failure. A failure is not always transient: where the driver allows no memory type for host-transfer images (the NVIDIA Pascal case create_texture documents), the image loses host-transfer usage at every try, so each BC shape there would cost two vkCreateImage calls, a pool suballocation and bind, and a deferred free every second for the whole session, where before it cost one try per shape per session. zero_image_retry now keeps the last wait with the retry time. It is a second after the first failure and doubles at each failure after it, up to 64 s; a shape that gets its image is dropped from the map. A shape that fails for good costs about one try a minute. One that failed under pressure gets its image at the first placement after its current wait, so at most 64 s after the memory is back. d3d12_zero_image_retry_test now refuses the shape's image a second time at the first retry. 1.5 s after that, a placement still has memory of its own (refused twice, the shape waits 2 s); 1.5 s later one gets the shared image. With the previous commit the placement 1.5 s after the second refusal already took the shared image. --- runtime/CMakeLists.txt | 3 +- runtime/shims/d3d12_vulkan_device.cpp | 31 ++++++++++----- runtime/test/d3d12_zero_image_retry_test.cpp | 42 ++++++++++++++++---- 3 files changed, 57 insertions(+), 19 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 799d2aeffc..7ec68673a2 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2967,7 +2967,8 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_existing_heap_write_watch COMMAND d3d12_existing_heap_test) set_tests_properties(d3d12_existing_heap_write_watch PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_WRITE_WATCH=1") - # A placed BC texture's shape whose shared zero image could not be made gets one at a later placement. + # A placed BC texture's shape whose shared zero image could not be made gets one at a later placement, after a wait + # that doubles at each failure. add_executable(d3d12_zero_image_retry_test test/d3d12_zero_image_retry_test.cpp) target_link_libraries(d3d12_zero_image_retry_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_zero_image_retry_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0eb6445a8d..dc2b3d4a39 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -7726,8 +7726,13 @@ struct DeviceState { using ZeroShape = std::tuple; std::mutex zero_image_mutex; std::map zero_images; // null: past the 256 MiB the shared images may take - // Shapes whose image could not be made, with when to try again (zero_sampled_image). Under zero_image_mutex. - std::map zero_image_retry; + // Shapes whose image could not be made, with when to try again and how long they waited last + // (zero_sampled_image). Under zero_image_mutex. + struct ZeroImageRetry { + std::chrono::steady_clock::time_point at; + std::chrono::steady_clock::duration delay; + }; + std::map zero_image_retry; std::atomic zero_image_bytes{0}; VkImage zero_sampled_image(const D3D12_RESOURCE_DESC&, const Format&, VkDeviceSize); std::multimap image_keys; // by the texture's address @@ -10759,15 +10764,15 @@ VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Form const ZeroShape key{d.Format, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels}; std::lock_guard lock(zero_image_mutex); if (auto it = zero_images.find(key); it != zero_images.end()) return it->second ? it->second->image() : VK_NULL_HANDLE; - // A shape whose image could not be made is tried again a second later. Under VRAM pressure create_texture fails, - // or its image loses host-transfer usage: a shape left without an image for good would have every later placement - // of it take memory of its own for the rest of the session, and one tried at every placement would make an image - // and ask for its memory each time. + // A shape whose image could not be made is tried again later. Under VRAM pressure create_texture fails, or its + // image loses host-transfer usage: a shape left without an image for good would have every later placement of it + // take memory of its own for the rest of the session, and one tried at every placement would make an image and ask + // for its memory each time. The wait is a second and doubles at each failure, up to 64 s, so a shape that fails + // every time (where the driver allows no memory type for host-transfer images, that usage is dropped at every try) + // is tried about once a minute, not once a second. const auto now = std::chrono::steady_clock::now(); - if (auto it = zero_image_retry.find(key); it != zero_image_retry.end()) { - if (now < it->second) return VK_NULL_HANDLE; - zero_image_retry.erase(it); - } + const auto retry = zero_image_retry.find(key); + if (retry != zero_image_retry.end() && now < retry->second.at) return VK_NULL_HANDLE; constexpr VkDeviceSize limit = 256ull << 20; const auto used = zero_image_bytes.load(std::memory_order_relaxed); if (used >= limit || bytes > limit - used) return VK_NULL_HANDLE; @@ -10775,9 +10780,13 @@ VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Form auto* zero = new Resource(*this, d, heap, D3D12_HEAP_FLAG_NONE); if (FAILED(zero->create_texture(format)) || (copy_memory_to_image && !zero->host_initialized_image())) { zero->Release(); - zero_image_retry[key] = now + std::chrono::seconds(1); + constexpr std::chrono::steady_clock::duration first = std::chrono::seconds(1), + longest = std::chrono::seconds(64); + const auto delay = retry != zero_image_retry.end() ? std::min(retry->second.delay * 2, longest) : first; + zero_image_retry[key] = {now + delay, delay}; return VK_NULL_HANDLE; } + if (retry != zero_image_retry.end()) zero_image_retry.erase(retry); // The shared images are never released, so a shape past the limit stays past it. if (zero->image_backing_bytes() > limit - used) { zero->Release(); diff --git a/runtime/test/d3d12_zero_image_retry_test.cpp b/runtime/test/d3d12_zero_image_retry_test.cpp index 964473a4f3..c6001acea8 100644 --- a/runtime/test/d3d12_zero_image_retry_test.cpp +++ b/runtime/test/d3d12_zero_image_retry_test.cpp @@ -7,8 +7,10 @@ // - The test wraps vkCreateImage behind the instance-proc pointer it hands the layer and refuses the next image of // the shape under test: that is the shared image, made before the placement's own. That placement, and one right // after it, have memory of their own: the shape is not tried again at every placement. -// - After the retry delay, a third placement of the shape gets its shared image (no memory of its own): two images -// of the shape are made for it, the shared one and the placement's. +// - After the retry delay (a second), a third placement of the shape tries again, and that image is refused too. +// - The delay doubles at each refusal: 1.5 s later a fourth placement does not try (memory of its own, one image of +// the shape made for it), and 1.5 s after that (past the 2 s) a fifth gets its shared image (no memory of its +// own): two images of the shape are made for it, the shared one and the placement's. // The device has no host image copies, so a placement takes the shared image whatever its driver allows for host-copy // images (d3d12_existing_heap's shared slot-133 BC images do the same). Needs the bindless set (skipped otherwise). // Synthetic data only. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. @@ -28,6 +30,9 @@ namespace { template struct Ref { T* p = nullptr; + Ref() = default; + Ref(const Ref&) = delete; // a copy would release the same interface twice + Ref& operator=(const Ref&) = delete; ~Ref() { reset(); } void reset() { if (p) p->Release(); @@ -92,7 +97,7 @@ int main() { vktest::Device vk; if (!vk.create()) return 77; real_instance_proc = vk.instance_proc; - void* pages = VirtualAlloc(nullptr, 4 * 65536, MEM_RESERVE, PAGE_NOACCESS); + void* pages = VirtualAlloc(nullptr, 6 * 65536, MEM_RESERVE, PAGE_NOACCESS); EXPECT(pages); const auto at = [&](unsigned i) { return static_cast(pages) + i * 65536; }; int result = 0; @@ -108,7 +113,7 @@ int main() { info.bindless_partially_bound = vk.partially_bound; Ref device; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); - Ref control, first, second, third; + Ref control, first, second, third, fourth, fifth; const D3D12_RESOURCE_DESC control_desc = bc1(32, 32), desc = bc1(width, height); if (!rt::d3d12::bindless_set_layout(device.p)) { std::fprintf(stderr, "SKIP: the device has no bindless set\n"); @@ -135,16 +140,39 @@ int main() { EXPECT(!shared(second.p)); EXPECT(by_second == 1); - // After the retry delay the shape is tried again, and the placement gets the shared image. + // After the retry delay the shape is tried again, and its image is refused again. Sleep(1500); + refuse_next = true; const unsigned before_third = shape_images.load(); EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, at(3), desc, 0, IID_PPV_ARGS(&third.p)))); const unsigned by_third = shape_images.load() - before_third; - std::printf("after the retry delay: placement %s; %u images of the shape made for it\n", + std::printf("after the retry delay, refused again: placement %s; %u images of the shape made for it\n", shared(third.p) ? "shared" : "with memory of their own", by_third); - EXPECT(shared(third.p)); + EXPECT(refused == 2); + EXPECT(!shared(third.p)); EXPECT(by_third == 2); + + // Refused twice, the shape waits 2 s: 1.5 s later it is not tried, and after the 2 s it gets its image. + Sleep(1500); + const unsigned before_fourth = shape_images.load(); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, at(4), desc, 0, + IID_PPV_ARGS(&fourth.p)))); + const unsigned by_fourth = shape_images.load() - before_fourth; + std::printf("1.5 s later: placement %s; %u images of the shape made for it\n", + shared(fourth.p) ? "shared" : "with memory of their own", by_fourth); + EXPECT(!shared(fourth.p)); + EXPECT(by_fourth == 1); + Sleep(1500); + const unsigned before_fifth = shape_images.load(); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, at(5), desc, 0, + IID_PPV_ARGS(&fifth.p)))); + const unsigned by_fifth = shape_images.load() - before_fifth; + std::printf("1.5 s later: placement %s; %u images of the shape made for it\n", + shared(fifth.p) ? "shared" : "with memory of their own", by_fifth); + EXPECT(refused == 2); + EXPECT(shared(fifth.p)); + EXPECT(by_fifth == 2); } } VirtualFree(pages, 0, MEM_RELEASE); From 876887de428819e3917fada9c58dd996da4c9331 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:09:04 +0100 Subject: [PATCH 18/49] d3d12: slot-70 image retirement is opt-in until a game session measures it (RT-SLOT70-OWNED-RETIRE) LEONIDA_TITLE_IMAGE_RETIRE is off by default now; 1 turns it on. Retirement decides on a newer texture over an image's bytes or on its pages going, and on no slot-70 view naming it for a while. A title that samples such an image through a descriptor it wrote once (a heap it copies from, a table it keeps) with no later view of the address would sample the fallback once the image goes, and the census cannot see that. With the switch off nothing changes for the title; with it on, a streaming session can show whether the images stay at the textures still there. d3d12_title_image_retire and d3d12_title_image_idle run with the switch on. A negative LEONIDA_TITLE_IMAGE_IDLE_MS counts as 0. --- docs/d3d12_vulkan.md | 7 +++++-- runtime/CMakeLists.txt | 9 ++++++--- runtime/README.md | 6 +++--- runtime/shims/d3d12_vulkan_device.cpp | 6 +++--- 4 files changed, 17 insertions(+), 11 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index ea236454ec..761f0a7ba8 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3578,8 +3578,11 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv so a pass visits at most `LEONIDA_TITLE_IMAGE_CHECKS` (128) of the images that may go, from where the last one stopped. The title textures census line counts the retirements under a newer texture and with their pages gone, and the images a view named again after a newer texture covered them (overlapping textures both in use). - `LEONIDA_TITLE_IMAGE_RETIRE=0` keeps the images as before. `d3d12_title_image_retire` and `d3d12_title_image_idle` - cover it without game files. + It is off by default (`LEONIDA_TITLE_IMAGE_RETIRE=1` turns it on) until a game session has measured it: a title + that samples an image through a descriptor it wrote once (a heap it copies from, a table it keeps), with no later + slot-70 view of the address, would sample the fallback once the image goes, and the census cannot see that. The + range a whole release records is there for every reader of the map, whatever the switch. + `d3d12_title_image_retire` and `d3d12_title_image_idle` cover it without game files, with the switch on. - With `LEONIDA_TITLE_PARTIAL_MIPS=1`, such a texture can be filled before all its pages are readable. The XG layout of a 2D texture of one slice stores its mips from the smallest to the largest, so the mips from `m` on are the first `mip_chain_bytes(layout, m)` bytes from its base (`xg_xs_layout.h`; checked in `xg_xs_test` for tiled, diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 6ba141784d..2b6a394d64 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2959,14 +2959,17 @@ if(TARGET Vulkan::Headers) # LEONIDA_TEXTURE_REFRESH_ASYNC=1 (set by the test itself): a mapped plane's first submission reads its bytes. add_test(NAME d3d12_mapped_plane_async COMMAND d3d12_existing_heap_test --mapped-plane-async) set_tests_properties(d3d12_mapped_plane_async PROPERTIES SKIP_RETURN_CODE 77) - # LEONIDA_TITLE_IMAGE_IDLE_MS=0 and LEONIDA_TITLE_IMAGE_CHECKS=4 (set by the test itself): the images made for + # LEONIDA_TITLE_IMAGE_RETIRE=1, with LEONIDA_TITLE_IMAGE_IDLE_MS=0 and LEONIDA_TITLE_IMAGE_CHECKS=4 (set by the test + # itself): the images made for # slot-70 views of textures a streaming title places at ever new addresses of the same memory stay at the textures # still there, and a pass looks at the pages of a few of them, only of those under a change it knows the range of. add_test(NAME d3d12_title_image_retire COMMAND d3d12_existing_heap_test --title-image-retire) - set_tests_properties(d3d12_title_image_retire PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(d3d12_title_image_retire PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_TITLE_IMAGE_RETIRE=1") # LEONIDA_TITLE_IMAGE_IDLE_MS=500 (set by the test itself): such an image goes only after that long unnamed. add_test(NAME d3d12_title_image_idle COMMAND d3d12_existing_heap_test --title-image-idle) - set_tests_properties(d3d12_title_image_idle PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(d3d12_title_image_idle PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_TITLE_IMAGE_RETIRE=1") # The same with write watching off: the guarded cases only, the concurrent writers among them. add_test(NAME d3d12_existing_heap_no_write_watch COMMAND d3d12_existing_heap_test) set_tests_properties(d3d12_existing_heap_no_write_watch PROPERTIES SKIP_RETURN_CODE 77 diff --git a/runtime/README.md b/runtime/README.md index e20474b8fe..cf308b2f90 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -400,9 +400,9 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TITLE_TEXTURE_FILL_MS` | `8` | Milliseconds one pass over the textures filled from the title's memory may spend filling; a texture already started is finished. `0` removes the time limit and leaves `LEONIDA_TITLE_TEXTURE_FILL_MB` to bound the pass. | | `LEONIDA_TITLE_PARTIAL_MIPS` | unset | `1`: a 2D texture of one slice the title keeps in its own memory, whose larger mips are not readable, is filled from the first mip that is when its last slot-70 view starts there or later. Views that start above keep the fallback until a later fill has their mips. Unset, a texture waits for all its mips. | | `LEONIDA_TITLE_PARTIAL_MIPS_MB` | `2048` | With `LEONIDA_TITLE_PARTIAL_MIPS=1`, the image memory the textures filled in part may hold, in MiB: each has memory for all its mips. A texture past it keeps the fallback. | -| `LEONIDA_TITLE_IMAGE_RETIRE` | on | An image the layer made for device slot 70 views of a texture in the title's memory is retired, with its bindless index, once a texture made or placed (slot 133, with the layout of the title's XG computer or of a slot 70 view) after its last view covers some of its bytes, or once none of its pages has been committed for `LEONIDA_TITLE_IMAGE_IDLE_MS`, and no slot 70 view has named it for that long. A title that streams places its textures at ever new addresses, and each such image stayed for the device's life. A later view of the address makes the image again, with the same T#. The title textures census line counts the retirements by reason. `0` keeps an image until its address gets another description or a slot-133 texture, as before. ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md), "When a slot-70 image goes") | -| `LEONIDA_TITLE_IMAGE_IDLE_MS` | `2000` | With `LEONIDA_TITLE_IMAGE_RETIRE` on: how long, in milliseconds, an image a newer texture covers must have gone without a slot 70 view, and one whose pages went must have stayed without them, before it is retired. `0` retires it at the next submission. | -| `LEONIDA_TITLE_IMAGE_CHECKS` | `128` | With `LEONIDA_TITLE_IMAGE_RETIRE` on: how many of the images that may be retired one pass over the title's textures visits, from where the last pass stopped. A visit looks at the pages of an image under a map change with a range (a VirtualQuery walk, about a microsecond a call, on the title's submitting thread), so a change over a large pool that the title unloads is looked at over several passes. `0` visits all of them every pass. | +| `LEONIDA_TITLE_IMAGE_RETIRE` | off | `1`: an image the layer made for device slot 70 views of a texture in the title's memory is retired, with its bindless index, once a texture made or placed (slot 133, with the layout of the title's XG computer or of a slot 70 view) after its last view covers some of its bytes, or once none of its pages has been committed for `LEONIDA_TITLE_IMAGE_IDLE_MS`, and no slot 70 view has named it for that long. A title that streams places its textures at ever new addresses, and each such image stayed for the device's life. A later view of the address makes the image again, with the same T#. The title textures census line counts the retirements by reason. Unset or `0` keeps an image until its address gets another description or a slot-133 texture, as before. Off by default until a game session has measured it: a title that samples such an image through a descriptor it wrote once, without a later slot 70 view of the address, would get the fallback texture once the image goes. ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md), "When a slot-70 image goes") | +| `LEONIDA_TITLE_IMAGE_IDLE_MS` | `2000` | With `LEONIDA_TITLE_IMAGE_RETIRE=1`: how long, in milliseconds, an image a newer texture covers must have gone without a slot 70 view, and one whose pages went must have stayed without them, before it is retired. `0` retires it at the next submission. | +| `LEONIDA_TITLE_IMAGE_CHECKS` | `128` | With `LEONIDA_TITLE_IMAGE_RETIRE=1`: how many of the images that may be retired one pass over the title's textures visits, from where the last pass stopped. A visit looks at the pages of an image under a map change with a range (a VirtualQuery walk, about a microsecond a call, on the title's submitting thread), so a change over a large pool that the title unloads is looked at over several passes. `0` visits all of them every pass. | | `LEONIDA_MAP_READBACK` | unset | `1` writes the GPU's texels of a small render or unordered-access target the title placed into the title's pages when the title maps it, so a CPU read of the target sees what the GPU rendered (the title reads its exposure statistics that way). Only a single-row, single-mip, single-layer, single-sample 2D target of at most 4 KiB a row; the copy waits for the GPU's work already submitted, and a page that is not writable is left as it is. Unset, the title reads its own pages, which the GPU never writes. | | `LEONIDA_SLOT133_IMPORT` | on | *Diagnostic.* `0` imports no title-placed buffer (device slot 133) as host memory: each takes the shadow-buffer fallback, so no GPU store can reach the title's memory through an import. | | `LEONIDA_ARENA_NULL_MB` | `0` | `n` (MiB) keeps the first `n` MiB of the descriptor arena, at `heap_base + 0`, zeroed and never allocated, and moves the zero page and the quad indices above it. A translated shader whose address arithmetic starts from a null base then reads or writes there instead of in a title buffer or the shared zero page. Ignored when it would take half of the arena or more; the device logs the region it made. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index b6954720b3..297a384101 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -17269,7 +17269,7 @@ class Device final ++title_stats_.retired; } - // LEONIDA_TITLE_IMAGE_RETIRE (on by default; 0: as before). An image made for slot-70 views was retired only when + // LEONIDA_TITLE_IMAGE_RETIRE=1 (off by default). An image made for slot-70 views was retired only when // its own address got another description or a slot-133 texture, and a title that streams places its textures at // ever new addresses: each kept its image (in VRAM, then in system memory), its bindless index and its turn in the // refresh passes for the device's life. Now one is also retired once a texture made or registered after the last @@ -17285,14 +17285,14 @@ class Device final static bool owned_image_retirement_on() { static const bool on = [] { const char* v = std::getenv("LEONIDA_TITLE_IMAGE_RETIRE"); - return !v || std::strcmp(v, "0"); + return v && *v && std::strcmp(v, "0") != 0; }(); return on; } static std::chrono::milliseconds owned_image_idle() { static const std::chrono::milliseconds idle([] { const char* v = std::getenv("LEONIDA_TITLE_IMAGE_IDLE_MS"); - return v && *v ? std::strtoll(v, nullptr, 10) : 2000ll; + return v && *v ? (std::max)(0ll, std::strtoll(v, nullptr, 10)) : 2000ll; }()); return idle; } From 1ea7df6a93713a6925ecbda9e26c373c540b8047 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:02:14 +0100 Subject: [PATCH 19/49] leonida-hle: XMemFreeDefault tells the GPU side of freed 32-bit memory (RS-XMEM-FREE-DEFAULT) XMemAllocDefault's 32-bit path goes through XMemVirtualAlloc, which tells the GPU side of the new memory (title_memory_allocated). XMemFreeDefault freed that memory with the host's VirtualFree directly, so title_memory_freed never ran for it: the guarded, absent and foreign blocks, the views and the write-combined regions noted for the range survived the free and could be taken for true of the next memory at the address. It now frees through title_virtual_free, the title's own VirtualFree, which tells the GPU side first. The new test frees a 32-bit block and checks that the free reached the GPU side; a test-only record in title_virtual_free shows which frees did. No caller known to us sets the 32-bit attribute, so this may never run with the title; it is a correctness fix more than a memory one (sweep R1-06). --- d3d12/crates/leonida-hle/src/modules/xmem.rs | 30 +++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/d3d12/crates/leonida-hle/src/modules/xmem.rs b/d3d12/crates/leonida-hle/src/modules/xmem.rs index dcc3d5e88f..dec4b2e3ca 100644 --- a/d3d12/crates/leonida-hle/src/modules/xmem.rs +++ b/d3d12/crates/leonida-hle/src/modules/xmem.rs @@ -372,7 +372,10 @@ pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) { // whole reservation, or a header-prefixed block. unsafe { if attributes & ALLOC_32BIT != 0 { - VirtualFree(address, 0, MEM_RELEASE); + // `XMemVirtualAlloc` told the GPU side of this memory, so it is + // freed as the title's own `VirtualFree` frees: what was noted of + // it must not be taken for true of the next memory there. + title_virtual_free(address, 0, MEM_RELEASE); return; } let user = address.cast::(); @@ -2182,11 +2185,21 @@ extern "system" fn title_virtual_free(address: *mut c_void, size: usize, kind: u // Splitting and joining placeholders changes nothing they show. if kind & (MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS) == 0 { leonida_gpu::title_memory_freed(address as usize, size); + #[cfg(test)] + TOLD_FREED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(address as usize); } // SAFETY: the title's own arguments. unsafe { VirtualFree(address, size, kind) } } +/// The addresses [`title_virtual_free`] told the GPU side were freed, so the +/// tests can see which frees reach it. +#[cfg(test)] +static TOLD_FREED: Mutex> = Mutex::new(Vec::new()); + pub(crate) fn module() -> HleModule { HleModule { name: "xmem", @@ -2239,6 +2252,21 @@ mod tests { XMemFree(p, ALLOC_32BIT); } + #[test] + fn free_default_tells_the_gpu_side_of_32bit_memory() { + // `XMemAllocDefault` told the GPU side of this memory + // (`XMemVirtualAlloc`), so freeing it must say it is gone, or what + // was noted of it is taken for true of the next memory there. + let p = XMemAllocDefault(4096, ALLOC_32BIT); + assert!(!p.is_null()); + XMemFreeDefault(p, ALLOC_32BIT); + let told = TOLD_FREED.lock().unwrap_or_else(|e| e.into_inner()); + assert!( + told.contains(&(p as usize)), + "the free of {p:p} never reached the GPU side" + ); + } + #[test] fn virtual_alloc_meets_console_constraints() { const GPU_READ_WRITE: u32 = 0x2000; From f468d3ec1c48fd683aba7e0d4aed0ceff78666db Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:05:49 +0100 Subject: [PATCH 20/49] leonida-gpu: the early pipeline list keeps the last two runs (RS-EARLY-START-AGE) early-pipelines.txt was the union of every run ever: each run loaded it, added the keys it requested and wrote the whole set back, so its comment ("this run and the last") was not true. Every title pipeline drawn with in any earlier run was started at creation, at every load, and its host pipeline stayed alive for the session whether this run drew with it or not. EARLY_MAX (100,000) is above the title's 84,000 pipelines, and at the cap the list stopped taking new keys instead of dropping old ones. Each line now holds a key and the run that last requested it. The run is counted by the list itself (one past the newest written down), and a save keeps the keys requested in the last two runs. A process that requests no pipeline writes the list back unchanged, so it does not age the others out. A list without runs (written by an older build) still loads: its keys count as run 0, are started early once more and then age like the others. LEONIDA_EARLY_RUNS= keeps n runs; 0 keeps every run's, as before. leonida warm --used reads the same file, so it now takes the first word of each line as the key. --- d3d12/apps/leonida/src/warm.rs | 4 +- .../leonida-gpu/src/pipeline/library.rs | 186 ++++++++++++++++-- 2 files changed, 175 insertions(+), 15 deletions(-) diff --git a/d3d12/apps/leonida/src/warm.rs b/d3d12/apps/leonida/src/warm.rs index 60d7b050a1..aa8a4aad5e 100644 --- a/d3d12/apps/leonida/src/warm.rs +++ b/d3d12/apps/leonida/src/warm.rs @@ -49,7 +49,9 @@ pub fn run(jobs: Option, limit: Option, again: bool, used: bool, t let bad = std::fs::read_to_string(&bad_file).unwrap_or_default(); let bad: HashSet<&str> = bad.lines().filter_map(|l| l.split(' ').next()).collect(); let early = std::fs::read_to_string(dir.join("early-pipelines.txt")).unwrap_or_default(); - let early: HashSet<&str> = early.lines().collect(); + // A key, then the run that last drew with it (a list of an older build + // has the key alone). + let early: HashSet<&str> = early.lines().filter_map(|l| l.split(' ').next()).collect(); // Those earlier runs drew with first, the others in no order (by key). let mut all: Vec = (0..keys.len()) .filter(|&n| { diff --git a/d3d12/crates/leonida-gpu/src/pipeline/library.rs b/d3d12/crates/leonida-gpu/src/pipeline/library.rs index feae4a5a2c..4bcd198fdc 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/library.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/library.rs @@ -12,7 +12,8 @@ //! 2. The title pipelines a run drew or dispatched with are listed by a key //! known when the title creates them (their shader containers and //! graphics state); the next run hands those to the workers at -//! creation, during loading. +//! creation, during loading. A pipeline stays listed for two runs after +//! the last one that drew with it ([`early_runs`]). //! //! Library calls overlap: the host documents the library as safe to use //! from several threads ("The pipeline library is thread-safe to use, and @@ -49,7 +50,7 @@ //! 16,352 of 16,384 pages read zeros with the handle closed, none with it //! open (the test below). `LEONIDA_LIBRARY_HANDLE=0`: closed, as before. -use std::collections::HashSet; +use std::collections::HashMap; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Mutex, MutexGuard, OnceLock, RwLock}; @@ -680,7 +681,7 @@ pub(crate) fn save(now: bool) { }; // Through `used`: a process that asked for none yet (`leonida shaders`) // must not write the earlier runs' list over with nothing. - let used: Vec = used().iter().flatten().cloned().collect(); + let used: Vec = used().as_ref().map(|e| e.lines(early_runs())).unwrap_or_default(); let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) }; if bytes > 0 && library_written.is_ok() { // In place unless the system refused and the new one waits beside it. @@ -803,25 +804,97 @@ pub(crate) fn note_time(key: &str, ms: u64) { } } -/// Title pipeline keys requested by draws or dispatches (this run and the last). -static USED: Mutex>> = Mutex::new(None); +/// Title pipeline keys requested by draws or dispatches (this run and the +/// last, [`early_runs`]). +static USED: Mutex> = Mutex::new(None); static USED_CHANGED: AtomicBool = AtomicBool::new(false); -fn used() -> std::sync::MutexGuard<'static, Option>> { +/// How many runs' title pipelines the early list keeps: 2, those this run +/// requested and those the run before did, so a pipeline is started early +/// by the two runs after the last one that drew with it. The list held +/// every run's: each pipeline drawn with in any earlier run was started at +/// the title's creation of it, at every load, and kept as a host pipeline +/// for the whole session whether this run drew with it or not. It grew +/// with every place visited, and at `EARLY_MAX` it stopped taking new ones. +/// `LEONIDA_EARLY_RUNS=`: n runs; 0: every run's, as before. +fn early_runs() -> u64 { + static RUNS: OnceLock = OnceLock::new(); + *RUNS.get_or_init(|| { + std::env::var("LEONIDA_EARLY_RUNS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2) + }) +} + +/// The early list ([`EARLY_FILE`]): a key and the run that last requested +/// it on each line. Runs are counted by the list itself: this one is one +/// past the newest written down. A line with a key alone (a list written +/// before runs were counted) is one of run 0. +struct Early { + /// This run's number. + run: u64, + keys: HashMap, +} + +impl Early { + fn read(text: &str) -> Early { + let mut keys: HashMap = HashMap::new(); + for line in text.lines() { + let mut words = line.split_ascii_whitespace(); + let Some(key) = words.next() else { continue }; + let run = words.next().and_then(|r| r.parse().ok()).unwrap_or(0); + let last = keys.entry(key.to_owned()).or_insert(run); + *last = run.max(*last); + } + let run = keys.values().copied().max().unwrap_or(0).saturating_add(1); + Early { run, keys } + } + + /// Whether a run on the list requested `key`. + fn has(&self, key: &str) -> bool { + self.keys.contains_key(key) + } + + /// This run requested `key`; whether the list changed: a key new to it, + /// or one an earlier run requested last (its run is written again). + fn note(&mut self, key: &str) -> bool { + if let Some(last) = self.keys.get_mut(key) { + return std::mem::replace(last, self.run) != self.run; + } + self.keys.len() < EARLY_MAX && self.keys.insert(key.to_owned(), self.run).is_none() + } + + /// The lines to write, by key: the keys requested in the last `runs` + /// runs (0: in any). They are counted back from the newest run on the + /// list, which is this one once it has requested a pipeline: a process + /// that requests none (one that only translates shaders) writes the + /// list back as it found it, and is not a run that ages the others out. + fn lines(&self, runs: u64) -> Vec { + let newest = self.keys.values().copied().max().unwrap_or(0); + let mut kept: Vec<(&String, &u64)> = self + .keys + .iter() + .filter(|&(_, &last)| runs == 0 || last.saturating_add(runs) > newest) + .collect(); + kept.sort_unstable(); + kept.into_iter().map(|(key, last)| format!("{key} {last}")).collect() + } +} + +fn used() -> std::sync::MutexGuard<'static, Option> { let mut used = USED.lock().unwrap_or_else(|e| e.into_inner()); if used.is_none() { let listed = DIR .get() .and_then(|d| std::fs::read_to_string(d.join(EARLY_FILE)).ok()) .unwrap_or_default(); - let set: HashSet = listed.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect(); - tracing::info!(pipelines = set.len(), "title pipelines to start early"); - *used = Some(set); + let early = Early::read(&listed); + tracing::info!(pipelines = early.keys.len(), "title pipelines to start early"); + *used = Some(early); } used } -/// Whether the title pipeline with `key` was requested in this or an earlier run. +/// Whether the title pipeline with `key` was requested in this run or one +/// of the earlier runs the early list keeps ([`early_runs`]). /// /// `LEONIDA_EARLY_ALL=1`: every title pipeline is started at creation, /// requested before or not, so that the driver's own cache holds it for @@ -831,14 +904,12 @@ pub(crate) fn wanted_early(key: &str) -> bool { if *ALL.get_or_init(|| std::env::var_os("LEONIDA_EARLY_ALL").is_some_and(|v| v == "1")) { return true; } - used().as_ref().is_some_and(|s| s.contains(key)) + used().as_ref().is_some_and(|early| early.has(key)) } /// A draw or dispatch requested the title pipeline with `key`. pub(crate) fn note_used(key: &str) { - let mut used = used(); - let set = used.get_or_insert_with(HashSet::new); - if set.len() < EARLY_MAX && set.insert(key.to_owned()) { + if used().get_or_insert_with(|| Early::read("")).note(key) { USED_CHANGED.store(true, Ordering::Relaxed); } } @@ -987,6 +1058,93 @@ mod tests { } } + /// The keys an early list's text holds, sorted. + fn listed(text: &str) -> Vec<&str> { + let mut keys: Vec<&str> = text.lines().filter_map(|l| l.split(' ').next()).collect(); + keys.sort_unstable(); + keys + } + + /// Five runs, each drawing with pipelines of its own: the list the last + /// one writes holds those of that run and the one before, and the next + /// run starts only those early. It held every run's, so each pipeline + /// drawn with in any run ever became a host pipeline at every load. + #[test] + fn the_early_list_keeps_the_last_two_runs() { + let mut text = String::new(); + for run in 1..=5 { + let mut early = Early::read(&text); + for n in 0..2 { + assert!(early.note(&format!("run{run}-{n}"))); + } + text = early.lines(2).join("\n"); + } + assert_eq!(listed(&text), ["run4-0", "run4-1", "run5-0", "run5-1"]); + let next = Early::read(&text); + assert!(next.has("run4-0") && next.has("run5-1")); + assert!(!next.has("run3-0") && !next.has("run1-0")); + } + + /// A pipeline drawn with again in a later run stays listed from then on. + #[test] + fn a_pipeline_drawn_with_again_stays_listed() { + let mut text = String::new(); + for run in 1..=5 { + let mut early = Early::read(&text); + early.note(&format!("run{run}")); + if run % 2 == 1 { + // The list changes (its run is written down), once a run. + assert!(early.note("odd-runs")); + assert!(!early.note("odd-runs")); + } + text = early.lines(2).join("\n"); + } + assert_eq!(listed(&text), ["odd-runs", "run4", "run5"]); + } + + /// A list written before runs were counted (a key alone on each line) + /// still loads: its keys are started early, kept for one more run and + /// then age as the others do. + #[test] + fn an_early_list_without_runs_still_loads() { + let mut early = Early::read("old-a\nold-b\n\n"); + assert!(early.has("old-a") && early.has("old-b")); + early.note("new"); + let text = early.lines(2).join("\n"); + assert_eq!(listed(&text), ["new", "old-a", "old-b"]); + let mut next = Early::read(&text); + next.note("new"); + next.note("old-b"); + assert_eq!(listed(&next.lines(2).join("\n")), ["new", "old-b"]); + } + + /// A process that requests no pipeline (one that only translates + /// shaders) writes the list back as it found it: it is not a run that + /// ages the others out. + #[test] + fn a_process_that_requests_nothing_writes_the_list_back() { + let mut text = String::new(); + for run in 1..=3 { + let mut early = Early::read(&text); + early.note(&format!("run{run}")); + text = early.lines(2).join("\n"); + } + assert_eq!(Early::read(&text).lines(2).join("\n"), text); + assert_eq!(listed(&text), ["run2", "run3"]); + } + + /// `LEONIDA_EARLY_RUNS=0`: every run's pipelines stay listed, as before. + #[test] + fn no_count_of_runs_keeps_every_run() { + let mut text = String::new(); + for run in 1..=4 { + let mut early = Early::read(&text); + early.note(&format!("run{run}")); + text = early.lines(0).join("\n"); + } + assert_eq!(listed(&text), ["run1", "run2", "run3", "run4"]); + } + #[test] fn concurrent_write_atomically_never_fails_or_truncates() { let dir = tempfile::tempdir().unwrap(); From 74a89d86f53589870d969a02675c65d58a3bc15d Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:06:24 +0100 Subject: [PATCH 21/49] leonida-gpu: replaced host copies go with LEONIDA_TEXTURE_SWEEP=0 too (RS-REPLACED-DRAIN) want_level puts a host copy replaced by one with more levels in REPLACED, so that a thread about to record its use still finds it alive for a second and four frames. let_go_idle was the only place that let those copies go, and it did that after the LEONIDA_TEXTURE_SWEEP=0 early return: with the sweep off every replaced copy (its host texture and twin) stayed on the card for good, although nothing could use it. The drain now runs before the switch is looked at; the switch still keeps every idle copy as before. The new test runs itself again in a process of its own with the sweep off (the switch is read once), makes a placed texture's copy from level 2, replaces it with one from level 0, and checks that let_go_idle lets the old one go after four frames and a second. It needs a host GPU, as its neighbours do. Only runs with the non-default LEONIDA_TEXTURE_SWEEP=0 are affected (sweep R3-07). --- d3d12/crates/leonida-gpu/src/resource.rs | 67 +++++++++++++++++++++--- 1 file changed, 61 insertions(+), 6 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/resource.rs b/d3d12/crates/leonida-gpu/src/resource.rs index 2fc331a1ef..4c8483e4d9 100644 --- a/d3d12/crates/leonida-gpu/src/resource.rs +++ b/d3d12/crates/leonida-gpu/src/resource.rs @@ -2153,16 +2153,16 @@ fn sweep_batch(all: &std::collections::BTreeSet, from: usize, limit: usiz /// makes the list or the slot hold it) is protected by that idle time alone. /// Every caller uses it at once, within the title's call. /// Called before a submission starts, by the thread that submits. -/// `LEONIDA_TEXTURE_SWEEP=0` lets nothing go. +/// `LEONIDA_TEXTURE_SWEEP=0` lets nothing idle go; copies replaced by ones +/// with more levels go all the same. #[cfg(windows)] pub(crate) fn let_go_idle() { use std::sync::atomic::Ordering::Relaxed; const IDLE_FRAMES: u64 = 4; - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - if !*ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { - return; - } - // Copies replaced by ones with more levels, as any let go. + // Copies replaced by ones with more levels, as any let go. Before the + // switch below, which must not keep them: nothing uses them any more and + // nothing else lets them go, so with the sweep off they would be held + // for good. { let mut replaced = REPLACED.lock().unwrap_or_else(|e| e.into_inner()); let (gone, keep): (Vec<_>, Vec<_>) = @@ -2173,6 +2173,10 @@ pub(crate) fn let_go_idle() { crate::host::retire(made); } } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { + return; + } let memory = crate::host::host().and_then(|h| h.video_memory()); static KEEP: std::sync::OnceLock = std::sync::OnceLock::new(); let keep = *KEEP @@ -5062,4 +5066,55 @@ float4 lit() : SV_Target { return 1.0; } assert_eq!((more.base, d.Width, d.MipLevels), (0, 256, 9)); assert!(more.serial != copy.serial && more.grown.load(std::sync::atomic::Ordering::Relaxed)); } + + /// With the sweep off (`LEONIDA_TEXTURE_SWEEP=0`), a host copy replaced + /// by one with more levels still goes once nothing may be about to + /// record its use: nothing else lets it go. In a process of its own, + /// since the switch is read once. + #[cfg(windows)] + #[test] + fn replaced_copies_go_with_the_sweep_off() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const CHILD: &str = "LEONIDA_REPLACED_CHILD"; + if std::env::var_os(CHILD).is_none() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "resource::tests::replaced_copies_go_with_the_sweep_off", "--nocapture"]) + .env(CHILD, "1") + .env("LEONIDA_TEXTURE_SWEEP", "0") + .output() + .unwrap(); + assert!( + out.status.success(), + "the run with the sweep off failed:\n{}\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + return; + } + if crate::host::host().is_none() || !held_only() { + return; + } + // As in `a_placed_texture_is_kept_from_the_level_viewed`: a copy from + // level 2, replaced by one from level 0. + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap(); + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + let texture = texture_at(at as u64, &desc).unwrap(); + want_level(texture, 2); + let copy = host_copy(texture).unwrap(); + want_level(texture, 0); + let replaced = || { + let replaced = REPLACED.lock().unwrap_or_else(|e| e.into_inner()); + replaced.iter().any(|(_, (old, _))| std::sync::Arc::ptr_eq(old, ©)) + }; + assert!(replaced()); + // Long enough ago: four frames and a second. + for _ in 0..4 { + crate::frame::test_advance(); + } + std::thread::sleep(std::time::Duration::from_millis(1200)); + let_go_idle(); + assert!(!replaced(), "the replaced copy is still held"); + } } From ae6bb29cd90dc569b369cf95e51f3f40212f39d9 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:06:33 +0100 Subject: [PATCH 22/49] leonida-gpu: a texture refresh thread keeps at most 16 MiB of read buffer between textures (RS-TEXTURE-READ-TRIM) The read buffer of texture refreshes (texture.rs READ, with_read) is one per thread and only grew. The threads that refresh write-watched, partly mapped and unlocked-path textures (the submitting thread and the leonida-wide-N helpers of shadow::wide_each) live for the run, so each kept the room of the largest texture it ever read until the end: 22 MB for a 4096x4096 BC7 texture with its levels, 89 MB for one in RGBA8, on each of five threads on a PC of 16 logical processors. Room over LEONIDA_TEXTURE_READ_KEEP_MB (16 unless set) is now given back when the read is over. The buffer grows by exactly what a texture asks for, so that one under the limit keeps its room instead of leaving doubled room over it (on d44285197 a read of 32 MiB after reads of 10 and 12 MiB left 40 MiB). A texture over the limit makes its room again at each read. The buffer's contents were already "whatever the last texture left", so no caller reads them before writing, and nothing the title sees changes. Test: texture::read_buffer_tests::a_large_read_gives_its_room_back_when_it_is_over. On d44285197 it fails with "40 MiB kept after a read of 32 MiB". --- d3d12/crates/leonida-gpu/src/texture.rs | 76 ++++++++++++++++++++++++- 1 file changed, 75 insertions(+), 1 deletion(-) diff --git a/d3d12/crates/leonida-gpu/src/texture.rs b/d3d12/crates/leonida-gpu/src/texture.rs index 6282633d9f..d7779fda1b 100644 --- a/d3d12/crates/leonida-gpu/src/texture.rs +++ b/d3d12/crates/leonida-gpu/src/texture.rs @@ -459,9 +459,39 @@ fn with_read(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R { READ.with(|read| { let mut read = read.borrow_mut(); if read.len() < size { + // Exactly the room asked for: grown by doubling, a texture under + // [`read_kept`] could leave room over it, which would go below. + let more = size - read.len(); + read.reserve_exact(more); read.resize(size, 0); } - f(&mut read[..size]) + let out = f(&mut read[..size]); + // The buffer only grew, so each thread that refreshes textures (the + // submitting one and the helpers of `crate::shadow::wide_each`, which + // live for the run) kept the room of the largest texture it ever + // read until the end: 22 MB for a 4096² BC7 texture with its levels, + // 89 MB for one in RGBA8, on each of those threads (five on a PC of + // 16 logical processors). Room over [`read_kept`] goes when the read + // is over; the next texture that large makes its room again. + if read.capacity() > read_kept() { + *read = Vec::new(); + } + out + }) +} + +/// The bytes of read buffer a thread keeps from one texture to the next +/// (`LEONIDA_TEXTURE_READ_KEEP_MB`, 16). That holds a 4096² BC1 texture or +/// a 2048² BC7 one with their levels (11 and 5.6 MB), so that textures of +/// those sizes do not make their room again at every read. +fn read_kept() -> usize { + static KEPT: std::sync::OnceLock = std::sync::OnceLock::new(); + *KEPT.get_or_init(|| { + std::env::var("LEONIDA_TEXTURE_READ_KEEP_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(16) + .saturating_mul(1 << 20) }) } @@ -2560,6 +2590,50 @@ mod title_memory_tests { } } +#[cfg(test)] +mod read_buffer_tests { + use super::{READ, with_read}; + + /// The default of `LEONIDA_TEXTURE_READ_KEEP_MB`, in bytes. + const KEPT: usize = 16 << 20; + + /// The capacity of this thread's read buffer. + fn room() -> usize { + READ.with(|read| read.borrow().capacity()) + } + + /// A thread that refreshes textures keeps a read buffer of up to the + /// kept bytes from one texture to the next, but not the room of a larger + /// texture once its read is over: those threads (the submitting one and + /// the helpers of `shadow::wide_each`) live for the run, and each held + /// the largest texture it ever read until the end. The reads run on + /// threads of their own, as refreshes do, so that the buffer of the + /// thread the harness runs the test on (shared by the tests with + /// `--test-threads=1`) plays no part. + #[test] + fn a_large_read_gives_its_room_back_when_it_is_over() { + std::thread::scope(|threads| { + for _ in 0..2 { + threads.spawn(|| { + // Up to the kept bytes: kept for the next texture, also + // when the buffer grows from one under them. + with_read(KEPT * 5 / 8, |read| read.fill(1)); + with_read(KEPT * 3 / 4, |read| read.fill(1)); + assert!(room() >= KEPT * 3 / 4, "a read under the kept bytes keeps its room"); + // A larger texture is read whole, then its room goes. + with_read(2 * KEPT, |read| { + assert_eq!(read.len(), 2 * KEPT); + read[2 * KEPT - 1] = 2; + }); + assert!(room() <= KEPT, "{} MiB kept after a read of {} MiB", room() >> 20, (2 * KEPT) >> 20); + // And the next read is served as before. + with_read(4096, |read| assert_eq!(read.len(), 4096)); + }); + } + }); + } +} + /// How long this PC's card takes to make the allocations a staged texture needs, for /// `cargo test -p leonida-gpu allocation_costs -- --ignored --nocapture`. #[cfg(test)] From b179a98a0f3bf8244086d1f16e3fd90074c3d0aa Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:07:42 +0100 Subject: [PATCH 23/49] leonida-gpu: submitted lists hold no host list until reset, idle ones are trimmed (RS-HOST-LIST-ALLOCATOR-PEAK) A command allocator keeps the memory of the most ever recorded into it over its resets, and the pool of idle host lists hands its lists to any title list, so every host list grows to the size of the largest recording. At each submission, detach and detach_parts gave every title list (with LEONIDA_THIN=1, every back list) a new host list at once, which it kept, closed and unused, until the title reset it. So each title list kept one grown allocator alive besides those in flight, and the pool kept up to 512 more that nothing ever let go. Now a submission takes the list's host list and leaves it none; reset takes one from the pool (closed first, so its reset is the same as before). Once a second the sweep lets go of the oldest half of the idle lists nobody took since the last sweep, through retire, so the pool follows what was needed lately and the allocators are freed on the reaper thread. Tests: a_submitted_list_keeps_no_host_list_until_its_reset (64 title lists submitted four times hold no host list afterwards; it held 64 before) and idle_lists_nobody_takes_are_let_go (the pool goes from a burst of 512 to the 8 a steady need takes). --- d3d12/crates/leonida-gpu/src/host.rs | 3 +- d3d12/crates/leonida-gpu/src/list.rs | 229 ++++++++++++++++++++++----- 2 files changed, 189 insertions(+), 43 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index ceffbdf114..d4b8baeb01 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -419,7 +419,7 @@ pub(crate) fn references(object: &impl Interface) -> u32 { /// Once a second, before a submission starts: lets go of what nothing /// names any more (copies of windows of title memory, staging buffers, -/// host copies of textures the title fills). +/// host copies of textures the title fills, idle host lists nobody took). /// `LEONIDA_SWEEP=0` keeps everything, as before. fn sweep() { // The in-place probe and census, if asked for (`LEONIDA_INPLACE_PROBE`). @@ -446,6 +446,7 @@ fn sweep() { trim_spare_backs(); } crate::pool::room(host().and_then(|h| h.video_memory())); + crate::list::trim_idle(); crate::pipeline::trim_library(); crate::shadow::let_go_idle(); crate::texture::let_go_idle(); diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs index 48a898b925..683e389d1e 100644 --- a/d3d12/crates/leonida-gpu/src/list.rs +++ b/d3d12/crates/leonida-gpu/src/list.rs @@ -218,25 +218,73 @@ impl Detached { } } -/// A host list that has run and waits to be used again, and the bytes of -/// upload memory it keeps. +/// A host list that has run and waits to be used again. #[cfg(windows)] -struct Idle(crate::host::HostList, u64); +struct Idle(crate::host::HostList); // SAFETY: D3D12 objects are free-threaded, and an idle list is touched by // nobody until it is taken out again. #[cfg(windows)] unsafe impl Send for Idle {} +/// Things kept to be used again, the oldest first, each with the bytes of +/// upload memory it keeps. +#[cfg(windows)] +struct Pool { + kept: Vec<(T, u64)>, + bytes: u64, + /// The fewest kept at any time since the last [`Pool::trim`]: the + /// oldest that many were not taken since then. + low: usize, +} + +#[cfg(windows)] +impl Pool { + const fn new() -> Self { + Pool { kept: Vec::new(), bytes: 0, low: 0 } + } + + /// The thing given last. + fn take(&mut self) -> Option { + let (thing, bytes) = self.kept.pop()?; + self.bytes -= bytes; + self.low = self.low.min(self.kept.len()); + Some(thing) + } + + /// Keeps `thing`, which keeps `bytes`, unless that takes the pool past + /// `most` things or bytes: then it comes back. + fn give(&mut self, thing: T, bytes: u64, most: (usize, u64)) -> Option { + if self.kept.len() >= most.0 || self.bytes + bytes > most.1 { + return Some(thing); + } + self.bytes += bytes; + self.kept.push((thing, bytes)); + None + } + + /// Takes out the oldest half (rounded up) of the things nobody took + /// since the last trim, so that what is kept follows what was needed + /// lately. Halving rather than taking out all of them keeps a need that + /// comes and goes from making things anew every time. + fn trim(&mut self) -> Vec<(T, u64)> { + let gone: Vec<(T, u64)> = self.kept.drain(..self.low.div_ceil(2)).collect(); + self.bytes -= gone.iter().map(|(_, bytes)| bytes).sum::(); + self.low = self.kept.len(); + gone + } +} + /// Host lists that have run, reset and ready to record: the host side of /// a list a queue held, or of a part of a list cut at a wait, is taken -/// from the title's list at its submission, and the title's list needs -/// another. Each was made new and thrown away after its run: a hundred a -/// frame in gameplay, each two command allocators and two lists, and for -/// four in ten a budget and an argument buffer (run 61: "104 host lists -/// made 21.2 ms" a frame, and the graphics kernel's time to free them). +/// from the title's list at its submission, and the title's list takes +/// another at its next reset. Each was made new and thrown away after its +/// run: a hundred a frame in gameplay, each two command allocators and two +/// lists, and for four in ten a budget and an argument buffer (run 61: +/// "104 host lists made 21.2 ms" a frame, and the graphics kernel's time to +/// free them). #[cfg(windows)] -static IDLE: std::sync::Mutex<(Vec, u64)> = std::sync::Mutex::new((Vec::new(), 0)); +static IDLE: std::sync::Mutex> = std::sync::Mutex::new(Pool::new()); /// The most host lists kept idle (128 were too few: flights land several at /// a time, so lists were thrown away and others made in the same frame, with @@ -259,20 +307,30 @@ fn pools() -> bool { /// after its reset, or a new one. #[cfg(windows)] fn fresh_list() -> Option { - let idle = { - let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); - let taken = idle.0.pop(); - if let Some(Idle(_, bytes)) = &taken { - idle.1 -= bytes; - } - taken - }; + let idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()).take(); match idle { - Some(Idle(list, _)) => Some(list), + Some(Idle(list)) => Some(list), None => crate::host::host().and_then(|h| h.new_list().ok()), } } +/// Lets go of idle host lists nobody took lately ([`Pool::trim`]), once a +/// second (`crate::host::sweep`). A command allocator keeps the memory of +/// the most a list ever recorded into it over its resets, and the pool +/// hands its lists to any title list, so every idle list grows to the size +/// of the largest recording; the pool may keep [`IDLE_MOST`] of them, +/// which a burst of landed flights fills and nothing emptied before. +#[cfg(windows)] +pub(crate) fn trim_idle() { + let gone = IDLE.lock().unwrap_or_else(|e| e.into_inner()).trim(); + if !gone.is_empty() { + // Freeing allocators is the driver's work: done where retired + // objects are dropped (the reaper thread), not on the submitting + // thread that sweeps. + crate::host::retire(gone); + } +} + /// The host sides of lists whose submission has run (submissions are /// waited for; `ran` names the ones it ran, by their place in `lists`): /// what they held is let go, as before, and the host lists are reset and @@ -286,18 +344,16 @@ pub(crate) fn recycle(lists: Vec, ran: &[usize]) { // The descriptor slots and the upload memory its commands named. drop(_state); drop(_uploads); - if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 { + if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).kept.len() >= IDLE_MOST.0 { continue; } // As the title's reset does: what the list kept for its commands // goes, its allocators stay. host.reset(); let bytes = host.scratch_kept(); - let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); - if idle.0.len() < IDLE_MOST.0 && idle.1 + bytes <= IDLE_MOST.1 { - idle.0.push(Idle(host, bytes)); - idle.1 += bytes; - } + let refused = IDLE.lock().unwrap_or_else(|e| e.into_inner()).give(Idle(host), bytes, IDLE_MOST); + // (Dropped outside the lock.) + drop(refused); } } @@ -379,8 +435,8 @@ pub(crate) fn cut_list(this: This) -> bool { pub(crate) type Parts = Vec<(Vec, Vec, Vec)>; /// Takes the host sides of the submitted `lists`, part by part ([`cut`]), -/// and leaves each list a new, closed host list for its next reset, as -/// [`detach`] does. What comes back is in the order the queue runs it: a +/// and leaves each list without one until its next reset, as [`detach`] +/// does. What comes back is in the order the queue runs it: a /// new entry starts at every part that has waits; host lists without /// waits join the entry before them. The list's upload memory and draw /// state (its dynamic descriptor slots) go with its last part, which runs @@ -410,16 +466,11 @@ pub(crate) fn detach_parts(lists: &[This]) -> Parts { } continue; } - let Some(fresh) = fresh_list() else { - continue; - }; - // A new host list is open; the title's next call on its list is a - // reset, which wants it closed. - fresh.close(); // SAFETY: one of our lists, closed and submitted: nothing records // into it until the title resets it. let list = unsafe { &mut *this.cast_mut().cast::() }; - let Some(host) = list.host.replace(fresh) else { + // The list takes another host list at its reset ([`reset`]). + let Some(host) = list.host.take() else { continue; }; let earlier = std::mem::take(&mut list.earlier); @@ -488,8 +539,8 @@ pub(crate) fn ahead_of_frame() -> Option { } /// Takes the host sides of submitted lists (each once, however often the -/// submission names it) and leaves each list a new, closed host list for -/// its next reset: what was taken, and which of them run in what order. +/// submission names it) and leaves each list without one until its next +/// reset ([`reset`]): what was taken, and which of them run in what order. #[cfg(windows)] pub(crate) fn detach(lists: &[This]) -> (Vec, Vec) { let mut taken: Vec<(This, Detached)> = Vec::new(); @@ -502,17 +553,11 @@ pub(crate) fn detach(lists: &[This]) -> (Vec, Vec) { order.push(i); continue; } - let Some(fresh) = fresh_list() else { - continue; - }; - // A new host list is open; the title's next call on its list is a - // reset, which wants it closed. - fresh.close(); let list = this.cast_mut().cast::(); // SAFETY: one of our lists, closed and submitted: nothing records // into it until the title resets it. let (host, uploads, state) = unsafe { - let Some(host) = (*list).host.replace(fresh) else { + let Some(host) = (*list).host.take() else { continue; }; let uploads = @@ -711,6 +756,18 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT let list = unsafe { &mut *this.cast_mut().cast::() }; list.earlier.clear(); list.gate.clear(); + // A submission took the list's host list ([`detach`]): it takes one + // now. A submitted list used to get a new one at once and keep it + // until this reset, which for a list the title leaves alone for a + // while is a command allocator grown to the size of some other + // list's recording, kept for nothing. Closed, so that its reset + // below is the same as the one the list had before. + if list.host.is_none() + && let Some(fresh) = fresh_list() + { + fresh.close(); + list.host = Some(fresh); + } } #[cfg(windows)] with_state(this, |host, state| { @@ -2690,6 +2747,94 @@ mod tests { assert_eq!(release(allocator), 0); } + /// A title list that was submitted holds no host list, and so no command + /// allocator grown by what it recorded, until the title resets it. Each + /// used to get a new host list at its submission and keep it while it + /// was idle, so every title list kept one alive besides those in flight + /// and in the pool. + #[cfg(windows)] + #[test] + fn a_submitted_list_keeps_no_host_list_until_its_reset() { + if crate::host::host().is_none() { + eprintln!("no D3D12 device; the host lists of submitted lists are not tested"); + return; + } + const LISTS: usize = 64; + let null = std::ptr::null(); + let mut allocator = null; + assert_eq!(create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), S_OK); + let lists: Vec = (0..LISTS) + .map(|_| { + let mut list = null; + assert_eq!(create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), S_OK); + list + }) + .collect(); + let held = |lists: &[This]| lists.iter().filter(|&&l| host_list(l).is_some()).count(); + assert_eq!(held(&lists), LISTS, "a new list records at once"); + for round in 0..4 { + for &list in &lists { + // (A new list starts open.) + if round > 0 { + assert_eq!(reset(list, allocator, null), S_OK); + assert!(host_list(list).is_some(), "round {round}: a reset list records"); + } + assert_eq!(close(list), S_OK); + } + // Submitted, run and landed, as a queue that holds its lists + // does it: their host sides are taken and given back once run. + let (taken, order) = detach(&lists); + assert_eq!(taken.len(), LISTS); + recycle(taken, &order); + assert_eq!(held(&lists), 0, "round {round}: submitted lists keep host lists alive"); + } + let release = |o: This| slot:: u32>(o, 0x10)(o); + for list in lists { + assert_eq!(release(list), 0); + } + assert_eq!(release(allocator), 0); + } + + /// The idle pool follows what was needed lately: after a burst fills it + /// to the most, a steady need of a few lists a second leaves it with + /// about those few. Each trim lets go of the oldest half of those + /// nobody took since the one before, and never of those that were taken. + #[cfg(windows)] + #[test] + fn idle_lists_nobody_takes_are_let_go() { + let mut pool: Pool = Pool::new(); + for i in 0..IDLE_MOST.0 as u32 { + assert_eq!(pool.give(i, 1, IDLE_MOST), None); + } + assert_eq!(pool.give(9999, 1, IDLE_MOST), Some(9999), "no more than the most"); + assert_eq!(pool.give(9999, IDLE_MOST.1, (usize::MAX, IDLE_MOST.1)), Some(9999), "no more bytes than the most"); + // Given since the last trim: nobody had the time to take them. + assert!(pool.trim().is_empty()); + let mut kept = Vec::new(); + for second in 0..12 { + // Eight lists recorded, run and given back. + let taken: Vec = (0..8).map(|_| pool.take().expect("kept")).collect(); + for &t in &taken { + assert_eq!(pool.give(t, 1, IDLE_MOST), None); + } + let gone = pool.trim(); + assert!(gone.iter().all(|(t, _)| !taken.contains(t)), "second {second}: a list in use was let go"); + if second == 0 { + assert_eq!(gone.len(), (IDLE_MOST.0 - 8).div_ceil(2)); + assert_eq!(gone[0].0, 0, "the oldest go first"); + } + kept = taken; + } + assert_eq!(pool.kept.len(), 8, "what is kept is what was needed lately"); + assert_eq!(pool.bytes, 8); + assert!(pool.kept.iter().all(|(t, _)| kept.contains(t))); + // Nothing needed at all: the pool empties. + for _ in 0..8 { + pool.trim(); + } + assert!(pool.kept.is_empty() && pool.bytes == 0); + } + /// An offset near `u64::MAX` must not overflow and write outside the /// query destination buffer. #[test] From 692ca275891dec0e28a630a16726aef34754be2b Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:07:52 +0100 Subject: [PATCH 24/49] leonida-hle: the XTaskQueue thread pool starts few workers in a burst and trims idle ones (RS-XTASKQUEUE-POOL-TRIM) The pool behind thread-pool ports started a thread whenever more tasks waited than workers were idle, and created it while holding the pool's lock. A worker that was starting did not count, and it could not take the lock while tasks kept coming, so a burst of short callbacks started about one thread per callback. Workers then waited for good, so the pool kept its peak size, and every thread kept its stack and the title's per-thread state. Now a queued task starts a worker only when none is idle or starting, and a worker that takes a task while others still wait, with none idle or starting, starts the next before its task runs. A queued task always has a worker coming, so a callback that blocks on another still never starves it, but a burst of short callbacks is run by a few workers. The thread is created after the lock is released. A worker that waits 30 seconds without a task leaves while at least four others are idle. The new test queues 256 short callbacks on a pool of its own, then checks how many workers started and that the idle ones leave. On d44285197, with only a worker count added to the old pool for the test, 256 callbacks started 256 workers in one run and 42 in another, and none of them ever left. With the change, 2 workers started in each of the 53 runs measured, 24 of them with 8 runs at once. A second test checks that eight callbacks queued together, each waiting for all eight to start, all run. --- .../crates/leonida-hle/src/modules/xasync.rs | 162 +++++++++++++++--- 1 file changed, 139 insertions(+), 23 deletions(-) diff --git a/d3d12/crates/leonida-hle/src/modules/xasync.rs b/d3d12/crates/leonida-hle/src/modules/xasync.rs index d08d4f6bf1..293d500cc5 100644 --- a/d3d12/crates/leonida-hle/src/modules/xasync.rs +++ b/d3d12/crates/leonida-hle/src/modules/xasync.rs @@ -147,45 +147,101 @@ impl Port { } } -/// The thread pool behind thread-pool ports: idle workers are reused, and a -/// new one starts whenever more tasks wait than workers idle, so a callback -/// that blocks on another never starves it. Workers stay for reuse. +/// The thread pool behind thread-pool ports. Idle workers are reused, and +/// while tasks wait there is always a worker idle or starting to take them: +/// a task queued with none starts one, and a worker that takes a task while +/// others still wait, with none idle or starting, starts the next before its +/// task runs. So a callback that blocks on another never starves it, while a +/// burst of short tasks is run by a few workers instead of a thread each. +/// Each worker holds a stack and the title's per-thread state, so one that +/// has waited out `linger` with no task leaves, down to `keep` idle ones. struct Pool { - /// Queued tasks and the number of idle workers. - state: Mutex<(VecDeque, usize)>, + state: Mutex, ready: Condvar, + linger: Duration, + keep: usize, } -static POOL: Pool = Pool { - state: Mutex::new((VecDeque::new(), 0)), - ready: Condvar::new(), -}; +struct PoolState { + tasks: VecDeque, + /// Workers waiting for a task. + idle: usize, + /// Workers started that have not looked for a task yet: each takes one + /// without waiting, so a task queued meanwhile has a worker coming. + starting: usize, + /// Every worker that has not left: idle, starting or running a task. + workers: usize, +} + +/// Idle workers leave after 30 seconds without a task, down to four, so the +/// pool goes back to a few threads once a burst is over. +static POOL: Pool = Pool::new(Duration::from_secs(30), 4); impl Pool { + const fn new(linger: Duration, keep: usize) -> Pool { + Pool { + state: Mutex::new(PoolState { + tasks: VecDeque::new(), + idle: 0, + starting: 0, + workers: 0, + }), + ready: Condvar::new(), + linger, + keep, + } + } + fn submit(&'static self, task: Task) { let mut state = lock(&self.state); - state.0.push_back(task); - if state.0.len() > state.1 { - std::thread::spawn(move || self.work()); - } else { + state.tasks.push_back(task); + // An idle worker takes it, or the one starting does (and starts the + // next if more wait); with neither, one starts. + if state.idle > 0 { self.ready.notify_one(); + } else if state.starting == 0 { + self.start(state); } } - fn work(&self) { + /// Starts a worker. The thread is created after the lock is let go, as + /// creating it takes a while and the other workers need the lock. + fn start(&'static self, mut state: MutexGuard<'_, PoolState>) { + state.starting += 1; + state.workers += 1; + drop(state); + std::thread::spawn(move || self.work()); + } + + fn work(&'static self) { let mut state = lock(&self.state); + state.starting -= 1; loop { - while state.0.is_empty() { - state.1 += 1; - state = self.ready.wait(state).unwrap_or_else(|e| e.into_inner()); - state.1 -= 1; - } - let task = state.0.pop_front(); - drop(state); - if let Some(task) = task { + if let Some(task) = state.tasks.pop_front() { + // This task may block on one still queued, so that one needs + // a worker of its own coming. + if !state.tasks.is_empty() && state.idle == 0 && state.starting == 0 { + self.start(state); + } else { + drop(state); + } task.run(false); + state = lock(&self.state); + continue; + } + state.idle += 1; + let (next, waited) = self + .ready + .wait_timeout(state, self.linger) + .unwrap_or_else(|e| e.into_inner()); + state = next; + state.idle -= 1; + // Leaving with the queue empty leaves no task without a worker. + if waited.timed_out() && state.tasks.is_empty() && state.idle >= self.keep { + state.workers -= 1; + tracing::debug!(workers = state.workers, "task pool: an idle worker leaves"); + return; } - state = lock(&self.state); } } } @@ -1543,6 +1599,66 @@ mod tests { XTaskQueueCloseHandle(q); } + /// The workers `pool` has started that have not left. + fn workers(pool: &Pool) -> usize { + lock(&pool.state).workers + } + + /// Waits up to five seconds for `done`, and says whether it came. + fn within_seconds(done: impl Fn() -> bool) -> bool { + let start = std::time::Instant::now(); + while !done() && start.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(1)); + } + done() + } + + /// A burst of short callbacks (completions queued together, say) is run + /// by a few workers instead of a thread each, and the workers left idle + /// leave once the pool's linger is over, down to the ones it keeps. + #[test] + fn pool_workers_stay_few_in_a_burst_and_leave_when_idle() { + static BURST: Pool = Pool::new(Duration::from_millis(200), 1); + static RAN: AtomicU32 = AtomicU32::new(0); + extern "system" fn ran(_: *mut c_void, _: bool) { + RAN.fetch_add(1, Ordering::SeqCst); + } + for _ in 0..256 { + BURST.submit(Task::new(std::ptr::null_mut(), ran)); + } + assert!(within_seconds(|| RAN.load(Ordering::SeqCst) == 256)); + let started = workers(&BURST); + assert!(started <= 32, "{started} workers for 256 short callbacks"); + + assert!( + within_seconds(|| workers(&BURST) == 1), + "{} workers still there", + workers(&BURST) + ); + // The worker kept still runs what comes. + BURST.submit(Task::new(std::ptr::null_mut(), ran)); + assert!(within_seconds(|| RAN.load(Ordering::SeqCst) == 257)); + } + + /// Callbacks queued together that each wait for all of them to have + /// started still all run: a queued task always has a worker coming. + #[test] + fn pool_callbacks_queued_together_may_wait_for_each_other() { + static MEET: Pool = Pool::new(Duration::from_millis(200), 0); + static STARTED: AtomicU32 = AtomicU32::new(0); + static MET: AtomicU32 = AtomicU32::new(0); + extern "system" fn meet(_: *mut c_void, _: bool) { + STARTED.fetch_add(1, Ordering::SeqCst); + if within_seconds(|| STARTED.load(Ordering::SeqCst) == 8) { + MET.fetch_add(1, Ordering::SeqCst); + } + } + for _ in 0..8 { + MEET.submit(Task::new(std::ptr::null_mut(), meet)); + } + assert!(within_seconds(|| MET.load(Ordering::SeqCst) == 8)); + } + /// A dispatcher thread's loop, `while (XTaskQueueDispatch(queue, port, /// INFINITE));`, ends when its queue is terminated: nothing can be /// submitted to it any more, so nothing else would ever wake it. From 6ab9419d89f7a4bf7d3953d29c5f2322af7cd59a Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:09:13 +0100 Subject: [PATCH 25/49] leonida-gpu: snapshot buffers no snapshot took for the idle time leave the pool (RS-SNAPSHOT-POOL-TRIM) The pool of snapshot buffers (shadow.rs POOL, pooled and give_back) kept up to 512 MiB, or its largest buffer when that is bigger (a snapshot is a whole copy's size), and nothing ever trimmed it: after a burst of submissions whose shaders write copies in the PC's memory, that memory stayed committed for the rest of the run. Each pooled buffer now carries when it was given back, and shadow::let_go_idle (the sweep once a second before a submission) lets go of those no snapshot took for crate::host::ram_idle_ms: five minutes with 12 GiB of the PC's memory free and LEONIDA_KEEP_FREED on, 10 s otherwise, down to 2 s when memory is short. A buffer in use is taken and given back at every snapshot, so it starts its idle time again and stays. The count and byte limits of give_back are as they were, and nothing the title sees changes. Test: shadow::snapshot_pool_tests::buffers_the_pool_kept_for_the_idle_time_go. On d44285197 it does not build (idle_snapshots is new); with idle_snapshots as a stub that takes nothing out, as d44285197 behaves, it fails with "0 of the eight idle buffers let go". --- d3d12/crates/leonida-gpu/src/shadow.rs | 71 ++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 9 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 8415889fac..572bba2cf1 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -1785,8 +1785,9 @@ mod relay_tests { } } -/// Snapshot memory kept for reuse (already touched, so no page faults). -static POOL: Mutex>> = Mutex::new(Vec::new()); +/// Snapshot memory kept for reuse (already touched, so no page faults), +/// each buffer with when it was given back ([`crate::host::coarse_ms`]). +static POOL: Mutex, u64)>> = Mutex::new(Vec::new()); /// An empty buffer with room for `n` bytes, from the pool if it has one /// of about that size: a small copy's snapshot took the 174 MB buffer kept @@ -1798,11 +1799,11 @@ fn pooled(n: usize) -> Vec { let fit = pool .iter() .enumerate() - .filter(|(_, v)| v.capacity() >= n && v.capacity() <= most) - .min_by_key(|(_, v)| v.capacity()) + .filter(|(_, (v, _))| v.capacity() >= n && v.capacity() <= most) + .min_by_key(|(_, (v, _))| v.capacity()) .map(|(i, _)| i); let mut v = match fit { - Some(i) => pool.swap_remove(i), + Some(i) => pool.swap_remove(i).0, None => Vec::with_capacity(n), }; v.clear(); @@ -1828,11 +1829,12 @@ fn snapshots_kept() -> usize { /// bytes in all. fn give_back(v: Vec) { const KEPT: usize = 512 << 20; + let now = crate::host::coarse_ms(); let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); - pool.push(v); - pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); + pool.push((v, now)); + pool.sort_by_key(|(v, _)| std::cmp::Reverse(v.capacity())); let (mut kept, mut total) = (0, 0usize); - for v in pool.iter().take(snapshots_kept()) { + for (v, _) in pool.iter().take(snapshots_kept()) { total = total.saturating_add(v.capacity()); if kept > 0 && total > KEPT { break; @@ -1845,6 +1847,54 @@ fn give_back(v: Vec) { drop(gone); } +/// Lets go of the snapshot buffers no snapshot took for `idle_ms` +/// ([`crate::host::ram_idle_ms`]). Nothing trimmed the pool: after a burst of +/// submissions whose shaders write copies in the PC's memory it kept up to +/// 512 MiB (or its largest buffer, a whole copy's size: 174 MB for the big +/// heap's, run 24) for the rest of the run. A buffer a snapshot takes and +/// gives back starts its idle time again. +fn let_go_idle_snapshots(idle_ms: u64) { + let now = crate::host::coarse_ms(); + let gone = idle_snapshots(&mut POOL.lock().unwrap_or_else(|e| e.into_inner()), now, idle_ms); + // (Given back to the kernel without the lock, as in `give_back`.) + drop(gone); +} + +/// Takes out of `pool` the buffers given back `idle_ms` or more before +/// `now`; the others keep their order. +fn idle_snapshots(pool: &mut Vec<(Vec, u64)>, now: u64, idle_ms: u64) -> Vec<(Vec, u64)> { + pool.extract_if(.., |(_, at)| now.saturating_sub(*at) >= idle_ms).collect() +} + +#[cfg(test)] +mod snapshot_pool_tests { + use super::idle_snapshots; + + /// Buffers no snapshot took for the idle time leave the pool, and those + /// given back since stay: the pool kept up to 512 MiB (or its largest + /// buffer) of the PC's memory for the rest of the run once a burst of + /// submissions had filled it. + #[test] + fn buffers_the_pool_kept_for_the_idle_time_go() { + const IDLE_MS: u64 = 10_000; + // Eight buffers given back at 1 s, as a burst leaves them (the + // pool's 512 MiB are eight of 64 MiB; these are smaller), and one at + // 9 s. + let mut pool: Vec<(Vec, u64)> = (0..8).map(|_| (Vec::with_capacity(64 << 10), 1_000)).collect(); + pool.push((Vec::with_capacity(64 << 10), 9_000)); + // Under the idle time: all stay. + assert!(idle_snapshots(&mut pool, 10_999, IDLE_MS).is_empty()); + assert_eq!(pool.len(), 9); + // The idle time since the burst: its eight go, the newer one stays. + let gone = idle_snapshots(&mut pool, 11_000, IDLE_MS); + assert_eq!(gone.len(), 8, "{} of the eight idle buffers let go", gone.len()); + assert_eq!(pool.iter().map(|(_, at)| *at).collect::>(), [9_000]); + // And it goes once it has been idle as long; nothing is reserved. + assert_eq!(idle_snapshots(&mut pool, 19_000, IDLE_MS).len(), 1); + assert!(pool.is_empty()); + } +} + const NOT_WATCHED: u8 = 2; /// Watched, not by the kernel but by the guards, when last asked about. const GUARDED: u8 = 3; @@ -3671,6 +3721,9 @@ pub(crate) fn window_use() -> [u64; 8] { /// The next read of that memory makes a new copy and copies the window /// again. Called before a submission starts, by the thread that submits. pub(crate) fn let_go_idle() { + // The snapshot buffers no snapshot took for the PC memory's idle time + // go too, whether or not there are windows. + let_go_idle_snapshots(crate::host::ram_idle_ms(crate::host::available_physical_ram())); const IDLE_FRAMES: u64 = 4; let gone: Vec> = { // Held from the look to the removal: `loose` hands a copy out @@ -3724,7 +3777,7 @@ pub(crate) fn memory() -> [u64; 6] { }; let (kept, kept_bytes) = { let pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); - (pool.len() as u64, pool.iter().map(|v| v.capacity() as u64).sum::()) + (pool.len() as u64, pool.iter().map(|(v, _)| v.capacity() as u64).sum::()) }; [ LIVE[0].load(Ordering::Relaxed), From 922ea46fa76acac0ac26056a478540639a3c89f7 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:09:21 +0100 Subject: [PATCH 26/49] leonida-gpu: title pipelines of one graphics state share it (RS-GRAPHICS-STATE-INTERN) Every title pipeline created from a stream kept its own boxed copy of the graphics state (about 540 bytes inline, plus its input elements and one heap string per semantic name) for as long as the title holds the pipeline, which is the whole session. The title creates some 84,000 pipelines from about 5,700 distinct states, and draws with only about 2,000 of them. Pending now holds an Arc to one copy per state. The copy is found by a hash of describe(), which Pending::new already computes for the key and which holds every field of the state (it also names the host pipeline in the library), so equal descriptions are equal states. The table holds the states weakly, so a state is freed with the last pipeline that has it, and it drops the dead entries each time it doubles. Compute pipelines created from a stream, which all carry the default state, now share one. Nothing the title sees changes: the states, keys and library names are the same as before. --- d3d12/crates/leonida-gpu/src/pipeline.rs | 38 +++++++++++++--- d3d12/crates/leonida-gpu/src/pipeline/make.rs | 44 +++++++++++++++++-- 2 files changed, 72 insertions(+), 10 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/pipeline.rs b/d3d12/crates/leonida-gpu/src/pipeline.rs index 709a4cc98a..4441906f5b 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline.rs @@ -1008,10 +1008,10 @@ mod tests { /// The stream layout the title builds (title+0x86f090): root /// signature, five shader slots (the first a mesh shader), blend, sample /// mask, rasterizer, depth-stencil 1, sample description, input layout, - /// topology, render target and depth formats: 0x2b0 bytes. - #[test] - fn streams_yield_their_shaders() { - let (ms, ps) = ([9u8; 7], [4u8; 5]); + /// topology, render target and depth formats: 0x2b0 bytes. With mesh + /// shader `ms`, pixel shader `ps`, topology type `topology` and one + /// render target of format 28. + fn mesh_stream(ms: &[u8], ps: &[u8], topology: u64) -> This { let mut stream = vec![0u8; 0x2b0]; let mut put = |at: usize, v: u64| stream[at..at + 8].copy_from_slice(&v.to_le_bytes()); for (at, kind) in [ @@ -1036,8 +1036,7 @@ mod tests { put(0x20, ms.len() as u64); put(0x30, ps.as_ptr() as u64); put(0x38, ps.len() as u64); - // Topology type 3 (triangles), one render target of format 28. - put(0x278, 14 | 3 << 32); + put(0x278, 14 | topology << 32); put(0x280, 15 | 28 << 32); put(0x2a0, 1 << 32); let desc = StreamDesc { @@ -1047,6 +1046,14 @@ mod tests { let mut p = std::ptr::null(); let hr = create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p); assert_eq!(hr, S_OK); + p + } + + #[test] + fn streams_yield_their_shaders() { + let (ms, ps) = ([9u8; 7], [4u8; 5]); + // Topology type 3 (triangles). + let p = mesh_stream(&ms, &ps, 3); assert_eq!(shaders(p), [("mesh", ms.to_vec()), ("pixel", ps.to_vec())]); #[cfg(windows)] { @@ -1058,4 +1065,23 @@ mod tests { ); } } + + /// Pipelines created with the same graphics state share one copy of it, + /// and one with another state has its own. Each title pipeline kept a + /// copy of its own for the session: 84,000 of them, of some 5,700 + /// different states. + #[cfg(windows)] + #[test] + fn pipelines_of_one_graphics_state_share_it() { + let (ms, ps) = ([7u8; 9], [6u8; 3]); + let state = |p: This| -> *const host::GraphicsState { + pipeline(p).host.graphics.as_deref().unwrap() + }; + let (a, b) = (mesh_stream(&ms, &ps, 3), mesh_stream(&ms, &ps, 3)); + assert_eq!(state(a), state(b)); + // Topology type 2 (lines). + let lines = mesh_stream(&ms, &ps, 2); + assert_ne!(state(a), state(lines)); + assert_eq!(pipeline(lines).host.graphics.as_deref().unwrap().topology.0, 2); + } } diff --git a/d3d12/crates/leonida-gpu/src/pipeline/make.rs b/d3d12/crates/leonida-gpu/src/pipeline/make.rs index 70588b4e20..9e570daae4 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/make.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/make.rs @@ -21,9 +21,9 @@ //! its end (run textures-d2, the first after a new translation; Belobug //! 18e57db8 found the same). -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; -use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, Weak}; use std::time::{Duration, Instant}; use super::Shader; @@ -32,7 +32,8 @@ use super::host::{GraphicsState, HostPipeline, TargetFormats}; /// What a host pipeline is made from, and the host pipeline once made. pub(crate) struct Pending { shaders: Vec>, - pub(crate) graphics: Option>, + /// Shared with every pipeline of the same state ([`shared_state`]). + pub(crate) graphics: Option>, queue_state: AtomicU8, /// Taken by a worker from [`Queue::slow`]. was_slow: AtomicBool, @@ -116,17 +117,19 @@ unsafe impl Sync for Pending {} impl Pending { pub(crate) fn new(shaders: Vec>, graphics: Option>) -> Pending { + let described = graphics.as_ref().map(|g| g.describe()); let mut key = blake3::Hasher::new(); for s in &shaders { key.update(s.stage.as_bytes()); key.update(s.hash.as_bytes()); } - key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); + key.update(described.as_deref().unwrap_or_default().as_bytes()); let scene_input = scene_input(&shaders); let screen = (graphics.as_ref().is_some_and(|g| g.screen_pass()) && shaders.iter().all(|s| s.stage != "mesh")) || scene_input; let left_out = left_out(&shaders); + let graphics = graphics.zip(described).map(|(g, described)| shared_state(g, &described)); Pending { screen, scene_input, @@ -188,6 +191,39 @@ impl Pending { } } +/// The one copy of the graphics state `state`, described as `described`: +/// pipelines of the same state share it. The title creates 84,000 pipelines +/// from some 5,700 different states, and each kept a copy of its own for +/// the session (about 540 bytes, its input elements and their names on +/// top). The description holds everything the state does (it names the +/// host pipeline in the library), so equal descriptions are equal states. +/// Held weakly: a state goes with the last pipeline that has it, and the +/// table lets go of those gone each time it has doubled. +fn shared_state(state: Box, described: &str) -> Arc { + struct Held(Weak); + // SAFETY: as for `Pending`: a state is only read after creation. + unsafe impl Send for Held {} + /// The states by the hash of their description, and the size at which + /// the table is next swept of states gone. + static STATES: Mutex, usize)>> = Mutex::new(None); + const SWEEP_AT: usize = 1024; + let id = *blake3::hash(described.as_bytes()).as_bytes(); + let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner()); + let (table, sweep_at) = states.get_or_insert_with(|| (HashMap::new(), SWEEP_AT)); + if let Some(shared) = table.get(&id).and_then(|held| held.0.upgrade()) { + return shared; + } + // (The input elements point into the names' own buffers, which the + // move into the shared allocation leaves where they are.) + let shared: Arc = Arc::from(state); + table.insert(id, Held(Arc::downgrade(&shared))); + if table.len() >= *sweep_at { + table.retain(|_, held| held.0.strong_count() > 0); + *sweep_at = (table.len() * 2).max(SWEEP_AT); + } + shared +} + /// Why a pipeline has no host pipeline (diagnostics): its shaders that do /// not translate, else "refused" or "being made"; `None` if it has one. #[cfg(feature = "diagnostics")] From a505e149843b69be193f9bd1c439512894db8fe7 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:09:24 +0100 Subject: [PATCH 27/49] leonida-gpu: thin lists give back uploads a reset or release leaves behind (RS-THIN-UPLOAD-DROP) With LEONIDA_THIN=1 (scripts/play.ps1 sets it), allocate_upload writes the Box it made into the list's words, and translate takes it back and keeps it for the list of ours. Words are handed over every CHUNK words and at Close. A title list reset or released while it records (no Close) cleared the words not handed over yet in Front::leave, so their uploads were never dropped and their 64 KiB arena blocks stayed taken for good. Front::leave now walks those words and drops the uploads they name before clearing them. Words already handed over are always translated, also for a recording let go of (translate takes the upload back before it skips anything), so Recording's drop needs nothing. The new test puts an upload into a recording's words and resets the list (and, in a second round, drops it) before any hand-over, then checks the upload was given back; a test-only list in Upload's drop records which uploads were. Reset without Close and release of an open list are rare, so this is small in practice (sweep R4-06). --- d3d12/crates/leonida-gpu/src/list/thin.rs | 44 +++++++++++++++++++++++ d3d12/crates/leonida-gpu/src/upload.rs | 9 +++++ 2 files changed, 53 insertions(+) diff --git a/d3d12/crates/leonida-gpu/src/list/thin.rs b/d3d12/crates/leonida-gpu/src/list/thin.rs index f262325444..f4600d2e88 100644 --- a/d3d12/crates/leonida-gpu/src/list/thin.rs +++ b/d3d12/crates/leonida-gpu/src/list/thin.rs @@ -83,6 +83,11 @@ impl Front { { recording.abandoned.store(true, Release); } + // Upload memory that only these words name is given back by + // `translate`, which they never reach now: it goes here, or its + // blocks stay taken for good. (Words handed over are always + // translated, also those of a recording let go of.) + free_uploads(&self.words); self.words.clear(); } @@ -690,6 +695,21 @@ extern "system" fn copy_texture_region_x( copy_texture_region(this, dst, x, y, z, src, source_box); } +/// Gives back the upload memory the `UPLOAD` calls of `stream` name, for a +/// stream that is never translated ([`translate`] keeps it for its list). +fn free_uploads(stream: &[u64]) { + let mut i = 0; + while i < stream.len() { + let (op, len) = (stream[i] & 0xffff, (stream[i] >> 16) as usize); + if op == UPLOAD { + // SAFETY: made by `allocate_upload`, named once, in a stream that + // is never translated. + drop(unsafe { Box::from_raw(stream[i + 1] as *mut Upload) }); + } + i += 1 + len; + } +} + /// Makes the calls of a stream on `list`: how many, and whether the last one /// closed it. Once `left` says so only what must not be lost is done. fn translate(list: This, stream: &[u64], left: impl Fn() -> bool) -> (u64, bool) { @@ -929,4 +949,28 @@ mod tests { assert_eq!(kept[1], 2); assert_eq!(record(0), [0; RECORD]); } + + /// Upload memory that only words not handed over yet name is given back + /// when the list is reset or released before it is closed: those words + /// are never translated, which is where it is given back otherwise. + #[test] + fn uploads_of_words_never_handed_over_are_given_back() { + for released in [false, true] { + let mut f = Front::default(); + f.begin(0, std::ptr::null()); + let mut upload = Upload::new(100).unwrap(); + let start = upload.start() as usize; + // Only what is given back from now on counts: an upload at this + // place before was another one. + let before = held(&crate::upload::GIVEN_BACK).len(); + f.put(UPLOAD, &[Box::into_raw(Box::new(upload)) as u64]); + if released { + drop(f); + } else { + f.begin(0, std::ptr::null()); + } + let given_back = held(&crate::upload::GIVEN_BACK); + assert!(given_back[before..].contains(&start), "released {released}: never given back"); + } + } } diff --git a/d3d12/crates/leonida-gpu/src/upload.rs b/d3d12/crates/leonida-gpu/src/upload.rs index 172d6928d3..b148fac7d6 100644 --- a/d3d12/crates/leonida-gpu/src/upload.rs +++ b/d3d12/crates/leonida-gpu/src/upload.rs @@ -122,8 +122,17 @@ impl Upload { } } +/// Where the uploads given back started, in order, so the tests can see +/// which were. +#[cfg(test)] +pub(crate) static GIVEN_BACK: Mutex> = Mutex::new(Vec::new()); + impl Drop for Upload { fn drop(&mut self) { + // Noted before the blocks are free, so that an upload made at the + // same place later is noted after this one. + #[cfg(test)] + GIVEN_BACK.lock().unwrap_or_else(|e| e.into_inner()).push(self.start() as usize); let Kind::Low(at, len) = self.0 else { return }; let mut arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner()); if let Some(arena) = arenas.iter_mut().find(|a| (a.at..a.at + a.taken.len() * BLOCK).contains(&at)) { From 11c9d1ac7cfa8522667ec0b2bf2edab8914fe2b2 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:11:11 +0100 Subject: [PATCH 28/49] leonida-hle: XApu decodes each packet into memory the connection keeps (RS-APU-SCRATCH) process() allocated a zeroed Vec of MAX_FRAMES * channels, 46 KB for stereo, for every PROCESS command, used it for one decode and freed it again: about 50 times a second for every stream that plays, all of it under the connection's lock. The connection's State now holds that memory, made once in XApuConnect for two channels; process() decodes into a slice of it. Only the frames the packet decoded are read back, so what an earlier packet left in it does not matter, and the lock that guards the decoders guards it too. The new test counts, through a test-only global allocator, this thread's allocations of a stereo packet's PCM size or more while ten packets decode after a first one: ten before, none now. The allocator is left out when the diagnostics or mimalloc features bring their own. This is processor time more than memory: the heap gave the same block back each time, so the footprint does not change (sweep R2-06). --- d3d12/crates/leonida-hle/src/modules/apu.rs | 159 +++++++++++++++++++- 1 file changed, 154 insertions(+), 5 deletions(-) diff --git a/d3d12/crates/leonida-hle/src/modules/apu.rs b/d3d12/crates/leonida-hle/src/modules/apu.rs index 9027da0a45..81e5bfcaa2 100644 --- a/d3d12/crates/leonida-hle/src/modules/apu.rs +++ b/d3d12/crates/leonida-hle/src/modules/apu.rs @@ -137,6 +137,11 @@ struct State { results: VecDeque, commands: u32, dequeued: u32, + /// What a packet decodes into before its frames are copied out: room for + /// the longest packet of two channels, made once. Each packet had its + /// own, 46 KB allocated and zeroed for each of the 50 packets a second + /// of every stream that plays. + pcm: Vec, } fn lock(c: &Connection) -> std::sync::MutexGuard<'_, State> { @@ -210,6 +215,7 @@ pub extern "system" fn XApuConnect( results: VecDeque::new(), commands: 0, dequeued: 0, + pcm: vec![0.0; MAX_FRAMES * 2], }), }); // SAFETY: checked non-null. @@ -249,6 +255,9 @@ pub extern "system" fn XApuEnqueueCommand( // SAFETY: a connection from `XApuConnect`; every command starts with an id. let (connection, id) = unsafe { (&*handle, command.read_unaligned()) }; let mut state = lock(connection); + // (Through a plain reference, so a decoder and the PCM memory can be + // borrowed at once.) + let state = &mut *state; let stream = id.stream as usize; if stream >= state.streams.len() { return INVALID_STREAM; @@ -300,7 +309,7 @@ pub extern "system" fn XApuEnqueueCommand( // SAFETY: a process command is this struct. let command = unsafe { command.cast::().read_unaligned() }; match decoder { - Some(d) => process(d, connection.options, &command, &mut result), + Some(d) => process(d, connection.options, &command, &mut state.pcm, &mut result), None => result.error = INVALID_STREAM, } } @@ -321,8 +330,15 @@ pub extern "system" fn XApuEnqueueCommand( } /// Decodes one packet into the command's output buffer, keeping the frames -/// from `first_frame` on, at most `frame_count` of them. -fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &mut ApuResult) { +/// from `first_frame` on, at most `frame_count` of them; `pcm` is room for +/// the longest packet of two channels. +fn process( + decoder: &mut OpusDecoder, + options: u32, + command: &Process, + pcm: &mut [f32], + result: &mut ApuResult, +) { let channels = decoder.channels(); let (input, input_length) = (command.input, command.input_length); let (output, output_length) = (command.output, command.output_length); @@ -335,8 +351,10 @@ fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: & } // SAFETY: the title's packet in its connection memory. let packet = unsafe { std::slice::from_raw_parts(input, input_length as usize) }; - let mut pcm = vec![0f32; MAX_FRAMES * channels]; - let decoded = match decoder.decode(packet, MAX_FRAMES, &mut pcm) { + // Only what this packet decodes is read back, so what an earlier one + // left in it does not matter. + let pcm = &mut pcm[..MAX_FRAMES * channels]; + let decoded = match decoder.decode(packet, MAX_FRAMES, pcm) { Ok(n) => n, Err(_) => { result.error = BAD_PACKET; @@ -540,6 +558,137 @@ mod tests { assert_eq!(XApuDisconnect(handle), S_OK); } + /// Counts this thread's allocations of a stereo packet's PCM or larger, + /// for what a packet costs. Not with the allocators the features bring. + #[cfg(not(any(feature = "diagnostics", feature = "mimalloc")))] + mod counting { + use std::alloc::{GlobalAlloc, Layout, System}; + use std::cell::Cell; + + const LARGE: usize = super::MAX_FRAMES * 2 * size_of::(); + + std::thread_local! { + pub(super) static COUNT: Cell = const { Cell::new(0) }; + } + + fn note(size: usize) { + if size >= LARGE { + let _ = COUNT.try_with(|n| n.set(n.get() + 1)); + } + } + + struct Counting; + + // SAFETY: everything goes to the system allocator as it came. + unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + note(layout.size()); + // SAFETY: the caller's contract, passed on. + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + note(layout.size()); + // SAFETY: as above. + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn realloc(&self, at: *mut u8, layout: Layout, size: usize) -> *mut u8 { + note(size); + // SAFETY: as above. + unsafe { System.realloc(at, layout, size) } + } + + unsafe fn dealloc(&self, at: *mut u8, layout: Layout) { + // SAFETY: as above. + unsafe { System.dealloc(at, layout) } + } + } + + #[global_allocator] + static HEAP: Counting = Counting; + } + + /// A packet decodes into memory the connection keeps: each of the 50 + /// packets a second of every stream that plays allocated and zeroed + /// 46 KB of its own. + #[cfg(not(any(feature = "diagnostics", feature = "mimalloc")))] + #[test] + fn packets_decode_without_memory_of_their_own() { + let input = ConnectInput { + process: DECODE_OPUS, + streams: 1, + commands_per_stream: 2, + memory: 0x2_0000, + frames_per_output: 0, + options: 0, + }; + let mut output = ConnectOutput { + memory: std::ptr::null_mut(), + result_event: std::ptr::null_mut(), + }; + let mut handle = std::ptr::null_mut(); + assert_eq!(XApuConnect(&input, &mut output, &mut handle), S_OK); + let base = output.memory.cast::(); + let activate = Activate { + id: id(ACTIVATE, 0), + channels: 2, + init_length: 0, + init: std::ptr::null(), + start_pitch: 1.0, + processing_length: 0, + processing: std::ptr::null_mut(), + }; + let mut result = std::mem::MaybeUninit::::zeroed(); + assert_eq!( + XApuEnqueueCommand(handle, (&raw const activate).cast(), std::ptr::null_mut()), + S_OK + ); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + + let tone: Vec = (0..960 * 2) + .map(|i| ((i / 2) as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5) + .collect(); + let mut encoder = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); + let mut packet = [0u8; 1500]; + let n = encoder.encode(&tone, 960, &mut packet).unwrap(); + // SAFETY: inside the connection memory. + unsafe { std::ptr::copy_nonoverlapping(packet.as_ptr(), base, n) }; + let process = Process { + id: id(PROCESS, 0), + pitch_ramp: 0.0, + target_pitch: 1.0, + first_frame: 0, + frame_count: 960, + input_length: n as u32, + input: base, + output_length: 960 * 8, + output: base.wrapping_add(0x1_0000), + }; + let mut decode = || { + assert_eq!( + XApuEnqueueCommand(handle, (&raw const process).cast(), std::ptr::null_mut()), + S_OK + ); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + // SAFETY: written above. + let error = unsafe { result.assume_init() }.error; + assert_eq!(error, S_OK); + }; + // The first packet may set up the decoder's own memory. + decode(); + let before = counting::COUNT.with(|n| n.get()); + for _ in 0..10 { + decode(); + } + let large = counting::COUNT.with(|n| n.get()) - before; + assert_eq!( + large, 0, + "10 packets made {large} allocations of a packet's PCM or larger" + ); + assert_eq!(XApuDisconnect(handle), S_OK); + } + #[test] fn decodes_into_unaligned_output_interleaved_and_deinterleaved() { let tone: Vec = (0..960 * 2) From ff0b7289efe5f47f74190963709c49cfe2f57a66 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:12:13 +0100 Subject: [PATCH 29/49] leonida-gpu: spare buffers of view copies are capped at 64 MiB and go when idle (RS-EXACT-SPARE-CAP) exact() parks the buffers of the per-view copies it sweeps in EXACT_SPARE for the next copy of the same width. The list was capped at 1,024 buffers and nothing else: a spare left it only when a view of exactly its width came again, so spares of widths that never came back stayed for the rest of the run. Each is a committed buffer in the PC's memory, at least a 64 KiB block and up to 64 MiB (exact's largest view), so a full list was at least 64 MiB and could be far more. Now a buffer is parked only while the spares, counted in whole 64 KiB blocks, stay within 64 MiB as well as 1,024 buffers (what comes after goes, as before), and each spare carries when it was parked. shadow::let_go_idle (the sweep once a second before a submission) retires the spares no copy took for crate::host::ram_idle_ms (five minutes with 12 GiB of the PC's memory free and LEONIDA_KEEP_FREED on, 10 s otherwise, down to 2 s when memory is short), through host::retire_resource as idle windows go. The same few widths the title's ring gives every frame are still reused, and nothing the title sees changes. Test: shadow::exact_spare_tests::spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle. On d44285197 it does not build (park, idle_spares and Spare are new); with d44285197's rule ported into them (count only, nothing ages out) it fails with "1024 spares hold 160 MiB". --- d3d12/crates/leonida-gpu/src/shadow.rs | 115 +++++++++++++++++++++++-- 1 file changed, 107 insertions(+), 8 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 8415889fac..330a54b699 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -3672,6 +3672,9 @@ pub(crate) fn window_use() -> [u64; 8] { /// again. Called before a submission starts, by the thread that submits. pub(crate) fn let_go_idle() { const IDLE_FRAMES: u64 = 4; + // The spare buffers of copies of views' own bytes that no copy took for + // the PC memory's idle time go too, whether or not there are windows. + let_go_idle_spares(crate::host::ram_idle_ms(crate::host::available_physical_ram())); let gone: Vec> = { // Held from the look to the removal: `loose` hands a copy out // under the same lock, so none is handed out in between. @@ -6546,15 +6549,17 @@ pub(crate) fn exact(address: u64, len: u64) -> Option> { let width = len.next_multiple_of(256); let spare = { let mut spare = EXACT_SPARE.lock().unwrap_or_else(|e| e.into_inner()); - for shadow in gone.drain(..) { - if spare.len() < SPARE_MOST && shadow.place.is_none() { - spare.push((shadow.width(), shadow.buffer.clone(), shadow.data as usize)); - } + if !gone.is_empty() { + let let_go = gone + .drain(..) + .filter(|shadow| shadow.place.is_none()) + .map(|shadow| (shadow.width(), shadow.buffer.clone(), shadow.data as usize)); + park(&mut spare, let_go, crate::host::coarse_ms()); } spare.iter().position(|(w, ..)| *w == width).map(|i| spare.swap_remove(i)) }; let (buffer, data) = match spare { - Some((_, buffer, data)) => (buffer, data as *mut u8), + Some((_, buffer, data, _)) => (buffer, data as *mut u8), None => host()?.shared_buffer(width)?, }; crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}")); @@ -6575,11 +6580,57 @@ pub(crate) fn exact(address: u64, len: u64) -> Option> { Some(shadow) } -/// Leonida: buffers of copies [`exact`] let go, with their widths and where -/// they are mapped, for its next copies of the same width. -static EXACT_SPARE: Mutex> = Mutex::new(Vec::new()); +/// Leonida: buffers of copies [`exact`] let go, for its next copies of the +/// same width. +static EXACT_SPARE: Mutex>> = Mutex::new(Vec::new()); +/// A spare buffer: its width, the buffer, where it is mapped, and when it +/// was parked ([`crate::host::coarse_ms`]). +type Spare = (u64, B, usize, u64); /// At most so many are kept (what comes after goes, as before). const SPARE_MOST: usize = 1024; +/// And at most so many bytes of the PC's memory, each buffer counted in the +/// whole 64 KiB blocks a committed buffer takes. A spare is reused only for +/// a view of the same width, and with the count alone a spare of a width +/// that never came back stayed for the rest of the run: a full list was at +/// least 64 MiB, since no buffer takes less than a block, and could be up +/// to 64 MiB a buffer ([`exact`]'s largest view). +const SPARE_BYTES: u64 = 64 << 20; + +/// Parks the buffers `let_go` (width, buffer, where it is mapped) among +/// `spare` at `now`, while those hold fewer than [`SPARE_MOST`] and room +/// for it within [`SPARE_BYTES`]; the others go, as before. +fn park(spare: &mut Vec>, let_go: impl IntoIterator, now: u64) { + let committed = |width: u64| width.next_multiple_of(64 << 10); + let mut bytes: u64 = spare.iter().map(|&(width, ..)| committed(width)).sum(); + for (width, buffer, data) in let_go { + if spare.len() < SPARE_MOST && bytes + committed(width) <= SPARE_BYTES { + bytes += committed(width); + spare.push((width, buffer, data, now)); + } + } +} + +/// Takes out of `spare` the buffers parked `idle_ms` or more before `now`. +fn idle_spares(spare: &mut Vec>, now: u64, idle_ms: u64) -> Vec { + spare + .extract_if(.., |&mut (.., parked)| now.saturating_sub(parked) >= idle_ms) + .map(|(_, buffer, ..)| buffer) + .collect() +} + +/// Lets go of the spare buffers of [`exact`] that no copy took for +/// `idle_ms` ([`crate::host::ram_idle_ms`]). The title's ring gives the same +/// few widths every frame, so their spares are taken again long before +/// that; one that stays so long is of a width that did not come back. As +/// idle windows of title memory do, they go through +/// [`crate::host::retire_resource`]. +fn let_go_idle_spares(idle_ms: u64) { + let now = crate::host::coarse_ms(); + let gone = idle_spares(&mut EXACT_SPARE.lock().unwrap_or_else(|e| e.into_inner()), now, idle_ms); + for buffer in gone { + crate::host::retire_resource(buffer); + } +} /// Copies of single views' bytes made since the start. pub(crate) static OWN_MADE: AtomicU64 = AtomicU64::new(0); @@ -6601,6 +6652,54 @@ pub(crate) fn exact_line(frames: f64) { ); } +#[cfg(test)] +mod exact_spare_tests { + use super::{SPARE_MOST, Spare, idle_spares, park}; + + /// The memory a committed buffer of `width` bytes takes: whole 64 KiB + /// blocks. + fn committed(width: u64) -> u64 { + width.next_multiple_of(64 << 10) + } + + /// Spare buffers of views whose widths never come back hold at most + /// 64 MiB of the PC's memory, and go once they have been parked for the + /// idle time: with the count alone the list kept 1,024 of them (up to + /// 64 MiB each) for the rest of the run. + #[test] + fn spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle() { + const IDLE_MS: u64 = 10_000; + let mut spare: Vec> = Vec::new(); + // 3,000 views of as many widths (256 bytes to 750 KiB), let go 30 + // at a sweep, one sweep every 0.1 s. + for sweep in 0..100u32 { + let let_go = (0..30).map(|i| { + let n = sweep * 30 + i; + (u64::from(n + 1) * 256, n, 0usize) + }); + park(&mut spare, let_go, u64::from(sweep) * 100); + } + let bytes: u64 = spare.iter().map(|&(width, ..)| committed(width)).sum(); + assert!(spare.len() <= SPARE_MOST); + assert!(bytes <= 64 << 20, "{} spares hold {} MiB", spare.len(), bytes >> 20); + assert!(!spare.is_empty(), "spares are still kept"); + // The idle time after the first second: what was parked by then + // goes, what came after stays. + let early = spare.iter().filter(|&&(.., at)| at <= 1_000).count(); + assert!(early > 0 && early < spare.len()); + let gone = idle_spares(&mut spare, 1_000 + IDLE_MS, IDLE_MS); + assert_eq!(gone.len(), early); + assert!(spare.iter().all(|&(.., at)| at > 1_000)); + // Their room is free again for the views let go from then on. + let before = spare.len(); + park(&mut spare, [(256, 9_999, 0)], 1_000 + IDLE_MS); + assert_eq!(spare.len(), before + 1, "a spare parked again once others went"); + // And at the idle time after the last of them, none is left. + idle_spares(&mut spare, 1_000 + 2 * IDLE_MS, IDLE_MS); + assert!(spare.is_empty(), "{} spares left", spare.len()); + } +} + #[cfg(test)] mod window_tests { use super::{ From 5e07de7caf077411064dfe761a7a22bbf7960cf2 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:28:57 +0100 Subject: [PATCH 30/49] leonida-hle: idle pool workers leave even while tasks keep coming (RS-XTASKQUEUE-POOL-TRIM) All idle workers waited on one shared condition variable, and each queued task woke the one that had waited longest (std's Condvar on Windows wakes waiters first in, first out). So a steady trickle of tasks, such as the process queue's XAsync completions during play, restarted every idle worker's linger before it ran out. A pool that grew in a burst never shrank while tasks came more often than once per linger divided by the number of workers. Each idle worker now waits on a condition variable of its own, on a stack, and a queued task goes to the worker that went idle last. Under a trickle the same one or two workers run the tasks, and the others wait out the linger untouched and leave. A worker woken for a task counts as coming, like one being started, so the chain-start rule and the number of workers a burst starts stay as they were. The burst test no longer checks trimming. A new test grows a pool to 16 workers with callbacks that block until released, then queues one short callback every 10 ms. The workers must drop to the one kept (or two) while the trickle runs. Before this change 17 workers were still there after 3 s and about 290 callbacks. --- .../crates/leonida-hle/src/modules/xasync.rs | 158 ++++++++++++------ 1 file changed, 111 insertions(+), 47 deletions(-) diff --git a/d3d12/crates/leonida-hle/src/modules/xasync.rs b/d3d12/crates/leonida-hle/src/modules/xasync.rs index 293d500cc5..e91a6fb5f6 100644 --- a/d3d12/crates/leonida-hle/src/modules/xasync.rs +++ b/d3d12/crates/leonida-hle/src/modules/xasync.rs @@ -14,7 +14,7 @@ use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard}; -use std::time::Duration; +use std::time::{Duration, Instant}; use super::xgameruntime::{Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing}; @@ -148,33 +148,38 @@ impl Port { } /// The thread pool behind thread-pool ports. Idle workers are reused, and -/// while tasks wait there is always a worker idle or starting to take them: -/// a task queued with none starts one, and a worker that takes a task while -/// others still wait, with none idle or starting, starts the next before its -/// task runs. So a callback that blocks on another never starves it, while a -/// burst of short tasks is run by a few workers instead of a thread each. -/// Each worker holds a stack and the title's per-thread state, so one that -/// has waited out `linger` with no task leaves, down to `keep` idle ones. +/// while tasks wait there is always a worker coming to take them: a task +/// queued wakes an idle worker or, with none idle or coming, starts one, and +/// a worker that takes a task while others still wait, with none idle or +/// coming, starts the next before its task runs. So a callback that blocks +/// on another never starves it, while a burst of short tasks is run by a few +/// workers instead of a thread each. Each worker holds a stack and the +/// title's per-thread state, so one that has waited out `linger` with no +/// task leaves, down to `keep` idle ones. struct Pool { state: Mutex, - ready: Condvar, linger: Duration, keep: usize, } struct PoolState { tasks: VecDeque, - /// Workers waiting for a task. - idle: usize, - /// Workers started that have not looked for a task yet: each takes one - /// without waiting, so a task queued meanwhile has a worker coming. - starting: usize, - /// Every worker that has not left: idle, starting or running a task. + /// Idle workers, each waiting on a condition variable of its own, the + /// one that went idle last on top. A queued task takes the top one off + /// and wakes it. Waking them in turn instead would restart each one's + /// linger, so under a steady trickle of tasks none would ever leave. + idle: Vec>, + /// Workers started, or woken for a task, that have not looked for one + /// yet: each takes a task without waiting, so a task queued meanwhile + /// has a worker coming. + coming: usize, + /// Every worker that has not left: idle, coming or running a task. workers: usize, } /// Idle workers leave after 30 seconds without a task, down to four, so the -/// pool goes back to a few threads once a burst is over. +/// pool goes back to a few threads once a burst is over, even while a few +/// tasks keep coming. static POOL: Pool = Pool::new(Duration::from_secs(30), 4); impl Pool { @@ -182,11 +187,10 @@ impl Pool { Pool { state: Mutex::new(PoolState { tasks: VecDeque::new(), - idle: 0, - starting: 0, + idle: Vec::new(), + coming: 0, workers: 0, }), - ready: Condvar::new(), linger, keep, } @@ -195,11 +199,12 @@ impl Pool { fn submit(&'static self, task: Task) { let mut state = lock(&self.state); state.tasks.push_back(task); - // An idle worker takes it, or the one starting does (and starts the - // next if more wait); with neither, one starts. - if state.idle > 0 { - self.ready.notify_one(); - } else if state.starting == 0 { + // The worker that went idle last takes it, or one coming does (and + // starts the next if more wait); with neither, one starts. + if let Some(worker) = state.idle.pop() { + state.coming += 1; + worker.notify_one(); + } else if state.coming == 0 { self.start(state); } } @@ -207,20 +212,21 @@ impl Pool { /// Starts a worker. The thread is created after the lock is let go, as /// creating it takes a while and the other workers need the lock. fn start(&'static self, mut state: MutexGuard<'_, PoolState>) { - state.starting += 1; + state.coming += 1; state.workers += 1; drop(state); std::thread::spawn(move || self.work()); } fn work(&'static self) { + let wake = Arc::new(Condvar::new()); let mut state = lock(&self.state); - state.starting -= 1; + state.coming -= 1; loop { if let Some(task) = state.tasks.pop_front() { // This task may block on one still queued, so that one needs // a worker of its own coming. - if !state.tasks.is_empty() && state.idle == 0 && state.starting == 0 { + if !state.tasks.is_empty() && state.idle.is_empty() && state.coming == 0 { self.start(state); } else { drop(state); @@ -229,18 +235,33 @@ impl Pool { state = lock(&self.state); continue; } - state.idle += 1; - let (next, waited) = self - .ready - .wait_timeout(state, self.linger) - .unwrap_or_else(|e| e.into_inner()); - state = next; - state.idle -= 1; - // Leaving with the queue empty leaves no task without a worker. - if waited.timed_out() && state.tasks.is_empty() && state.idle >= self.keep { - state.workers -= 1; - tracing::debug!(workers = state.workers, "task pool: an idle worker leaves"); - return; + state.idle.push(wake.clone()); + let mut deadline = Instant::now() + self.linger; + loop { + let left = deadline.saturating_duration_since(Instant::now()); + state = wake + .wait_timeout(state, left) + .unwrap_or_else(|e| e.into_inner()) + .0; + // Taken off the stack: a task was queued for this worker. + let Some(at) = state.idle.iter().position(|w| Arc::ptr_eq(w, &wake)) else { + state.coming -= 1; + break; + }; + if Instant::now() < deadline { + continue; + } + // A worker is on the stack only while the queue is empty (it + // goes idle when it finds no task, and each task queued takes + // one off), so leaving leaves no task without a worker. + if state.idle.len() > self.keep { + debug_assert!(state.tasks.is_empty()); + state.idle.remove(at); + state.workers -= 1; + tracing::debug!(workers = state.workers, "task pool: an idle worker leaves"); + return; + } + deadline = Instant::now() + self.linger; } } } @@ -1614,10 +1635,9 @@ mod tests { } /// A burst of short callbacks (completions queued together, say) is run - /// by a few workers instead of a thread each, and the workers left idle - /// leave once the pool's linger is over, down to the ones it keeps. + /// by a few workers instead of a thread each. #[test] - fn pool_workers_stay_few_in_a_burst_and_leave_when_idle() { + fn pool_workers_stay_few_in_a_burst_of_short_callbacks() { static BURST: Pool = Pool::new(Duration::from_millis(200), 1); static RAN: AtomicU32 = AtomicU32::new(0); extern "system" fn ran(_: *mut c_void, _: bool) { @@ -1629,15 +1649,59 @@ mod tests { assert!(within_seconds(|| RAN.load(Ordering::SeqCst) == 256)); let started = workers(&BURST); assert!(started <= 32, "{started} workers for 256 short callbacks"); + } + + /// The workers a burst left idle leave once the pool's linger is over, + /// down to the ones it keeps, even while a trickle of short callbacks + /// keeps coming (the process queue's completions during play, say). + #[test] + fn pool_workers_left_idle_leave_under_a_trickle_of_callbacks() { + static TRICKLE: Pool = Pool::new(Duration::from_millis(200), 1); + static HELD: AtomicU32 = AtomicU32::new(0); + static HOLD: AtomicBool = AtomicBool::new(true); + static RAN: AtomicU32 = AtomicU32::new(0); + extern "system" fn held(_: *mut c_void, _: bool) { + HELD.fetch_add(1, Ordering::SeqCst); + while HOLD.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + } + extern "system" fn ran(_: *mut c_void, _: bool) { + RAN.fetch_add(1, Ordering::SeqCst); + } + // Sixteen callbacks that block until released take a worker each. + for _ in 0..16 { + TRICKLE.submit(Task::new(std::ptr::null_mut(), held)); + } + assert!(within_seconds(|| HELD.load(Ordering::SeqCst) == 16)); + assert_eq!(workers(&TRICKLE), 16); + HOLD.store(false, Ordering::SeqCst); + + // One short callback every 10 ms, for up to fifteen lingers. Two + // workers may stay a while longer: one that times out while another + // is running a callback is the only idle one, so it is kept. + let start = std::time::Instant::now(); + let mut sent = 0; + while workers(&TRICKLE) > 2 && start.elapsed() < Duration::from_secs(3) { + TRICKLE.submit(Task::new(std::ptr::null_mut(), ran)); + sent += 1; + std::thread::sleep(Duration::from_millis(10)); + } + assert!( + workers(&TRICKLE) <= 2, + "{} workers still there after {sent} callbacks 10 ms apart", + workers(&TRICKLE) + ); + assert!(within_seconds(|| RAN.load(Ordering::SeqCst) == sent)); + // Once it is quiet, the one kept stays and still runs what comes. assert!( - within_seconds(|| workers(&BURST) == 1), + within_seconds(|| workers(&TRICKLE) == 1), "{} workers still there", - workers(&BURST) + workers(&TRICKLE) ); - // The worker kept still runs what comes. - BURST.submit(Task::new(std::ptr::null_mut(), ran)); - assert!(within_seconds(|| RAN.load(Ordering::SeqCst) == 257)); + TRICKLE.submit(Task::new(std::ptr::null_mut(), ran)); + assert!(within_seconds(|| RAN.load(Ordering::SeqCst) == sent + 1)); } /// Callbacks queued together that each wait for all of them to have From 8e1bf0bd604b1010cc5d51b70ccdb7f963d00f97 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:29:43 +0100 Subject: [PATCH 31/49] leonida-hle: a pool worker that cannot be started leaves the pool able to start others (RS-XTASKQUEUE-POOL-TRIM) Pool::start counted the new worker as coming before it created the thread, and std::thread::spawn panics when the thread cannot be created. On the chain path that panic ended the worker that called start, lost the task it had just taken, and left the worker counted as coming for good, so no task queued later would start another. The thread is now created with std::thread::Builder::spawn. On error the counts are put back and a warning is logged. The worker that called start keeps its task and runs it, and the tasks still waiting go to the next worker that finishes a task, or to the worker the next queued task tries to start. --- d3d12/crates/leonida-hle/src/modules/xasync.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/d3d12/crates/leonida-hle/src/modules/xasync.rs b/d3d12/crates/leonida-hle/src/modules/xasync.rs index e91a6fb5f6..d57945b97b 100644 --- a/d3d12/crates/leonida-hle/src/modules/xasync.rs +++ b/d3d12/crates/leonida-hle/src/modules/xasync.rs @@ -215,7 +215,16 @@ impl Pool { state.coming += 1; state.workers += 1; drop(state); - std::thread::spawn(move || self.work()); + if let Err(error) = std::thread::Builder::new().spawn(move || self.work()) { + // A worker that never came must not stay counted as coming, or no + // task queued later would start another. The tasks waiting now + // go to the next worker that finishes a task, or to the worker + // the next queued task tries to start. + let mut state = lock(&self.state); + state.coming -= 1; + state.workers -= 1; + tracing::warn!(%error, "task pool: a worker could not be started"); + } } fn work(&'static self) { From 8ebf6c099a54676123071ef45f34422ba5a21fd8 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:34:44 +0100 Subject: [PATCH 32/49] leonida-gpu: reads of textures over 16 MiB reuse buffers from a shared pool the sweep empties when idle (RS-TEXTURE-READ-TRIM) The commit before this one freed a thread's read buffer after every read of a texture larger than LEONIDA_TEXTURE_READ_KEEP_MB (16 unless set). The 22 MB 4096x4096 BC7 class it named as the reason, and a 2048x2048 RGBA8 texture with its levels, are above that limit, so each of their reads allocated, faulted the pages in and freed them again, on the submitting thread and the leonida-wide helpers while the world streams in. In a standalone timing on a Ryzen 7 5800X, one read of 22.4 MB took 0.85-0.88 ms in a reused buffer and 3.3-3.5 ms in a fresh one (with five threads at once: 4.1 ms against 8.6-9.3 ms). Reads larger than the kept bytes now take a buffer from a process-wide pool (LARGE_READS) and give it back afterwards. A read takes the smallest buffer there that is large enough, or else the largest, which it makes again larger, so the pool never holds more buffers than reads ran at once. Large reads that come one after another reuse touched memory as on d44285197 (0.82-0.84 ms in the same timing). The sweep (texture::let_go_idle) takes out the buffers no read took for host::ram_idle_ms and hands them to host::retire, so the reaper thread frees them, not the submitting thread. A thread's own buffer serves reads up to the kept bytes, as in the commit before. It is made exactly as large as asked (vec![0u8; size]), with no doubling and no copy of the old contents. The trade-off: a texture over 16 MiB no longer makes its room at every read. After an idle stretch of ram_idle_ms (10 s, or 5 min with 12 GiB free and LEONIDA_KEEP_FREED on) the first such read allocates again. At its peak the pool holds one buffer per large read running at once, each up to the largest texture read. That is what d44285197's per-thread buffers held, but shared between the threads and given back when idle. Each thread still keeps up to 16 MiB of its own for the run. Tests: texture::read_buffer_tests::a_large_read_gives_its_room_back_when_it_is_over now sizes its reads from read_kept() and checks the pool and its reuse. On d44285197 it fails with "40 MiB kept after a read of 32 MiB" (with read_kept and LARGE_READS stubbed in so that it builds). texture::read_buffer_tests::the_pool_of_large_reads_reuses_its_buffers_and_lets_the_idle_ones_go checks take_read and idle_reads. --- d3d12/crates/leonida-gpu/src/texture.rs | 177 ++++++++++++++++++------ 1 file changed, 136 insertions(+), 41 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/texture.rs b/d3d12/crates/leonida-gpu/src/texture.rs index d7779fda1b..c371bd186a 100644 --- a/d3d12/crates/leonida-gpu/src/texture.rs +++ b/d3d12/crates/leonida-gpu/src/texture.rs @@ -448,42 +448,91 @@ fn waited(slot: usize, f: impl FnOnce() -> T) -> T { thread_local! { /// Room to read a texture's memory into: one buffer per submitting - /// thread. Each texture kept its own, a second copy in memory of every - /// write-watched or partly mapped texture ever sampled, for the run. + /// thread, of up to [`read_kept`] bytes. Each texture kept its own, a + /// second copy in memory of every write-watched or partly mapped texture + /// ever sampled, for the run. static READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } -/// Calls `f` with `size` bytes of this thread's read buffer (their -/// contents are whatever the last texture left). +/// Read buffers of textures larger than [`read_kept`], shared by the threads +/// that refresh textures, each with when it was given back +/// ([`crate::host::coarse_ms`]). A thread's own buffer only grew, so each of +/// those threads (the submitting one and the helpers of +/// `crate::shadow::wide_each`, which live for the run) kept the room of the +/// largest texture it ever read until the end: 22 MB for a 4096² BC7 texture +/// with its levels, 89 MB for one in RGBA8, on each of them (five on a PC of +/// 16 logical processors). Here such a buffer is still reused by the reads +/// that come one after another while the world streams in, and the sweep +/// lets it go once no read took it for a while ([`let_go_idle_reads`]). +static LARGE_READS: Mutex, u64)>> = Mutex::new(Vec::new()); + +/// Calls `f` with `size` bytes of read buffer (their contents are whatever +/// the last texture left). fn with_read(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R { - READ.with(|read| { - let mut read = read.borrow_mut(); + if size > read_kept() { + let mut read = take_read(&mut LARGE_READS.lock().unwrap_or_else(|e| e.into_inner()), size); if read.len() < size { - // Exactly the room asked for: grown by doubling, a texture under - // [`read_kept`] could leave room over it, which would go below. - let more = size - read.len(); - read.reserve_exact(more); - read.resize(size, 0); + // None there was large enough (or none was there): the largest + // goes before a new one is made, outside the lock. A new buffer + // comes zeroed from the allocator, without a second pass. + drop(read); + read = vec![0u8; size]; } let out = f(&mut read[..size]); - // The buffer only grew, so each thread that refreshes textures (the - // submitting one and the helpers of `crate::shadow::wide_each`, which - // live for the run) kept the room of the largest texture it ever - // read until the end: 22 MB for a 4096² BC7 texture with its levels, - // 89 MB for one in RGBA8, on each of those threads (five on a PC of - // 16 logical processors). Room over [`read_kept`] goes when the read - // is over; the next texture that large makes its room again. - if read.capacity() > read_kept() { - *read = Vec::new(); + let now = crate::host::coarse_ms(); + LARGE_READS.lock().unwrap_or_else(|e| e.into_inner()).push((read, now)); + return out; + } + READ.with(|read| { + let mut read = read.borrow_mut(); + if read.len() < size { + // Exactly the room asked for, which stays under [`read_kept`]: + // grown by doubling, it could be twice that. The old contents + // need no copy. + *read = vec![0u8; size]; } - out + f(&mut read[..size]) }) } -/// The bytes of read buffer a thread keeps from one texture to the next -/// (`LEONIDA_TEXTURE_READ_KEEP_MB`, 16). That holds a 4096² BC1 texture or -/// a 2048² BC7 one with their levels (11 and 5.6 MB), so that textures of -/// those sizes do not make their room again at every read. +/// A buffer for a read of `size` bytes from `pool`: the smallest there that +/// is large enough, or else the largest, which the caller makes again larger; +/// empty if the pool is. So the pool holds no more buffers than reads ran at +/// once, each at most the size of the largest texture read. +fn take_read(pool: &mut Vec<(Vec, u64)>, size: usize) -> Vec { + let fit = pool + .iter() + .enumerate() + .filter(|(_, (read, _))| read.len() >= size) + .min_by_key(|(_, (read, _))| read.len()) + .or_else(|| pool.iter().enumerate().max_by_key(|(_, (read, _))| read.len())) + .map(|(i, _)| i); + fit.map(|i| pool.swap_remove(i).0).unwrap_or_default() +} + +/// Takes out of `pool` the buffers given back `idle_ms` or more before +/// `now`. +fn idle_reads(pool: &mut Vec<(Vec, u64)>, now: u64, idle_ms: u64) -> Vec<(Vec, u64)> { + pool.extract_if(.., |(_, at)| now.saturating_sub(*at) >= idle_ms).collect() +} + +/// Lets go of the read buffers of large textures no read took for `idle_ms` +/// ([`crate::host::ram_idle_ms`]). They are freed on the reaper thread, not +/// on the submitting thread that runs the sweep: freeing tens of MB of +/// touched memory takes milliseconds, and nothing is in flight while the +/// sweep runs, so the card would wait for it. +fn let_go_idle_reads(idle_ms: u64) { + let now = crate::host::coarse_ms(); + let gone = idle_reads(&mut LARGE_READS.lock().unwrap_or_else(|e| e.into_inner()), now, idle_ms); + if !gone.is_empty() { + crate::host::retire(gone); + } +} + +/// The bytes of read buffer a thread keeps for itself from one texture to +/// the next (`LEONIDA_TEXTURE_READ_KEEP_MB`, 16); larger textures are read +/// into [`LARGE_READS`]. That holds a 4096² BC1 texture or a 2048² BC7 one +/// with their levels (11 and 5.6 MB) without a lock. fn read_kept() -> usize { static KEPT: std::sync::OnceLock = std::sync::OnceLock::new(); *KEPT.get_or_init(|| { @@ -564,10 +613,14 @@ pub(crate) fn let_go() -> [u64; 2] { /// those of textures no longer sampled were kept for the run (2,246 of /// them, 2.1 GB, at the end of run 24). The next list that samples such a /// texture makes a staging buffer anew, detiles and uploads once more. +/// Read buffers of large textures no read took for `idle_ms` go too +/// ([`let_go_idle_reads`]), whether or not there are staging buffers. /// Called before a submission starts, by the thread that submits. pub(crate) fn let_go_idle() { use std::sync::atomic::Ordering::Relaxed; const IDLE_FRAMES: u64 = 4; + let idle_ms = crate::host::ram_idle_ms(crate::residency::headroom()); + let_go_idle_reads(idle_ms); let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); let Some(map) = map.as_mut() else { return; @@ -575,7 +628,6 @@ pub(crate) fn let_go_idle() { if map.is_empty() { return; } - let idle_ms = crate::host::ram_idle_ms(crate::residency::headroom()); // A list that recorded an upload or a check holds the staging until it // is reset: one only the table holds is named by no list, recorded or // running. @@ -2592,12 +2644,9 @@ mod title_memory_tests { #[cfg(test)] mod read_buffer_tests { - use super::{READ, with_read}; + use super::{LARGE_READS, READ, idle_reads, read_kept, take_read, with_read}; - /// The default of `LEONIDA_TEXTURE_READ_KEEP_MB`, in bytes. - const KEPT: usize = 16 << 20; - - /// The capacity of this thread's read buffer. + /// The capacity of this thread's own read buffer. fn room() -> usize { READ.with(|read| read.borrow().capacity()) } @@ -2606,31 +2655,77 @@ mod read_buffer_tests { /// kept bytes from one texture to the next, but not the room of a larger /// texture once its read is over: those threads (the submitting one and /// the helpers of `shadow::wide_each`) live for the run, and each held - /// the largest texture it ever read until the end. The reads run on + /// the largest texture it ever read until the end. That room waits in + /// the shared pool for the next large read instead. The reads run on /// threads of their own, as refreshes do, so that the buffer of the /// thread the harness runs the test on (shared by the tests with - /// `--test-threads=1`) plays no part. + /// `--test-threads=1`) plays no part. No other test reads a texture + /// larger than the kept bytes, so the shared pool is this test's alone. #[test] fn a_large_read_gives_its_room_back_when_it_is_over() { + let kept = read_kept(); + // Larger than the kept bytes, whatever LEONIDA_TEXTURE_READ_KEEP_MB + // says. + let large = 2 * kept.max(1 << 20); std::thread::scope(|threads| { for _ in 0..2 { threads.spawn(|| { // Up to the kept bytes: kept for the next texture, also // when the buffer grows from one under them. - with_read(KEPT * 5 / 8, |read| read.fill(1)); - with_read(KEPT * 3 / 4, |read| read.fill(1)); - assert!(room() >= KEPT * 3 / 4, "a read under the kept bytes keeps its room"); - // A larger texture is read whole, then its room goes. - with_read(2 * KEPT, |read| { - assert_eq!(read.len(), 2 * KEPT); - read[2 * KEPT - 1] = 2; + with_read(kept * 5 / 8, |read| read.fill(1)); + with_read(kept * 3 / 4, |read| read.fill(1)); + assert!(room() >= kept * 3 / 4, "a read under the kept bytes keeps its room"); + // A larger texture is read whole, then the thread does + // not keep its room. + with_read(large, |read| { + assert_eq!(read.len(), large); + read[large - 1] = 2; }); - assert!(room() <= KEPT, "{} MiB kept after a read of {} MiB", room() >> 20, (2 * KEPT) >> 20); + assert!(room() <= kept, "{} MiB kept after a read of {} MiB", room() >> 20, large >> 20); // And the next read is served as before. with_read(4096, |read| assert_eq!(read.len(), 4096)); }); } }); + // The pool holds a buffer for each of the large reads that ran at + // once (one or two, as the threads overlapped), each large enough. + let pooled: Vec<(usize, usize)> = LARGE_READS + .lock() + .unwrap() + .iter() + .map(|(read, _)| (read.as_ptr() as usize, read.len())) + .collect(); + assert!((1..=2).contains(&pooled.len()), "{} buffers pooled after two large reads", pooled.len()); + assert!(pooled.iter().all(|&(_, len)| len >= large)); + // The next large read, on another thread, takes one of them instead + // of making its room again. + let took = std::thread::spawn(move || with_read(large, |read| read.as_ptr() as usize)).join().unwrap(); + assert!(pooled.iter().any(|&(at, _)| at == took), "a large read reuses a pooled buffer"); + // (Their memory goes now, not at the end of the run of tests.) + LARGE_READS.lock().unwrap().clear(); + } + + /// The shared pool hands out the smallest buffer large enough for a + /// read, and the largest when none is (the reader makes it again + /// larger), so it holds no more buffers than reads ran at once; and it + /// lets go of those no read took for the idle time, while the ones given + /// back since stay. + #[test] + fn the_pool_of_large_reads_reuses_its_buffers_and_lets_the_idle_ones_go() { + const IDLE_MS: u64 = 10_000; + let mut pool: Vec<(Vec, u64)> = vec![(vec![0; 3000], 1_000), (vec![0; 9000], 1_000), (vec![0; 5000], 9_000)]; + assert_eq!(take_read(&mut pool, 4000).len(), 5000, "the smallest buffer large enough"); + assert_eq!(take_read(&mut pool, 20_000).len(), 9000, "the largest when none is large enough"); + assert_eq!(take_read(&mut pool, 1).len(), 3000); + assert!(take_read(&mut pool, 1).is_empty(), "an empty pool has none to give"); + // Two buffers given back at 1 s and one at 9 s. + let mut pool: Vec<(Vec, u64)> = vec![(vec![0; 3000], 1_000), (vec![0; 3000], 1_000), (vec![0; 3000], 9_000)]; + assert!(idle_reads(&mut pool, 10_999, IDLE_MS).is_empty(), "none goes under the idle time"); + let gone = idle_reads(&mut pool, 11_000, IDLE_MS); + assert_eq!(gone.len(), 2, "{} of the two idle buffers let go", gone.len()); + assert_eq!(pool.iter().map(|(_, at)| *at).collect::>(), [9_000]); + assert_eq!(idle_reads(&mut pool, 19_000, IDLE_MS).len(), 1); + assert!(pool.is_empty()); } } From 8f0d83d2e10df5fc9dd2a486eb7140ee8413e5b7 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:35:57 +0100 Subject: [PATCH 33/49] leonida-gpu: idle snapshot buffers are freed on the reaper thread, not in the submission sweep (RS-SNAPSHOT-POOL-TRIM) let_go_idle_snapshots dropped every idle buffer of the pool at once, on the submitting thread, inside shadow::let_go_idle. That sweep runs before a submission while nothing is in flight, so the card waits for it. The pool holds up to 512 MiB of touched memory, or its largest buffer when that is bigger (174 MB for the big heap). Freeing 512 MiB of touched memory took 22-58 ms on a Ryzen 7 5800X, so the title could see a stall of that size in the submit path after each idle stretch. The idle buffers now go to crate::host::retire, after the pool's lock is released. retire queues them past the bury lag, and the leonida-reaper thread frees them, as it does for the idle windows the same sweep lets go. The old comment pointed to give_back, but give_back frees only what goes over its limits at that moment, not the whole pool. The test is unchanged: shadow::snapshot_pool_tests::buffers_the_pool_kept_for_the_idle_time_go. --- d3d12/crates/leonida-gpu/src/shadow.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 572bba2cf1..150cf92634 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -1856,8 +1856,13 @@ fn give_back(v: Vec) { fn let_go_idle_snapshots(idle_ms: u64) { let now = crate::host::coarse_ms(); let gone = idle_snapshots(&mut POOL.lock().unwrap_or_else(|e| e.into_inner()), now, idle_ms); - // (Given back to the kernel without the lock, as in `give_back`.) - drop(gone); + // Freed on the reaper thread, after the lock is released: the sweep + // runs on the submitting thread while nothing is in flight, so the card + // waits for it, and freeing the whole idle pool at once (up to 512 MiB + // of touched memory) took 22-58 ms on a Ryzen 7 5800X. + if !gone.is_empty() { + crate::host::retire(gone); + } } /// Takes out of `pool` the buffers given back `idle_ms` or more before From b421086ea48ae44f5e83214b2551f566a9ee2766 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:36:29 +0100 Subject: [PATCH 34/49] leonida-gpu: the window sweep asks for the RAM idle time once and passes it on (RS-SNAPSHOT-POOL-TRIM) shadow::let_go_idle asked crate::host::ram_idle_ms once for the snapshot pool and again for the windows. Each ask is a GlobalMemoryStatusEx call and a look at the residency headroom. The idle time is now worked out once, right after IDLE_FRAMES, and passed to let_go_idle_snapshots and to the window filter. RS-EXACT-SPARE-CAP makes the same change and puts its own call at the same place. --- d3d12/crates/leonida-gpu/src/shadow.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 150cf92634..411d23678a 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -3726,10 +3726,13 @@ pub(crate) fn window_use() -> [u64; 8] { /// The next read of that memory makes a new copy and copies the window /// again. Called before a submission starts, by the thread that submits. pub(crate) fn let_go_idle() { - // The snapshot buffers no snapshot took for the PC memory's idle time - // go too, whether or not there are windows. - let_go_idle_snapshots(crate::host::ram_idle_ms(crate::host::available_physical_ram())); const IDLE_FRAMES: u64 = 4; + // Asked once for the whole sweep: each ask is a GlobalMemoryStatusEx + // call and a look at the residency headroom. + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + // The snapshot buffers no snapshot took for that long go too, whether + // or not there are windows. + let_go_idle_snapshots(idle_ms); let gone: Vec> = { // Held from the look to the removal: `loose` hands a copy out // under the same lock, so none is handed out in between. @@ -3737,7 +3740,6 @@ pub(crate) fn let_go_idle() { if map.is_empty() { return; } - let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); let idle: Vec<(u64, u64)> = map .iter() .filter(|(_, s)| { From ace765945624badbd96c03cb7299c9c6edb8c5eb Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:37:10 +0100 Subject: [PATCH 35/49] leonida-gpu: the window sweep asks for the RAM idle time once and passes it on (RS-EXACT-SPARE-CAP) shadow::let_go_idle asked crate::host::ram_idle_ms once for the spare buffers and again for the windows. Each ask is a GlobalMemoryStatusEx call and a look at the residency headroom. The idle time is now worked out once, right after IDLE_FRAMES, and passed to let_go_idle_spares and to the window filter. RS-SNAPSHOT-POOL-TRIM makes the same change and puts its own call at the same place. --- d3d12/crates/leonida-gpu/src/shadow.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 330a54b699..d4ff155988 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -3672,9 +3672,12 @@ pub(crate) fn window_use() -> [u64; 8] { /// again. Called before a submission starts, by the thread that submits. pub(crate) fn let_go_idle() { const IDLE_FRAMES: u64 = 4; + // Asked once for the whole sweep: each ask is a GlobalMemoryStatusEx + // call and a look at the residency headroom. + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); // The spare buffers of copies of views' own bytes that no copy took for - // the PC memory's idle time go too, whether or not there are windows. - let_go_idle_spares(crate::host::ram_idle_ms(crate::host::available_physical_ram())); + // that long go too, whether or not there are windows. + let_go_idle_spares(idle_ms); let gone: Vec> = { // Held from the look to the removal: `loose` hands a copy out // under the same lock, so none is handed out in between. @@ -3682,7 +3685,6 @@ pub(crate) fn let_go_idle() { if map.is_empty() { return; } - let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); let idle: Vec<(u64, u64)> = map .iter() .filter(|(_, s)| { From d48f6b4f1a0cbc56729de8d15b48ea30e32f9684 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:40:55 +0100 Subject: [PATCH 36/49] leonida-gpu: a full spare list gives up its oldest buffer, released outside the lock (RS-EXACT-SPARE-CAP) When parking a buffer would take the spares of exact() over 1,024 buffers or 64 MiB, park() refused the newcomer. Spares of widths that never come back could then keep a width the title's ring repeats out of the list until they aged out (up to host::ram_idle_ms, 5 min with 12 GiB free). Now the spare parked longest ago goes to make room. The widths the ring repeats are taken and parked again all the time, so the oldest spare is of a width that did not come back. park() now returns the buffers that go: the oldest spares it pushes out, and a newcomer larger than the whole list may hold, which no view of exact() is. exact() drops the copies it lets go before it takes the EXACT_SPARE lock, and passes the returned buffers to host::retire_resource after the lock is released. Before, a refused buffer of up to 64 MiB of committed memory was released while the lock was held, and the eight threads that translate lists queue on that lock. d44285197 did the same when the count overflowed. Test: shadow::exact_spare_tests::spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle now also checks that every buffer is either parked or returned, that the last sweep's spares are all kept, and that a 640 KiB width parked into the full list finds room. With d44285197's rule ported into park and idle_spares it still fails with "1024 spares hold 160 MiB". With the rule of the commit before this one (newcomers refused) it fails because none of the last sweep's 30 spares is kept. --- d3d12/crates/leonida-gpu/src/shadow.rs | 100 +++++++++++++++++-------- 1 file changed, 67 insertions(+), 33 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index d4ff155988..31d856cfe9 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -6549,17 +6549,25 @@ pub(crate) fn exact(address: u64, len: u64) -> Option> { // frame): making a buffer and letting one go are a call into the kernel // each, and were most of what these threads ran. let width = len.next_multiple_of(256); - let spare = { + // The copies let go are dropped here, before the spare list's lock is + // taken; their buffers live on in `let_go` (placed copies have none of + // their own). + let let_go: Vec<(u64, ID3D12Resource, usize)> = gone + .into_iter() + .filter(|shadow| shadow.place.is_none()) + .map(|shadow| (shadow.width(), shadow.buffer.clone(), shadow.data as usize)) + .collect(); + let (spare, unparked) = { let mut spare = EXACT_SPARE.lock().unwrap_or_else(|e| e.into_inner()); - if !gone.is_empty() { - let let_go = gone - .drain(..) - .filter(|shadow| shadow.place.is_none()) - .map(|shadow| (shadow.width(), shadow.buffer.clone(), shadow.data as usize)); - park(&mut spare, let_go, crate::host::coarse_ms()); - } - spare.iter().position(|(w, ..)| *w == width).map(|i| spare.swap_remove(i)) + let unparked = if let_go.is_empty() { Vec::new() } else { park(&mut spare, let_go, crate::host::coarse_ms()) }; + (spare.iter().position(|(w, ..)| *w == width).map(|i| spare.swap_remove(i)), unparked) }; + // Released after the lock, which the eight threads that translate lists + // queue on: a buffer is up to 64 MiB of committed memory. As idle spares + // and windows do, they go through `retire_resource`. + for buffer in unparked { + crate::host::retire_resource(buffer); + } let (buffer, data) = match spare { Some((_, buffer, data, _)) => (buffer, data as *mut u8), None => host()?.shared_buffer(width)?, @@ -6588,7 +6596,8 @@ static EXACT_SPARE: Mutex>> = Mutex::new(Vec::new()); /// A spare buffer: its width, the buffer, where it is mapped, and when it /// was parked ([`crate::host::coarse_ms`]). type Spare = (u64, B, usize, u64); -/// At most so many are kept (what comes after goes, as before). +/// At most so many are kept (past that, the oldest goes for a newcomer, +/// [`park`]). const SPARE_MOST: usize = 1024; /// And at most so many bytes of the PC's memory, each buffer counted in the /// whole 64 KiB blocks a committed buffer takes. A spare is reused only for @@ -6599,17 +6608,35 @@ const SPARE_MOST: usize = 1024; const SPARE_BYTES: u64 = 64 << 20; /// Parks the buffers `let_go` (width, buffer, where it is mapped) among -/// `spare` at `now`, while those hold fewer than [`SPARE_MOST`] and room -/// for it within [`SPARE_BYTES`]; the others go, as before. -fn park(spare: &mut Vec>, let_go: impl IntoIterator, now: u64) { +/// `spare` at `now`. Where the spares would then hold more than +/// [`SPARE_MOST`] buffers or [`SPARE_BYTES`], the spare parked longest ago +/// makes room: the widths the title's ring repeats are taken and parked +/// again all the time, so the oldest is of a width that did not come back. +/// Refusing the newcomer instead would let those keep a width that does +/// recur out of the list until they aged out. Returns the buffers that go, +/// for the caller to release once the lock is released. +fn park(spare: &mut Vec>, let_go: impl IntoIterator, now: u64) -> Vec { let committed = |width: u64| width.next_multiple_of(64 << 10); let mut bytes: u64 = spare.iter().map(|&(width, ..)| committed(width)).sum(); + let mut gone = Vec::new(); for (width, buffer, data) in let_go { - if spare.len() < SPARE_MOST && bytes + committed(width) <= SPARE_BYTES { - bytes += committed(width); - spare.push((width, buffer, data, now)); + // (Larger than the list may hold at all; [`exact`]'s views are not.) + if committed(width) > SPARE_BYTES { + gone.push(buffer); + continue; + } + while spare.len() >= SPARE_MOST || bytes + committed(width) > SPARE_BYTES { + let Some(oldest) = spare.iter().enumerate().min_by_key(|(_, parked)| parked.3).map(|(i, _)| i) else { + break; + }; + let (old, buffer, ..) = spare.swap_remove(oldest); + bytes -= committed(old); + gone.push(buffer); } + bytes += committed(width); + spare.push((width, buffer, data, now)); } + gone } /// Takes out of `spare` the buffers parked `idle_ms` or more before `now`. @@ -6665,13 +6692,15 @@ mod exact_spare_tests { } /// Spare buffers of views whose widths never come back hold at most - /// 64 MiB of the PC's memory, and go once they have been parked for the - /// idle time: with the count alone the list kept 1,024 of them (up to - /// 64 MiB each) for the rest of the run. + /// 64 MiB of the PC's memory, the oldest giving way to newcomers, and go + /// once they have been parked for the idle time: with the count alone + /// the list kept 1,024 of them (up to 64 MiB each) for the rest of the + /// run. #[test] fn spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle() { const IDLE_MS: u64 = 10_000; let mut spare: Vec> = Vec::new(); + let mut went = 0; // 3,000 views of as many widths (256 bytes to 750 KiB), let go 30 // at a sweep, one sweep every 0.1 s. for sweep in 0..100u32 { @@ -6679,25 +6708,30 @@ mod exact_spare_tests { let n = sweep * 30 + i; (u64::from(n + 1) * 256, n, 0usize) }); - park(&mut spare, let_go, u64::from(sweep) * 100); + went += park(&mut spare, let_go, u64::from(sweep) * 100).len(); } let bytes: u64 = spare.iter().map(|&(width, ..)| committed(width)).sum(); assert!(spare.len() <= SPARE_MOST); assert!(bytes <= 64 << 20, "{} spares hold {} MiB", spare.len(), bytes >> 20); assert!(!spare.is_empty(), "spares are still kept"); - // The idle time after the first second: what was parked by then - // goes, what came after stays. - let early = spare.iter().filter(|&&(.., at)| at <= 1_000).count(); - assert!(early > 0 && early < spare.len()); - let gone = idle_spares(&mut spare, 1_000 + IDLE_MS, IDLE_MS); - assert_eq!(gone.len(), early); - assert!(spare.iter().all(|&(.., at)| at > 1_000)); - // Their room is free again for the views let go from then on. - let before = spare.len(); - park(&mut spare, [(256, 9_999, 0)], 1_000 + IDLE_MS); - assert_eq!(spare.len(), before + 1, "a spare parked again once others went"); - // And at the idle time after the last of them, none is left. - idle_spares(&mut spare, 1_000 + 2 * IDLE_MS, IDLE_MS); + // Each buffer is either parked or handed back to be released. + assert_eq!(went + spare.len(), 3_000); + // Those that gave way were the oldest: the last sweep's are all kept. + assert_eq!(spare.iter().filter(|&&(.., at)| at == 9_900).count(), 30); + // A width that comes again still finds room in the full list: the + // oldest spare goes for it. + let width = 640 << 10; + assert!(bytes + committed(width) > 64 << 20, "the list has no room for it"); + let gone = park(&mut spare, [(width, 9_999, 0)], 10_000); + assert!(!gone.is_empty()); + assert!(spare.iter().any(|&(w, id, ..)| w == width && id == 9_999), "a newcomer is parked in a full list"); + // The idle time after the last sweep: all it and those before it + // parked goes, the newcomer stays. + let gone = idle_spares(&mut spare, 9_900 + IDLE_MS, IDLE_MS); + assert!(!gone.is_empty()); + assert_eq!(spare.iter().map(|&(_, id, ..)| id).collect::>(), [9_999]); + // And at the idle time after it, none is left. + idle_spares(&mut spare, 10_000 + IDLE_MS, IDLE_MS); assert!(spare.is_empty(), "{} spares left", spare.len()); } } From 4b8af776f3c2b0c4fe439521a425f8860a931c19 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:45:03 +0100 Subject: [PATCH 37/49] leonida-gpu: the texture read pool's comment says what a zeroed allocation can save (RS-TEXTURE-READ-TRIM) The comment said a new large read buffer comes zeroed without a second pass. alloc_zeroed only lets the allocator skip writing pages that come fresh from the system, and in a standalone timing on this PC vec![0u8; n] cost the same as reserve_exact plus resize. The comment now says only that. --- d3d12/crates/leonida-gpu/src/texture.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/texture.rs b/d3d12/crates/leonida-gpu/src/texture.rs index c371bd186a..4e2d2d5ac2 100644 --- a/d3d12/crates/leonida-gpu/src/texture.rs +++ b/d3d12/crates/leonida-gpu/src/texture.rs @@ -473,8 +473,9 @@ fn with_read(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R { let mut read = take_read(&mut LARGE_READS.lock().unwrap_or_else(|e| e.into_inner()), size); if read.len() < size { // None there was large enough (or none was there): the largest - // goes before a new one is made, outside the lock. A new buffer - // comes zeroed from the allocator, without a second pass. + // goes before a new one is made, outside the lock. The new one + // is asked for zeroed, which lets the allocator skip writing + // pages that come fresh from the system. drop(read); read = vec![0u8; size]; } From 198cef9ba9c202767f3e84324333ff3df516e5b6 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:44:18 +0100 Subject: [PATCH 38/49] d3d12: draws that bind the same views again share one views block (RT-DRAW-VIEWS-UNCHANGED) set_vertex_buffers marked the list's DrawViews block stale for any call that wrote a slot, and OMSetRenderTargets for every call, without comparing with what was bound. A title that binds the same vertex buffer before each draw therefore made one make_shared per draw, about 728 bytes each (8 render targets and 32 vertex buffer views plus the control block), kept by the recorded draws until the list's Reset. set_vertex_buffers now marks the block stale only for a slot whose view changes, and OMSetRenderTargets only when the target count or one of the copied target views differs. TargetView and VertexBufferView get a defaulted operator== for the comparison. What each draw records is unchanged: the block always holds the targets and buffers bound at the draw. d3d12_draw_test --draw-views-sharing (ctest d3d12_draw_views_sharing) records 1000 draws with the same IASetVertexBuffers before each and counts the distinct blocks: 1000 before, 1 now. It also checks that a changed slot, an unbound slot, another render target and a rewritten RTV descriptor behind the same handle each start a new block that holds the new views. --- runtime/CMakeLists.txt | 6 +- runtime/shims/d3d12_com.cpp | 26 +++-- runtime/src/command_list.h | 4 + runtime/test/d3d12_draw_test.cpp | 9 ++ runtime/test/d3d12_draw_views_sharing.cpp | 128 ++++++++++++++++++++++ 5 files changed, 164 insertions(+), 9 deletions(-) create mode 100644 runtime/test/d3d12_draw_views_sharing.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..c8f21dbff1 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -4070,6 +4070,7 @@ if(TARGET Vulkan::Headers) VERBATIM) endforeach() add_executable(d3d12_draw_test test/d3d12_draw_test.cpp test/d3d12_stateful_indirect_pixels.cpp + test/d3d12_draw_views_sharing.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_VS_INT}) target_link_libraries(d3d12_draw_test PRIVATE gta6rt_d3d12_com) @@ -4094,6 +4095,8 @@ if(TARGET Vulkan::Headers) d3d12_stateful_indirect_nonindexed_counted_pixels PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) add_test(NAME d3d12_title_index_window COMMAND d3d12_draw_test --title-index-window) add_test(NAME d3d12_title_vertex_window COMMAND d3d12_draw_test --title-vertex-window) + # Draws that keep the same render targets and vertex buffers share one views block (recording only). + add_test(NAME d3d12_draw_views_sharing COMMAND d3d12_draw_test --draw-views-sharing) # LEONIDA_STUB_PIPELINES: a pipeline with no translated shader is a no-op stub when the switch is on. add_executable(d3d12_stub_pipelines_test test/d3d12_stub_pipelines_test.cpp) target_link_libraries(d3d12_stub_pipelines_test PRIVATE gta6rt_d3d12_com) @@ -4101,7 +4104,8 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_stub_pipelines_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_stub_pipelines COMMAND d3d12_stub_pipelines_test) set_tests_properties(d3d12_stub_pipelines PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) - set_tests_properties(d3d12_draw d3d12_title_index_window d3d12_title_vertex_window PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(d3d12_draw d3d12_title_index_window d3d12_title_vertex_window d3d12_draw_views_sharing + PROPERTIES SKIP_RETURN_CODE 77) # Graphics & compute PSO descriptor validation parity against live Windows D3D12 (WARP and HW). add_executable(d3d12_pso_validation_test test/d3d12_pso_validation_test.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_CS}) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4a61ffadbc..879e518ced 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -497,12 +497,17 @@ class GraphicsCommandList final const D3D12_CPU_DESCRIPTOR_HANDLE* depth) override { if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return check(false); - render_targets_.fill({}); - render_target_count_ = count; - draw_views_stale_ = true; + std::array bound{}; for (UINT i = 0; i < count && targets; ++i) { const SIZE_T handle = single_range ? targets[0].ptr + SIZE_T(i) * descriptor_size : targets[i].ptr; - if (handle) render_targets_[i] = *reinterpret_cast(handle); + if (handle) bound[i] = *reinterpret_cast(handle); + } + // The same targets bound again keep the current views block (draw_views), so the draws after them do not + // each allocate a new one. + if (count != render_target_count_ || bound != render_targets_) { + render_targets_ = bound; + render_target_count_ = count; + draw_views_stale_ = true; } depth_ = depth && depth->ptr ? *reinterpret_cast(depth->ptr) : leonida::TargetView{}; } @@ -1852,8 +1857,10 @@ class GraphicsCommandList final } } + // Only a slot whose view changes marks the views block stale (draw_views). Titles bind the same vertex buffer + // again before many of their draws, and a new block for each would be one allocation of about 700 bytes per + // draw, kept until the list's Reset. void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) { - if (count) draw_views_stale_ = true; for (UINT i = 0; i < count; ++i) { // A stream pool's GPU-only alias becomes the CPU view of the same pages (rule B, gfxgeom section 6): the // buffer made for it, and every other view naming that range, then use one host-readable address. @@ -1863,9 +1870,12 @@ class GraphicsCommandList final : 0; if (views) leonida::title_va_aliases().note(va, leonida::TitleVaAliases::vertex_view); if (views) leonida::title_va_aliases().want_buffer(va, views[i].SizeInBytes); - vertex_buffers_[start + i] = views ? leonida::VertexBufferView{va, views[i].SizeInBytes, - views[i].StrideInBytes} - : leonida::VertexBufferView{}; + const leonida::VertexBufferView view = + views ? leonida::VertexBufferView{va, views[i].SizeInBytes, views[i].StrideInBytes} + : leonida::VertexBufferView{}; + if (view == vertex_buffers_[start + i]) continue; + vertex_buffers_[start + i] = view; + draw_views_stale_ = true; } } diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 8b79c987e9..0c429f5f8d 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -229,6 +229,8 @@ struct TargetView { std::uint32_t first_layer; std::uint32_t layer_count; ColorViewFormat format = ColorViewFormat::resource; + + bool operator==(const TargetView&) const = default; }; // D3D12_RECT: right and bottom are exclusive. @@ -399,6 +401,8 @@ struct VertexBufferView { std::uint64_t va; std::uint32_t size; std::uint32_t stride; + + bool operator==(const VertexBufferView&) const = default; }; struct IndexBufferView { diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp index ffbfbf718d..bbf0426f93 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -80,6 +80,9 @@ static_assert(offsetof(Vertex, wrong_color) == 16); // Positive-only offscreen variant, sharing the translated-shader fixture, root signature and PSO description. int check_stateful_indirect_pixels(ID3D12Device* device, ID3D12RootSignature* root, D3D12_GRAPHICS_PIPELINE_STATE_DESC desc, bool multi, bool counted, bool nonindexed_only); +// Recording only, on the same root signature and PSO description: which draws share a views block (DrawViews). +int check_draw_views_sharing(ID3D12Device* device, ID3D12RootSignature* root, + const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc); int main(int argc, char** argv) { const bool nonindexed_only = argc == 3 && std::strcmp(argv[2], "--nonindexed-only") == 0; @@ -92,6 +95,7 @@ int main(int argc, char** argv) { const bool title_index = argc == 2 && std::strcmp(argv[1], "--title-index-window") == 0; const bool title_vertex = argc == 2 && std::strcmp(argv[1], "--title-vertex-window") == 0; const bool title_window = title_index || title_vertex; + const bool views_sharing = argc == 2 && std::strcmp(argv[1], "--draw-views-sharing") == 0; vktest::Device d; d.request_draw_indirect_first_instance = indirect_pixels; d.request_robust_index_view = indirect_pixels && !nonindexed_only; @@ -243,6 +247,11 @@ int main(int argc, char** argv) { pso_desc.NumRenderTargets = 1; pso_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; pso_desc.SampleDesc.Count = 1; + if (views_sharing) { + const int result = check_draw_views_sharing(device.p, root.p, pso_desc); + EXPECT(d.validation_errors() == 0); + return result; + } if (indirect_pixels) { const int result = check_stateful_indirect_pixels(device.p, root.p, pso_desc, multi_pixels || count_pixels, count_pixels, nonindexed_only); diff --git a/runtime/test/d3d12_draw_views_sharing.cpp b/runtime/test/d3d12_draw_views_sharing.cpp new file mode 100644 index 0000000000..8f0678f7f4 --- /dev/null +++ b/runtime/test/d3d12_draw_views_sharing.cpp @@ -0,0 +1,128 @@ +// The views block a list records with each draw (leonida::DrawViews: 8 render targets and 32 vertex buffer views, +// about 700 bytes, kept until the list's Reset) is shared by the draws that keep the same render targets and vertex +// buffers. A title that binds the same vertex buffer, or the same render targets, again before every draw gets one +// block, not one per draw. A changed vertex buffer slot, a different render target, or a new descriptor behind the +// same RTV handle still starts a new block that holds the new views. Recording only: nothing is submitted. +// Run by d3d12_draw_test --draw-views-sharing, on its device, root signature and PSO description. No game data. +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" + +#include +#include +#include +#include + +using namespace d3d12test; + +#define CHECK(x) \ + do { \ + if (!(x)) { \ + std::fprintf(stderr, "draw views line %d: %s\n", __LINE__, #x); \ + return 1; \ + } \ + } while (0) + +int check_draw_views_sharing(ID3D12Device* device, ID3D12RootSignature* root, + const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { + Ref pso; + CHECK(SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))); + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto upload_desc = buffer_desc(2048); + Ref vertices; + CHECK(SUCCEEDED(device->CreateCommittedResource(&upload_heap, {}, &upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&vertices.p)))); + const auto va = vertices->GetGPUVirtualAddress(); + const D3D12_VERTEX_BUFFER_VIEW first{va, 1024, 12}, second{va + 1024, 1024, 12}; + + // Two render targets, each named by the RTV of a heap of its own. + D3D12_RESOURCE_DESC tex{}; + tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex.Width = tex.Height = 64; + tex.DepthOrArraySize = tex.MipLevels = 1; + tex.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + tex.SampleDesc.Count = 1; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void*); // heap slot 9: the CPU handle in RAX + Ref targets[2]; + Ref heaps[2]; + D3D12_CPU_DESCRIPTOR_HANDLE rtvs[2]{}; + for (int i = 0; i < 2; ++i) { + CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, {}, &tex, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&targets[i].p)))); + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heaps[i].p)))); + rtvs[i].ptr = SIZE_T(reinterpret_cast(slot(heaps[i].p, 9))(heaps[i].p)); + device->CreateRenderTargetView(targets[i].p, nullptr, rtvs[i]); + } + const D3D12_VIEWPORT viewport{0, 0, 64, 64, 0, 1}; + + Ref allocator; + Ref list; + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p, + IID_PPV_ARGS(&list.p)))); + list->SetGraphicsRootSignature(root); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->RSSetViewports(1, &viewport); + list->OMSetRenderTargets(1, &rtvs[0], FALSE, nullptr); + constexpr std::size_t repeats = 1000; + for (std::size_t i = 0; i < repeats; ++i) { + list->IASetVertexBuffers(0, 1, &first); // the view slot 0 already holds after the first pass + list->DrawInstanced(3, 1, 0, 0); + } + list->IASetVertexBuffers(0, 1, &second); // [0] slot 0 changes + list->DrawInstanced(3, 1, 0, 0); + list->IASetVertexBuffers(0, 0, nullptr); // [1] no slot written, and the same render target bound again + list->OMSetRenderTargets(1, &rtvs[0], FALSE, nullptr); + list->DrawInstanced(3, 1, 0, 0); + list->IASetVertexBuffers(1, 1, &first); // [2] another slot is bound + list->DrawInstanced(3, 1, 0, 0); + list->IASetVertexBuffers(1, 1, nullptr); // [3] and unbound again + list->DrawInstanced(3, 1, 0, 0); + list->OMSetRenderTargets(1, &rtvs[1], FALSE, nullptr); // [4] another render target + list->DrawInstanced(3, 1, 0, 0); + // [5] The same handle, whose descriptor now names the first target. D3D12 reads the descriptor at + // OMSetRenderTargets, so this is a change as well. + device->CreateRenderTargetView(targets[0].p, nullptr, rtvs[1]); + list->OMSetRenderTargets(1, &rtvs[1], FALSE, nullptr); + list->DrawInstanced(3, 1, 0, 0); + CHECK(list->Close() == S_OK); + + std::vector recorded; + CHECK(rt::d3d12::recorded_commands(list.p, recorded) && recorded.size() == repeats + 6); + std::vector views; + for (const auto& command : recorded) { + const auto* draw = std::get_if(&command); + CHECK(draw && draw->views); + views.push_back(draw->views.get()); + } + const std::set repeated(views.begin(), views.begin() + repeats); + if (repeated.size() != 1) + std::fprintf(stderr, "draw views: %zu blocks for %zu draws that bind the same vertex buffer again\n", + repeated.size(), repeats); + CHECK(repeated.size() == 1); + + const leonida::DrawViews& base = *views[0]; + CHECK(base.render_target_count == 1 && base.render_targets[0].resource); + CHECK(base.vertex_buffers[0].va == va && base.vertex_buffers[0].size == 1024 && + base.vertex_buffers[0].stride == 12); + CHECK(!base.vertex_buffers[1].va); + const leonida::DrawViews* const* changed = views.data() + repeats; + CHECK(changed[0] != &base && changed[0]->vertex_buffers[0].va == va + 1024); + CHECK(changed[0]->render_targets[0].resource == base.render_targets[0].resource); + CHECK(changed[1] == changed[0]); + CHECK(changed[2] != changed[1] && changed[2]->vertex_buffers[1].va == va && + changed[2]->vertex_buffers[0].va == va + 1024); + CHECK(changed[3] != changed[2] && !changed[3]->vertex_buffers[1].va && + changed[3]->vertex_buffers[0].va == va + 1024); + CHECK(changed[4] != changed[3] && changed[4]->render_targets[0].resource && + changed[4]->render_targets[0].resource != base.render_targets[0].resource); + CHECK(changed[4]->render_target_count == 1 && changed[4]->vertex_buffers[0].va == va + 1024); + CHECK(changed[5] != changed[4] && changed[5]->render_targets[0].resource == base.render_targets[0].resource); + const std::set all(views.begin(), views.end()); + CHECK(all.size() == 6); + std::printf("draw views: %zu draws that bind the same vertex buffer again share 1 block; a changed slot, render " + "target or RTV descriptor starts a new one (%zu blocks for %zu draws)\n", + repeats, all.size(), views.size()); + return 0; +} From 98bbaffaed2fa8c7867e1eece0e1a6c2983c90eb Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:49:20 +0100 Subject: [PATCH 39/49] d3d12: a geometry range inside a live view is answered from that view, not copied again (RT-GEOMETRY-VIEWS-CONTAIN) GeometryViews::resolve looked only for its exact key (source, bytes), so a range inside a live view got a view of its own: (A, 128 KiB), (A, 64 KiB) and (A + 4 KiB, 64 KiB) were three views and 256 KiB of copies of 132 KiB of the title's bytes, each charged to LEONIDA_GEOMETRY_MB, each watched and refreshed on its own. docs/d3d12_vulkan.md measured 4.4-6 GB of VRAM in geometry copies in a world run. The live views that no other live view holds now form an index by source (outer_). As none of them holds another, their ends rise with their sources, so one lookup finds the view a range is inside. A range inside a filled live view is answered with that view's address plus its offset: the view's tiles already watch it and its refresh copies it. A view that is not filled (made over pages that were not all readable) is not used, and the exact-key path is unchanged. Such a range is that view's bytes, so it leaves with it. retire_range retires it with the view, tells on_retire its own source, size and address (the device drops its aliases, heap slots and stream-pool extent by that address) and removes it from the lock-free answers; the live views the retired one held take its place in the index. The next request for the range makes a view of its own. Nothing is retired for disuse. A release can now retire a range the title still uses: one inside the released view that the release did not touch. A command list recorded before the retirement may name it and be executed after, so such a view's memory also waits until no list older than the retirement is left (src/command_list_epochs.h), as a retired title window's does. A view with no such range is freed as before. The geometry buffers line counts the ranges answered from inside a view, and LEONIDA_GEOMETRY_CONTAINED=0 gives every range a copy of its own, as before. Tests: geometry_views case 17. Largest first, the two inner ranges are one view of 128 KiB (3 views and 256 KiB before); smallest first, (B, 64 KiB), (B, 128 KiB) and (B + 4 KiB, 64 KiB) are two views; a write inside an inner range reaches it through the view; retiring the outer view by its tail retires the ranges inside it, each told with its own address, and one asked for again gets a view of its own; once the larger view of B goes, the smaller one answers what is inside it; while a list stamped before the retirement lives, only the view retired with nothing inside it is freed, and the other at the next replay's ticket once the list is gone. On d44285197 11 of the 92 checks fail; with the change all pass, and with LEONIDA_GEOMETRY_CONTAINED=0 the same 11 fail. --- docs/d3d12_vulkan.md | 10 ++- runtime/README.md | 1 + runtime/shims/d3d12_geometry_views.h | 112 +++++++++++++++++++++++++-- runtime/test/geometry_views_test.cpp | 96 ++++++++++++++++++++++- 4 files changed, 209 insertions(+), 10 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e843d8debc..4dfd06a073 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1780,7 +1780,9 @@ The copies: whole gets a copy of its whole range, so the BVH builder's commands are recorded. - `LEONIDA_GEOMETRY_MB` sets the device-local memory cap for streamed buffer views. The default is 0. A positive cap enables persistent copies of placed buffer SRVs and buffer descriptors in title memory. - A GPU-only reservation uses its paired CPU mapping. Matching source ranges share one copy. + A GPU-only reservation uses its paired CPU mapping. Matching source ranges share one copy, and a range inside a + live, filled copy is answered from that copy at its offset instead of being copied again + (`LEONIDA_GEOMETRY_CONTAINED=0`: a copy of its own, as before). The resource descriptor heap keeps its console indices and original CPU bytes. Its shader-visible copy encodes each resolved buffer's offset from the arena base. CPU writes through either physical mapping, file reads and XMem remaps invalidate the affected copies before their next submission. @@ -1799,8 +1801,10 @@ The copies: extent is forgotten, and its memory is freed only after every ExecuteCommandLists replay in progress at the retirement has recorded its submissions and those have completed (`kAfterExecutes`). Before it leaves the refresh it is copied once more from its pages if they are still readable (a heap block freed in memory that - stays committed). The next view of the range makes a new copy. - `geometry_views_test` cases 14-16 cover this without a GPU. + stays committed). The ranges answered from inside it go with it, each invalidated by its own address; when the + release did not touch one of them, the view's memory also waits until no command list recorded before the + retirement is left, as a retired title window's does. The next view of the range makes a new copy. + `geometry_views_test` cases 14-17 cover this without a GPU. - **Which pages changed** since the last refresh: where xmem reserved the title's memory with `MEM_WRITE_WATCH` (`XMemVirtualAlloc`'s ordinary regions and the title's `VirtualAlloc` reservations, not placeholders or physical-page windows), the kernel says (`GetWriteWatch` with reset, its answers kept for every copy over the page: diff --git a/runtime/README.md b/runtime/README.md index cdce0a811d..ce14ddfe11 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -393,6 +393,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. | | `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. | | `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. | +| `LEONIDA_GEOMETRY_CONTAINED` | on | A range of title memory inside a live, filled geometry copy (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) is answered from that copy at its offset, refreshed with it and retired with it, instead of being copied again. `0` gives every range a copy of its own, as before: the same title bytes can then be held several times against the cap. The `geometry buffers` line counts the ranges answered this way. | | `LEONIDA_GEOMETRY_HOST` | unset | Where the geometry copies (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) live. Unset or `0`: device-local memory through the BAR while the driver gives it (several GB of VRAM in a world run). `1`: system memory outside VRAM, write-back where the device offers a cached host type; `2`: system memory, write-combined. The GPU then reads every vertex and index of a copy over the bus, which can cost frame time in geometry-heavy passes. A device whose host-visible memory is all device-local (an integrated GPU) keeps its types. The choice is logged once and in the `geometry buffers` line. | | `LEONIDA_TITLE_FILL_ASYNC` | unset | Trades correctness for speed. `1` stops device slot 70 views from hashing and filling the texture they name on the title's thread: a texture never filled or known stale is queued for a worker thread that fills one texture at a time. Until then a shader samples the image as it is, empty or a frame behind. | | `LEONIDA_TITLE_VIEW_REFRESH_MS` | `0` | The shortest time, in milliseconds, between two checks of a title texture's bytes when a device slot 70 view of it is written. `0` checks at every view. The periodic pass still checks the texture on its own period, and a texture known stale is checked at once. Has no effect with `LEONIDA_TITLE_FILL_ASYNC=1`. | diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h index 58649a29c2..4c2a6a7486 100644 --- a/runtime/shims/d3d12_geometry_views.h +++ b/runtime/shims/d3d12_geometry_views.h @@ -1,6 +1,7 @@ #pragma once #include "d3d12_title_buffer_windows.h" +#include "../src/command_list_epochs.h" #include "../src/memory_breakdown.h" #include "../src/title_geometry_watch.h" #include @@ -21,7 +22,7 @@ namespace rt::d3d12 { // Every CPU mapping of a source tile is watched; a physical remap changes which aliases must be watched. // Views whose title range is released are retired immediately and their backing storage is reclaimed once // in-flight GPU submissions up to their retire ticket have completed; previously cap-refused ranges retry -// once budget has been freed. +// once budget has been freed. A range inside a live view is answered from that view's bytes, not copied again. enum class GeometryCopy { copied, unreadable, interrupted }; class GeometryViews { @@ -57,6 +58,7 @@ class GeometryViews { std::size_t size{}; std::uint64_t ticket{}; // kAfterExecutes until execute_end() stamps it std::uint64_t epoch{}; // the last execute begun when it was retired (kAfterExecutes only) + std::uint64_t lists{}; // the command-list epoch it waits for (retire_range), 0 for none }; std::uint64_t cap_override_{}; mutable std::mutex mutex_; @@ -109,6 +111,16 @@ class GeometryViews { std::size_t live_views_{}; bool refreshing_{}; std::map by_address_; + // The live views that no other live view holds, by their first byte: source -> {end, id}. As none holds another, + // their ends rise with their sources, so the last one starting at or before an address reaches furthest past it, + // and a range is inside some live view exactly when it is inside that one (outer_view_locked). A view held by one + // that is retired takes its place (retire_range). Under mutex_. + std::map> outer_; + // The keys resolve() answered from inside a live view instead of with a view of their own, with that view's id. + // They are its bytes at their offsets, watched and refreshed with it, and they leave with it (retire_range). + // Under mutex_. + std::map contained_; + std::uint64_t contained_hits_{}; std::map tiles_; std::vector retired_; std::atomic retired_count_{0}; @@ -154,6 +166,24 @@ class GeometryViews { } } + static constexpr std::size_t kNoView = SIZE_MAX; + // The live view that holds all of [cpu, cpu + bytes), or kNoView. mutex_ held; cpu + bytes does not wrap. + std::size_t outer_view_locked(Address cpu, std::size_t bytes) const { + auto it = outer_.upper_bound(cpu); + if (it == outer_.begin()) return kNoView; + --it; + return it->second.first >= cpu + bytes ? it->second.second : kNoView; + } + // A live view enters outer_ unless one there holds it, and the ones there that it holds leave. mutex_ held. + void enter_outer_locked(Address source, std::size_t size, std::size_t id) { + const Address end = source + size; + auto it = outer_.upper_bound(source); + if (it != outer_.begin() && std::prev(it)->second.first >= end) return; + // The ones it holds start at or after it, their ends rising: they leave until one reaches past its end. + for (it = outer_.lower_bound(source); it != outer_.end() && it->second.first <= end;) it = outer_.erase(it); + outer_.emplace(source, std::make_pair(end, id)); + } + bool update(Address va, Tile& t) { namespace watch = leonida::geometry_writes; if (!t.primary) t.primary = watch::acquire(va); @@ -245,6 +275,15 @@ class GeometryViews { } int system_memory() const { return pool_.system_memory(); } + // LEONIDA_GEOMETRY_CONTAINED=0: a range inside a live view gets a copy of its own, as before. + static bool contain_setting() { + static const bool value = [] { + const char* v = std::getenv("LEONIDA_GEOMETRY_CONTAINED"); + return !v || std::strcmp(v, "0") != 0; + }(); + return value; + } + bool has_released() const { return leonida::geometry_writes::has_released(releases_); } bool has_retired() const { return retired_count_.load(std::memory_order_acquire) != 0; } bool has_pending_reclaim() const { return has_released() || has_retired(); } @@ -309,6 +348,19 @@ class GeometryViews { publish(key, known, 0); return known; } + // A range inside a live view is that view's bytes at its offset: the view's tiles already watch it and its + // refresh copies it, so a copy of its own would hold the same title bytes again, against the same cap. The + // view must be filled: one made over pages not all readable then is zeroed, also where the range is readable. + if (contain_setting()) { + if (const std::size_t id = outer_view_locked(cpu, bytes); id != kNoView && views_[id].ready) { + const VkDeviceSize at = views_[id].va + (cpu - views_[id].source); + contained_[key] = id; + refused_.erase(key); + ++contained_hits_; + publish(key, at, 0); + return at; + } + } const std::uint64_t gen = free_generation_.load(std::memory_order_acquire); const auto refused_it = refused_.find(key); if (refused_it != refused_.end() && refused_it->second == gen) { @@ -352,6 +404,7 @@ class GeometryViews { keys_[key] = id; by_address_.emplace(bda, id); } + if (contain_setting()) enter_outer_locked(cpu, bytes, id); if (bytes > max_view_bytes_) max_view_bytes_ = bytes; ++live_views_; bytes_ += bytes; @@ -411,11 +464,13 @@ class GeometryViews { std::lock_guard execute(execute_mutex_); for (const auto s : executing_) oldest = (std::min)(oldest, s); } + // Before the ticket: a list released after this read has had its submissions counted in it. + const std::uint64_t oldest_list = leonida::command_list_epochs::oldest(); const std::uint64_t ticket = submitted(); bool left = false; for (auto& r : retired_) { if (r.ticket != kAfterExecutes) continue; - if (r.epoch < oldest) r.ticket = ticket; + if (r.epoch < oldest && r.lists <= oldest_list) r.ticket = ticket; else left = true; } unstamped_.store(left, std::memory_order_release); @@ -429,6 +484,8 @@ class GeometryViews { // committed) may hold new bytes, and a list recorded before the release that runs in a submission the view waits // for reads those, as it would have read them in the console's memory. Decommitted or unmapped memory is not // readable, so such a view keeps what it held. + // The ranges resolve() answered from inside a retired view go with it, each told to `on_retire` with the address + // it was answered with. Returns the number of views retired. template std::size_t retire_range(Address begin, Address end, std::uint64_t retire_ticket = 0, OnRetire&& on_retire = {}, Copy&& final_copy = {}) { @@ -439,6 +496,7 @@ class GeometryViews { VkDeviceSize va; }; std::vector callbacks; + std::size_t retired_views = 0; { std::lock_guard lock(mutex_); std::vector ids; @@ -456,6 +514,7 @@ class GeometryViews { if (begin < key.first + key.second) stale_refused.push_back(key); } if (ids.empty() && stale_refused.empty()) return 0; + retired_views = ids.size(); if (retire_ticket == kAfterExecutes && !ids.empty()) unstamped_.store(true, std::memory_order_release); callbacks.reserve(ids.size()); const std::size_t first_retired = retired_.size(); @@ -476,6 +535,39 @@ class GeometryViews { callbacks.push_back({v.source, v.size, v.va}); retired_.push_back({v.va, v.size, retire_ticket, 0}); } + // The ranges answered from inside these views are their bytes and leave with them. A view that was in + // outer_ leaves it; the live views it held take its place below, once the retired ones are out of keys_. + std::vector inner; + std::vector> vacated; + std::uint64_t lists = 0; + for (std::size_t i = 0; i < ids.size(); ++i) { + const std::size_t id = ids[i]; + const View& v = views_[id]; + bool untouched = false; + for (auto it = contained_.lower_bound({v.source, 0}); + it != contained_.end() && it->first.first < v.source + v.size;) { + if (it->second != id) { + ++it; + continue; + } + const auto [source, size] = it->first; + untouched |= source >= end || source + size <= begin; + callbacks.push_back({source, size, v.va + (source - v.source)}); + inner.push_back(it->first); + it = contained_.erase(it); + } + // A range inside it that the release did not touch is still the title's, and a command list recorded + // before now that names it may be executed after: the view's memory also waits until no such list is + // left, as a retired title window does (src/command_list_epochs.h). + if (untouched && retire_ticket == kAfterExecutes) { + if (!lists) lists = leonida::command_list_epochs::advance(); + retired_[first_retired + i].lists = lists; + } + if (const auto it = outer_.find(v.source); it != outer_.end() && it->second.second == id) { + vacated.emplace_back(v.source, v.source + v.size); + outer_.erase(it); + } + } if (!ids.empty()) { std::unique_lock structure(structure_mutex_); for (const auto id : ids) { @@ -485,9 +577,13 @@ class GeometryViews { v.alive = false; } } + for (const auto& [from, to] : vacated) + for (auto it = keys_.lower_bound({from, 0}); it != keys_.end() && it->first.first < to; ++it) + enter_outer_locked(it->first.first, it->first.second, it->second); { std::unique_lock fast(fast_mutex_); for (const auto id : ids) fast_.erase({views_[id].source, views_[id].size}); + for (const auto& k : inner) fast_.erase(k); for (const auto& k : stale_refused) fast_.erase(k); } // No resolve() or find() answers these views from here on, so a replay that begins now cannot name them: @@ -509,7 +605,7 @@ class GeometryViews { retired_count_.store(retired_.size(), std::memory_order_release); } for (const auto& item : callbacks) on_retire(item.source, item.size, item.va); - return callbacks.size(); + return retired_views; } // Frees backing storage for retired views whose GPU retire_ticket <= completed_ticket, returning their budget @@ -711,15 +807,17 @@ class GeometryViews { std::fprintf(stderr, "[rt] geometry buffers: seen %zu, backed %zu (%llu bytes), populated %llu, cap %llu MiB, " "cap refused %llu, retried ok %llu, evicted %llu (reaped %llu, retired %zu, copied at " "retirement %llu), allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, " - "reserved %llu bytes (%s)\n", - keys_.size() + refused_.size(), live_views_, (unsigned long long)bytes_, (unsigned long long)ready_, + "reserved %llu bytes (%s), ranges inside a live view %zu (%llu so far)\n", + keys_.size() + refused_.size() + contained_.size(), live_views_, (unsigned long long)bytes_, + (unsigned long long)ready_, (unsigned long long)(effective_cap() >> 20), (unsigned long long)cap_refusals_, (unsigned long long)retries_succeeded_, (unsigned long long)evicted_, (unsigned long long)reaped_, retired_.size(), (unsigned long long)final_copies_, (unsigned long long)allocation_failures_, (unsigned long long)uploads_, (unsigned long long)uploaded_, tiles_.size(), static_cast(pool_.reserved()), - pool_.system_memory() ? "system memory" : "device-local"); + pool_.system_memory() ? "system memory" : "device-local", contained_.size(), + (unsigned long long)contained_hits_); std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes (%llu views by " "their written tiles only); %.3f s checking and refreshing sources, %llu bytes cleared\n", static_cast(dirty_refreshes_), static_cast(submissions_), @@ -740,6 +838,8 @@ class GeometryViews { by_address_.clear(); views_.clear(); } + outer_.clear(); + contained_.clear(); { std::unique_lock fast(fast_mutex_); fast_.clear(); diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp index 37a1bd391d..d9fb6c658c 100644 --- a/runtime/test/geometry_views_test.cpp +++ b/runtime/test/geometry_views_test.cpp @@ -19,9 +19,14 @@ // (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device; // 14. LEONIDA_GEOMETRY_HOST picks a system-memory type (write-back for 1, write-combined for 2), never the BAR; // 15. a retired view is copied once more from its pages when they are readable, not when they are not; -// 16. a full release queue joins touching ranges before it collapses to one covering range. +// 16. a full release queue joins touching ranges before it collapses to one covering range; +// 17. a range inside a live view is answered from that view (its address plus the offset), not copied again; it is +// refreshed with that view and leaves with it, and a view it was inside before keeps answering after the outer +// one goes; a retired view with a range inside it the release did not touch also waits for the command lists +// recorded before (LEONIDA_GEOMETRY_CONTAINED=0, a copy of its own as before, fails 17). #include +#include #include #include #include @@ -31,6 +36,7 @@ #include #include "../shims/d3d12_geometry_views.h" +#include "../src/command_list_epochs.h" #include "../src/title_va_alias.h" namespace { @@ -620,6 +626,94 @@ int main() { VirtualFree(host_title, 0, MEM_RELEASE); } + // 17. Ranges inside a live view: (A, 128 KiB), then (A, 64 KiB) and (A + 4 KiB, 64 KiB), are 132 KiB of the + // title's bytes. Each with a copy of its own they were three views and 256 KiB of copies; the two inside the first + // are its bytes at their offsets, so one view of 128 KiB. Asked for smallest first, (B, 64 KiB) is no view's bytes + // yet and (B, 128 KiB) is not inside it: two views, and (B + 4 KiB, 64 KiB) is inside the second. + { + auto* nest_title = + static_cast(VirtualAlloc(nullptr, 8 * kTile, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!nest_title) return 1; + for (std::size_t i = 0; i < 8 * kTile; ++i) nest_title[i] = std::uint8_t((i * 11) ^ 0x6e); + const auto a = reinterpret_cast(nest_title); + const auto b = a + 4 * kTile; + rt::d3d12::GeometryViews nest; + const auto host_of = [&](std::uint64_t at) -> const std::uint8_t* { + std::uint64_t host = 0, room = 0; + return at && nest.lookup(device.arena.address + at, host, room) ? reinterpret_cast(host) + : nullptr; + }; + const std::uint64_t outer = nest.resolve(device, a, 2 * kTile, copy); + const std::uint64_t head = nest.resolve(device, a, kTile, copy); + const std::uint64_t inner = nest.resolve(device, a + 4096, kTile, copy); + check(outer != 0 && head == outer && inner == outer + 4096 && nest.live_views() == 1 && + nest.bytes() == 2 * kTile, + "two ranges inside a live 128 KiB view are its bytes at their offsets: one view, 128 KiB"); + check(nest.resolve(device, a + 4096, kTile, copy) == inner && nest.find(a + 4096, kTile) == inner && + nest.find(a, kTile) == head && host_of(inner) && !std::memcmp(host_of(inner), nest_title + 4096, kTile), + "asked again or found, the inner range has the same address, which holds the title's bytes"); + title_write(a + 4096 + 77, 0xe1); + nest.refresh(copy); + check(host_of(inner) && host_of(inner)[77] == 0xe1, "a write inside the inner range reaches it with the view"); + + const std::uint64_t small = nest.resolve(device, b, kTile, copy); + const std::uint64_t large = nest.resolve(device, b, 2 * kTile, copy); + const std::uint64_t inside = nest.resolve(device, b + 4096, kTile, copy); + check(small != 0 && large != 0 && large != small && inside == large + 4096 && nest.live_views() == 3 && + nest.bytes() == 5 * kTile, + "smallest first: (B, 64 KiB) and (B, 128 KiB) are two views, (B + 4 KiB, 64 KiB) is inside the second"); + + // Retiring a range at the outer view's tail, which neither inner range touches, retires them with it: they + // were its bytes. Each is told by the address it was answered with. + std::vector> told; + const auto tell = [&](std::uintptr_t source, std::size_t, VkDeviceSize at) { told.emplace_back(source, at); }; + const std::size_t retired = nest.retire_range(a + 100 * 1024, a + 104 * 1024, 1, tell); + const auto was_told = [&](std::uintptr_t source, VkDeviceSize at) { + return std::find(told.begin(), told.end(), std::make_pair(source, at)) != told.end(); + }; + check(retired == 1 && told.size() == 3 && was_told(a, outer) && was_told(a, head) && + was_told(a + 4096, inner) && nest.live_views() == 2, + "retiring the outer view retires the ranges inside it, each told with its own address"); + check(nest.find(a, kTile) == 0 && nest.find(a + 4096, kTile) == 0 && nest.find(a, 2 * kTile) == 0, + "no range inside the retired view is found any more"); + check(nest.reap(device, 1) == 1 && nest.bytes() == 3 * kTile, "the outer view's 128 KiB are freed once"); + const std::uint64_t again = nest.resolve(device, a + 4096, kTile, copy); + check(again != 0 && nest.live_views() == 3 && nest.bytes() == 4 * kTile && host_of(again) && + !std::memcmp(host_of(again), nest_title + 4096, kTile), + "asked for after its view went, the inner range gets a view of its own with the title's bytes"); + + // The view (B, 128 KiB) goes by its tail; (B, 64 KiB), which it held inside, answers what is inside it again. + told.clear(); + check(nest.retire_range(b + 100 * 1024, b + 104 * 1024, 2, tell) == 1 && told.size() == 2 && + was_told(b, large) && was_told(b + 4096, large + 4096) && nest.find(b, kTile) == small, + "the outer view of B retires with its inner range; the smaller view of B stays"); + const std::uint64_t quarter = nest.resolve(device, b + 8192, kTile / 4, copy); + check(nest.reap(device, 2) == 1 && quarter == small + 8192 && nest.live_views() == 2, + "a range inside the smaller view of B is answered from it once the larger one has gone (and is freed)"); + + // A command list recorded before a retirement (its command_list_epochs stamp) may name a range inside the + // retired view that the release did not touch, which is still the title's: that view's memory waits for the + // list as well as for the replays. A view with nothing inside it, retired in the same replay, does not. + const auto c = a + 6 * kTile; + const std::uint64_t outer_c = nest.resolve(device, c, 2 * kTile, copy); + check(outer_c != 0 && nest.resolve(device, c + 4096, kTile, copy) == outer_c + 4096, + "a third outer view with a range inside it"); + auto list = std::make_unique(); + const std::uint64_t replay = nest.execute_begin(); + nest.retire_range(c + 100 * 1024, c + 104 * 1024, rt::d3d12::GeometryViews::kAfterExecutes); + nest.retire_range(a + 4096, a + 8192, rt::d3d12::GeometryViews::kAfterExecutes); // `again`: nothing inside + nest.execute_end(replay, [] { return std::uint64_t(3); }); + check(nest.reap(device, 3) == 1 && nest.retired_count() == 1, + "while a list recorded before the retirement lives, only the view with nothing inside it is freed"); + list.reset(); + const std::uint64_t next = nest.execute_begin(); + nest.execute_end(next, [] { return std::uint64_t(4); }); + check(nest.reap(device, 3) == 0 && nest.reap(device, 4) == 1 && nest.retired_count() == 0, + "once that list is gone, the outer view waits only for the next replay's submissions"); + nest.release(device); + VirtualFree(nest_title, 0, MEM_RELEASE); + } + std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } From 5893834b894f3e89a4f9da787d761cb06bfd74b8 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:18:18 +0100 Subject: [PATCH 40/49] d3d12: a pinned geometry view keeps its written tiles; a contained range holds its view until nothing answers it (RT-GEOMETRY-VIEWS-CONTAIN) refresh() skipped every per-tile copy of a view over a tile that cannot be guarded yet (a file read into it in flight), but update() had already taken the versions of the view's other written tiles. Those writes never reached the view: once the read ended only the retry tile was copied. With whole-view fills this caught up after the pin; with per-tile copies it did not, and containment widened it to every range inside such a view. A pinned view is now only kept from being filled whole. The retry tile is never among the written ones, so a filled view still takes its other written tiles at once and the retry tile once it can be guarded. retire_range took the command-list epoch for a view with an untouched range inside it while that range was still answered: from the lock-free answers until later in the same critical section, and from the alias table, heap slots and stream-pool span until on_retire had run after the lock. A list reset in that window carried a newer stamp, could still take the range's address, and did not hold the view. Such a view is now pending until on_retire has run, and only then takes its epoch. The copy of an acceleration structure's whole range (copy_title_range) is never answered from inside a larger view: a release elsewhere in that view would retire the structure with it, and its next copy would be made from the title's pages. resolve() takes contain = false for it. Also: a range answered from inside a view twice by racing threads is counted once, the geometry buffers line counts the retired views waiting for older command lists, and docs/d3d12_vulkan.md says that such a view is not refreshed while it waits, unlike a retired title window. Tests: geometry_views case 17 gains a stamp made inside on_retire, which must hold the view, and a range asked for with contain = false inside a live view, which gets a view of its own that outlives it. Case 18: a view over two tiles and a range inside its first tile; the title writes both tiles while a file read into the second is in flight, and the write to the first must reach both at the next refresh. Built with the one contain = false argument removed (neither has the parameter), 16 of 98 checks fail on d44285197, both checks of case 18 among them, and 5 fail on the previous commit. With this change all pass, and with LEONIDA_GEOMETRY_CONTAINED=0 the 14 containment checks of case 17 fail. --- docs/d3d12_vulkan.md | 16 +++-- runtime/README.md | 2 +- runtime/shims/d3d12_geometry_views.h | 75 +++++++++++++++++------- runtime/shims/d3d12_vulkan_device.cpp | 7 ++- runtime/test/geometry_views_test.cpp | 84 +++++++++++++++++++++++++-- 5 files changed, 150 insertions(+), 34 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 4dfd06a073..52f983eeb3 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1782,10 +1782,14 @@ The copies: A positive cap enables persistent copies of placed buffer SRVs and buffer descriptors in title memory. A GPU-only reservation uses its paired CPU mapping. Matching source ranges share one copy, and a range inside a live, filled copy is answered from that copy at its offset instead of being copied again - (`LEONIDA_GEOMETRY_CONTAINED=0`: a copy of its own, as before). + (`LEONIDA_GEOMETRY_CONTAINED=0`: a copy of its own, as before). The copy of an acceleration structure's whole + range (`copy_title_range`: a destination, scratch or input no other range holds whole) is never answered that way, + so a release elsewhere in a larger copy cannot take a structure the GPU wrote with it. The resource descriptor heap keeps its console indices and original CPU bytes. Its shader-visible copy encodes each resolved buffer's offset from the arena base. CPU writes through either physical mapping, - file reads and XMem remaps invalidate the affected copies before their next submission. + file reads and XMem remaps invalidate the affected copies before their next submission. A filled copy over a + 64 KiB tile that a file read is still writing (it cannot be guarded yet) takes its other written tiles at once, + and that tile once the read has ended (`geometry_views_test` case 18). During an untyped heap scan, an extent above 16 MiB with no format or an unrecognized descriptor encoding reuses only an independently established geometry view. An explicit table or placed SRV can establish that view. The Vulkan memory probe reports populated views, payload and reserved bytes, @@ -1802,9 +1806,11 @@ The copies: retirement has recorded its submissions and those have completed (`kAfterExecutes`). Before it leaves the refresh it is copied once more from its pages if they are still readable (a heap block freed in memory that stays committed). The ranges answered from inside it go with it, each invalidated by its own address; when the - release did not touch one of them, the view's memory also waits until no command list recorded before the - retirement is left, as a retired title window's does. The next view of the range makes a new copy. - `geometry_views_test` cases 14-17 cover this without a GPU. + release did not touch one of them, the view's memory also waits until no command list is left whose recording + began before those invalidations had run. Unlike a retired title window, the view is not refreshed meanwhile: a + list recorded before the retirement and executed after it reads such a range as the last copy left it. The + `geometry buffers` line counts the retired views waiting for command lists. The next view of the range makes a + new copy. `geometry_views_test` cases 14-17 cover this without a GPU. - **Which pages changed** since the last refresh: where xmem reserved the title's memory with `MEM_WRITE_WATCH` (`XMemVirtualAlloc`'s ordinary regions and the title's `VirtualAlloc` reservations, not placeholders or physical-page windows), the kernel says (`GetWriteWatch` with reset, its answers kept for every copy over the page: diff --git a/runtime/README.md b/runtime/README.md index ce14ddfe11..28793a1efd 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -393,7 +393,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. | | `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. | | `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. | -| `LEONIDA_GEOMETRY_CONTAINED` | on | A range of title memory inside a live, filled geometry copy (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) is answered from that copy at its offset, refreshed with it and retired with it, instead of being copied again. `0` gives every range a copy of its own, as before: the same title bytes can then be held several times against the cap. The `geometry buffers` line counts the ranges answered this way. | +| `LEONIDA_GEOMETRY_CONTAINED` | on | A range of title memory inside a live, filled geometry copy (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) is answered from that copy at its offset, refreshed with it and retired with it, instead of being copied again. The copy of an acceleration structure's whole range (`copy_title_range`) always gets its own. `0` gives every range a copy of its own, as before: the same title bytes can then be held several times against the cap. The `geometry buffers` line counts the ranges answered this way, and the retired copies that wait for older command lists because a range inside them was still the title's. | | `LEONIDA_GEOMETRY_HOST` | unset | Where the geometry copies (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) live. Unset or `0`: device-local memory through the BAR while the driver gives it (several GB of VRAM in a world run). `1`: system memory outside VRAM, write-back where the device offers a cached host type; `2`: system memory, write-combined. The GPU then reads every vertex and index of a copy over the bus, which can cost frame time in geometry-heavy passes. A device whose host-visible memory is all device-local (an integrated GPU) keeps its types. The choice is logged once and in the `geometry buffers` line. | | `LEONIDA_TITLE_FILL_ASYNC` | unset | Trades correctness for speed. `1` stops device slot 70 views from hashing and filling the texture they name on the title's thread: a texture never filled or known stale is queued for a worker thread that fills one texture at a time. Until then a shader samples the image as it is, empty or a frame behind. | | `LEONIDA_TITLE_VIEW_REFRESH_MS` | `0` | The shortest time, in milliseconds, between two checks of a title texture's bytes when a device slot 70 view of it is written. `0` checks at every view. The periodic pass still checks the texture on its own period, and a texture known stale is checked at once. Has no effect with `LEONIDA_TITLE_FILL_ASYNC=1`. | diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h index 4c2a6a7486..e19abb5c10 100644 --- a/runtime/shims/d3d12_geometry_views.h +++ b/runtime/shims/d3d12_geometry_views.h @@ -4,6 +4,7 @@ #include "../src/command_list_epochs.h" #include "../src/memory_breakdown.h" #include "../src/title_geometry_watch.h" +#include #include #include #include @@ -52,6 +53,7 @@ class GeometryViews { struct FastEntry { VkDeviceSize va{}; std::uint64_t refused_at{}; // free_generation_ when refused (only meaningful when va == 0) + bool inside{}; // answered from inside a live view (contained_) }; struct Retired { VkDeviceSize va{}; @@ -60,6 +62,9 @@ class GeometryViews { std::uint64_t epoch{}; // the last execute begun when it was retired (kAfterExecutes only) std::uint64_t lists{}; // the command-list epoch it waits for (retire_range), 0 for none }; + // Retired::lists until retire_range has taken the epoch, once nothing answers the ranges inside the view: until + // then execute_end does not stamp the view. + static constexpr std::uint64_t kListsPending = UINT64_MAX; std::uint64_t cap_override_{}; mutable std::mutex mutex_; std::mutex refresh_mutex_; // refresh() only, held for its whole run, before mutex_ @@ -86,9 +91,9 @@ class GeometryViews { mutable std::shared_mutex structure_mutex_; mutable std::shared_mutex fast_mutex_; std::unordered_map fast_; - void publish(const Key& key, VkDeviceSize va, std::uint64_t refused_at = 0) { // mutex_ held + void publish(const Key& key, VkDeviceSize va, std::uint64_t refused_at = 0, bool inside = false) { // mutex_ held std::unique_lock lock(fast_mutex_); - fast_[key] = {va, refused_at}; + fast_[key] = {va, refused_at, inside}; } bool fast_find(const Key& key, VkDeviceSize& va) const { std::shared_lock lock(fast_mutex_); @@ -97,12 +102,13 @@ class GeometryViews { va = it->second.va; return true; } - bool fast_find_resolve(const Key& key, VkDeviceSize& va) const { + bool fast_find_resolve(const Key& key, VkDeviceSize& va, bool contain) const { std::shared_lock lock(fast_mutex_); const auto it = fast_.find(key); if (it == fast_.end()) return false; if (it->second.va == 0 && it->second.refused_at != free_generation_.load(std::memory_order_acquire)) return false; + if (it->second.inside && !contain) return false; va = it->second.va; return true; } @@ -335,13 +341,16 @@ class GeometryViews { return it == keys_.end() || !views_[it->second].alive ? 0 : views_[it->second].va; } + // `contain` false: a range inside a live view gets a view of its own all the same. A structure the GPU writes + // (copy_title_range) needs one: in another view's bytes it would leave with that view when a release elsewhere in + // it retires it, and its next copy would be made from the title's pages. template - std::uint64_t resolve(Device& device, Address cpu, std::size_t bytes, Copy copy) { + std::uint64_t resolve(Device& device, Address cpu, std::size_t bytes, Copy copy, bool contain = true) { if (!bytes || bytes > UINTPTR_MAX - cpu) return 0; const std::uint64_t limit = effective_cap(); if (!limit) return 0; const Key key = std::make_pair(cpu, bytes); - if (VkDeviceSize known = 0; fast_find_resolve(key, known)) return known; + if (VkDeviceSize known = 0; fast_find_resolve(key, known, contain)) return known; std::lock_guard lock(mutex_); if (const auto it = keys_.find(key); it != keys_.end()) { const VkDeviceSize known = views_[it->second].va; @@ -351,13 +360,13 @@ class GeometryViews { // A range inside a live view is that view's bytes at its offset: the view's tiles already watch it and its // refresh copies it, so a copy of its own would hold the same title bytes again, against the same cap. The // view must be filled: one made over pages not all readable then is zeroed, also where the range is readable. - if (contain_setting()) { + if (contain && contain_setting()) { if (const std::size_t id = outer_view_locked(cpu, bytes); id != kNoView && views_[id].ready) { const VkDeviceSize at = views_[id].va + (cpu - views_[id].source); - contained_[key] = id; + // Two threads that missed the lock-free answer for the same key both come here, one after the other. + if (contained_.insert_or_assign(key, id).second) ++contained_hits_; refused_.erase(key); - ++contained_hits_; - publish(key, at, 0); + publish(key, at, 0, true); return at; } } @@ -470,7 +479,7 @@ class GeometryViews { bool left = false; for (auto& r : retired_) { if (r.ticket != kAfterExecutes) continue; - if (r.epoch < oldest && r.lists <= oldest_list) r.ticket = ticket; + if (r.epoch < oldest && r.lists != kListsPending && r.lists <= oldest_list) r.ticket = ticket; else left = true; } unstamped_.store(left, std::memory_order_release); @@ -496,6 +505,7 @@ class GeometryViews { VkDeviceSize va; }; std::vector callbacks; + std::vector pending; // the retired views at kListsPending, by address std::size_t retired_views = 0; { std::lock_guard lock(mutex_); @@ -539,7 +549,6 @@ class GeometryViews { // outer_ leaves it; the live views it held take its place below, once the retired ones are out of keys_. std::vector inner; std::vector> vacated; - std::uint64_t lists = 0; for (std::size_t i = 0; i < ids.size(); ++i) { const std::size_t id = ids[i]; const View& v = views_[id]; @@ -557,11 +566,13 @@ class GeometryViews { it = contained_.erase(it); } // A range inside it that the release did not touch is still the title's, and a command list recorded - // before now that names it may be executed after: the view's memory also waits until no such list is - // left, as a retired title window does (src/command_list_epochs.h). + // while it is still answered may name it and be executed after: the view's memory also waits until no + // such list is left (src/command_list_epochs.h). It is answered until fast_ forgets it below and the + // aliases and heap slots that hold its address are dropped (on_retire, after the lock), so the epoch is + // taken after on_retire. if (untouched && retire_ticket == kAfterExecutes) { - if (!lists) lists = leonida::command_list_epochs::advance(); - retired_[first_retired + i].lists = lists; + retired_[first_retired + i].lists = kListsPending; + pending.push_back(v.va); } if (const auto it = outer_.find(v.source); it != outer_.end() && it->second.second == id) { vacated.emplace_back(v.source, v.source + v.size); @@ -605,6 +616,16 @@ class GeometryViews { retired_count_.store(retired_.size(), std::memory_order_release); } for (const auto& item : callbacks) on_retire(item.source, item.size, item.va); + // Nothing answers the ranges inside those views now, so a list whose recording begins from here on cannot name + // them. reap() may have compacted retired_ meanwhile, but it cannot have freed these entries, which execute_end + // leaves unstamped while they are pending: their addresses find them. + if (!pending.empty()) { + const std::uint64_t lists = leonida::command_list_epochs::advance(); + std::lock_guard lock(mutex_); + for (auto& r : retired_) + if (r.lists == kListsPending && std::find(pending.begin(), pending.end(), r.va) != pending.end()) + r.lists = lists; + } return retired_views; } @@ -680,8 +701,11 @@ class GeometryViews { }(); // One pass over the tiles: each written tile is read once and copied into every view over it, not view by // view (speed-16: up to 63 written tiles under 918 views a refresh, ~58,000 per-view lookups and copies, - // 30-80 ms). A view over a tile that cannot be guarded yet (retry) is left as it is this time; a view not - // filled yet is filled whole, once. + // 30-80 ms). A view over a tile that cannot be guarded yet (retry) is not filled whole this time, as that + // would read the tile; a view not filled yet is filled whole, once. A filled view over such a tile still takes + // its other written tiles: update() has taken their versions, so a tile skipped now would not be copied again + // until it is written again, and every range inside the view would keep the old bytes. The retry tile itself + // is not among the written ones, and is copied once it can be guarded. marks_.assign(views_.size(), 0); written_vas_.clear(); // The pass over the watched tiles makes a VirtualQuery and a VirtualProtect for each written one (tens of @@ -724,7 +748,7 @@ class GeometryViews { View& v = views_[id]; if (!v.alive) continue; std::uint8_t& mark = marks_[id]; - if (mark & (kPinned | kWhole)) continue; + if (mark & kWhole) continue; if (!(mark & kTouched)) { mark |= kTouched; ++changed_views; @@ -743,7 +767,7 @@ class GeometryViews { std::memcpy(v.dst + (from - v.source), read + (from - va), to - from); } else if (copy(v.dst + (from - v.source), reinterpret_cast(from), to - from) != GeometryCopy::copied) { - mark |= kWhole; // filled whole below, which zeroes it if that fails too + mark |= kWhole; // filled whole below (unless pinned), which zeroes it if that fails too continue; } uploaded_ += to - from; @@ -804,10 +828,19 @@ class GeometryViews { void report() const { if (!effective_cap()) return; std::lock_guard lock(mutex_); + // A command list kept for long (an idle one, or a bundle) holds these, and keeps execute_end walking retired_. + std::size_t waiting = 0; + std::uint64_t waiting_bytes = 0; + for (const auto& r : retired_) + if (r.ticket == kAfterExecutes && r.lists) { + ++waiting; + waiting_bytes += r.size; + } std::fprintf(stderr, "[rt] geometry buffers: seen %zu, backed %zu (%llu bytes), populated %llu, cap %llu MiB, " "cap refused %llu, retried ok %llu, evicted %llu (reaped %llu, retired %zu, copied at " "retirement %llu), allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, " - "reserved %llu bytes (%s), ranges inside a live view %zu (%llu so far)\n", + "reserved %llu bytes (%s), ranges inside a live view %zu (%llu so far), retired views " + "waiting for older command lists %zu (%llu bytes)\n", keys_.size() + refused_.size() + contained_.size(), live_views_, (unsigned long long)bytes_, (unsigned long long)ready_, (unsigned long long)(effective_cap() >> 20), (unsigned long long)cap_refusals_, @@ -817,7 +850,7 @@ class GeometryViews { (unsigned long long)uploads_, (unsigned long long)uploaded_, tiles_.size(), static_cast(pool_.reserved()), pool_.system_memory() ? "system memory" : "device-local", contained_.size(), - (unsigned long long)contained_hits_); + (unsigned long long)contained_hits_, waiting, (unsigned long long)waiting_bytes); std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes (%llu views by " "their written tiles only); %.3f s checking and refreshing sources, %llu bytes cleared\n", static_cast(dirty_refreshes_), static_cast(submissions_), diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 748d6144a5..47b6ac4a33 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -4099,8 +4099,9 @@ struct DeviceState { // or a build reaches the whole range by one address. A GPU-written structure (a BVH destination or its scratch) // keeps the GPU's writes in the copy: that is the only place the structure is read from afterwards, so the copy // is the structure. It is made even when a shorter range already maps the start: spreading a window's address over - // bytes it does not cover would be a lie. 0 when geometry copies are off (LEONIDA_GEOMETRY_MB), their cap refuses - // it, or the range is not the title's memory. + // bytes it does not cover would be a lie. It is not answered from inside a larger copy either (resolve's + // `contain`): a release elsewhere in that copy would retire the structure with it. 0 when geometry copies are off + // (LEONIDA_GEOMETRY_MB), their cap refuses it, or the range is not the title's memory. std::uint64_t copy_title_range(std::uint64_t va, std::uint64_t bytes) { const std::uint64_t span = std::max(bytes, 1); auto& aliases = leonida::title_va_aliases(); @@ -4109,7 +4110,7 @@ struct DeviceState { const auto cpu = leonida::title_gpu_views::to_host_view(static_cast(va), static_cast(span)); if (context->knows_buffer_va(cpu, span)) return 0; - const std::uint64_t copy = geometry.resolve(*this, cpu, span, copy_geometry); + const std::uint64_t copy = geometry.resolve(*this, cpu, span, copy_geometry, false); if (!copy) return 0; std::lock_guard lock(title_window_mutex); aliases.add(va, span, copy); diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp index d9fb6c658c..ce4c3917ca 100644 --- a/runtime/test/geometry_views_test.cpp +++ b/runtime/test/geometry_views_test.cpp @@ -20,10 +20,14 @@ // 14. LEONIDA_GEOMETRY_HOST picks a system-memory type (write-back for 1, write-combined for 2), never the BAR; // 15. a retired view is copied once more from its pages when they are readable, not when they are not; // 16. a full release queue joins touching ranges before it collapses to one covering range; -// 17. a range inside a live view is answered from that view (its address plus the offset), not copied again; it is -// refreshed with that view and leaves with it, and a view it was inside before keeps answering after the outer -// one goes; a retired view with a range inside it the release did not touch also waits for the command lists -// recorded before (LEONIDA_GEOMETRY_CONTAINED=0, a copy of its own as before, fails 17). +// 17. a range inside a live view is answered from that view (its address plus the offset), not copied again, unless +// the caller asks for a copy of its own; it is refreshed with that view and leaves with it, and a view it was +// inside before keeps answering after the outer one goes; a retired view with a range inside it the release did +// not touch also waits for the command lists whose recording began before that range stopped being answered, +// on_retire included (LEONIDA_GEOMETRY_CONTAINED=0, a copy of its own as before, fails 17); +// 18. a filled view over a tile that cannot be guarded yet (a file read into it in flight) still takes the writes to +// its other tiles, and so does a range inside it (with whole views such a view waits for the read to end and is +// then copied whole, so its first check fails). #include #include @@ -144,6 +148,10 @@ void title_write(std::uintptr_t at, std::uint8_t value) { *reinterpret_cast(at) = value; } +// kernel_writes::begin_write pins a range only once the layer has an opener; the test's pages are opened by +// title_write already. +void open_nothing(std::uintptr_t, std::uintptr_t) {} + } // namespace int main() { @@ -710,10 +718,78 @@ int main() { nest.execute_end(next, [] { return std::uint64_t(4); }); check(nest.reap(device, 3) == 0 && nest.reap(device, 4) == 1 && nest.retired_count() == 0, "once that list is gone, the outer view waits only for the next replay's submissions"); + + // The range inside answers until on_retire has dropped what still names it (aliases, heap slots), after the + // views' lock is let go: a list whose recording begins in on_retire can still take its address, so the view + // waits for that list too. + const auto d = a + 2 * kTile; + const std::uint64_t outer_d = nest.resolve(device, d, 2 * kTile, copy); + check(outer_d != 0 && nest.resolve(device, d + 4096, kTile, copy) == outer_d + 4096, + "a fourth outer view with a range inside it"); + std::unique_ptr late; + nest.retire_range(d + 100 * 1024, d + 104 * 1024, rt::d3d12::GeometryViews::kAfterExecutes, + [&](std::uintptr_t, std::size_t, VkDeviceSize) { + if (!late) late = std::make_unique(); + }); + const std::uint64_t after = nest.execute_begin(); + nest.execute_end(after, [] { return std::uint64_t(5); }); + check(late && nest.reap(device, 5) == 0 && nest.retired_count() == 1, + "a list whose recording began in on_retire, while the range inside still answered, holds the view"); + late.reset(); + const std::uint64_t last_replay = nest.execute_begin(); + nest.execute_end(last_replay, [] { return std::uint64_t(6); }); + check(nest.reap(device, 6) == 1 && nest.retired_count() == 0, "once that list is gone, the view is freed"); + + // A caller that asks for a copy of its own (a structure the GPU writes, copy_title_range) gets one, even + // inside a live view: a release elsewhere in that view must not take the structure with it. + const std::uint64_t holder = nest.resolve(device, d, 2 * kTile, copy); + const std::uint64_t own = nest.resolve(device, d + 4096, kTile, copy, false); + check(holder != 0 && own != 0 && own != holder + 4096 && nest.find(d + 4096, kTile) == own && + nest.retire_range(d + 100 * 1024, d + 104 * 1024, 7) == 1 && nest.find(d + 4096, kTile) == own, + "asked for a copy of its own, a range inside a live view gets one, which outlives that view"); nest.release(device); VirtualFree(nest_title, 0, MEM_RELEASE); } + // 18. V = (P, 128 KiB) over tiles 0 and 1, and K = (P + 4 KiB, 4 KiB) inside tile 0. The title writes K and tile + // 1, and a file read into tile 1 is in flight at the next refresh, so tile 1 cannot be guarded yet. The refresh + // takes tile 0's version all the same, so a write to it that is not copied then is never copied: tile 0 goes to + // V (and K) now, and tile 1 once the read has ended. + { + auto* pin_title = + static_cast(VirtualAlloc(nullptr, 2 * kTile, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!pin_title) return 1; + for (std::size_t i = 0; i < 2 * kTile; ++i) pin_title[i] = std::uint8_t((i * 5) ^ 0x0f); + const auto p = reinterpret_cast(pin_title); + rt::d3d12::GeometryViews pinned; + const auto host_of = [&](std::uint64_t at) -> const std::uint8_t* { + std::uint64_t host = 0, room = 0; + return at && pinned.lookup(device.arena.address + at, host, room) + ? reinterpret_cast(host) + : nullptr; + }; + const std::uint64_t whole = pinned.resolve(device, p, 2 * kTile, copy); + const std::uint64_t part = pinned.resolve(device, p + 4096, 4096, copy); + pinned.refresh(copy); + const std::uint8_t before = pin_title[kTile + 10]; + leonida::kernel_writes::set_opener(open_nothing); + title_write(p + kTile + 10, 0x11); + title_write(p + 4096 + 5, 0x5a); + const std::uint64_t pin = leonida::kernel_writes::begin_write(pin_title + kTile + 100, 16, nullptr); + pinned.refresh(copy); + check(pin != 0 && host_of(whole) && host_of(part) && host_of(whole)[4096 + 5] == 0x5a && + host_of(part)[5] == 0x5a && host_of(whole)[kTile + 10] == before, + "while a file read into tile 1 is in flight, the write to tile 0 reaches V and K; tile 1 waits"); + leonida::kernel_writes::end_write(pin, false); + pinned.refresh(copy); + check(host_of(whole) && host_of(part) && host_of(whole)[kTile + 10] == 0x11 && + host_of(whole)[4096 + 5] == 0x5a && host_of(part)[5] == 0x5a, + "once the read has ended, tile 1 reaches V too, and tile 0 keeps the write"); + leonida::kernel_writes::set_opener(nullptr); + pinned.release(device); + VirtualFree(pin_title, 0, MEM_RELEASE); + } + std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } From 46f3cddb2c42585d1beacabbde35664c05a358f0 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:00:17 +0100 Subject: [PATCH 41/49] vulkan: after a device loss, released objects are destroyed at once (RT-DEVICE-LOST-DRAIN) Once the device is lost, completed_retire_ticket() answers 0 and acquire() returns before its drain, so nothing drained the context's deferred deletion queue again until the context went away. Every image, buffer, device memory, view and image-memory range the title released after the loss stayed allocated, and the queue's ring kept doubling. defer_destroy now destroys the object at once when the device is lost, and the first such call also destroys everything queued before the loss. A lost device runs nothing more, and vkDestroy* and vkFreeMemory are valid on it. Bindless slots still wait in the queue: their release takes the device's descriptor lock, which release() holds when it defers one, and the set gives out no more slots than it has, so those entries stay bounded. vk_deferred_destroy_lost_test defers 500 buffers, marks the context lost and defers 500 more: all 1000 are destroyed while the context lives, none twice at teardown, and the two bindless slots are released once, at teardown. Before this change it stopped with none of the 1000 destroyed. --- runtime/CMakeLists.txt | 17 +++ runtime/src/vulkan_backend.h | 118 ++++++++++++------ .../test/vk_deferred_destroy_lost_test.cpp | 104 +++++++++++++++ 3 files changed, 199 insertions(+), 40 deletions(-) create mode 100644 runtime/test/vk_deferred_destroy_lost_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..8c14cb2d47 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2280,6 +2280,23 @@ if(TARGET Vulkan::Headers) add_test(NAME vk_fence_lost_by_counter COMMAND vk_fence_lost_by_counter_test) set_tests_properties(vk_fence_lost_by_counter PROPERTIES SKIP_RETURN_CODE 77) endif() + # The deferred deletion queue after a device loss: what was queued and what is released later is destroyed while + # the context lives, not at its teardown (driver vkDestroyBuffer interposed). + add_executable(vk_deferred_destroy_lost_test test/vk_deferred_destroy_lost_test.cpp) + target_link_libraries(vk_deferred_destroy_lost_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_deferred_destroy_lost_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + else() + find_package(Threads REQUIRED) + target_link_libraries(vk_deferred_destroy_lost_test PRIVATE Threads::Threads) + endif() + if(MSVC) + target_compile_options(vk_deferred_destroy_lost_test PRIVATE /W4 /permissive- /utf-8) + endif() + if(BUILD_TESTING) + add_test(NAME vk_deferred_destroy_lost COMMAND vk_deferred_destroy_lost_test) + set_tests_properties(vk_deferred_destroy_lost PROPERTIES SKIP_RETURN_CODE 77) + endif() # The bindless set under view churn (bounded table, spare generations) and failed allocations (host table, in-place # rewrite, a degraded flush instead of a refused submission). add_executable(vk_bindless_grow_test test/vk_bindless_grow_test.cpp) diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 858ba46bec..470251eeb7 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -529,45 +529,73 @@ class DeferredDeletionQueue { } } - for (const Item& item : to_destroy) { - switch (item.kind) { - case Kind::bindless_slot: - if (release_fn) { - release_fn(release_user, static_cast(item.handle >> 32), - static_cast(item.handle & 0xFFFFFFFFu)); + for (const Item& item : to_destroy) destroy(item, device, vk, release_fn, release_user); + } + + // After a device loss: destroys every item now, whatever its ticket, except the bindless slots, which stay queued + // in their order. Releasing a slot takes the device's descriptor lock, which a caller of this may hold. + void drain_lost(VkDevice device, const VulkanDeviceFunctions& vk) { + std::vector to_destroy; + { + std::lock_guard lock(mutex_); + const std::size_t mask = pending_.size() - 1; + std::size_t kept = 0; + for (std::size_t i = 0; i < count_; ++i) { + const Item& item = pending_[(head_ + i) & mask]; + if (item.kind == Kind::bindless_slot) { + // Kept items move towards the front only, so this never overwrites one not yet read. + pending_[(head_ + kept) & mask] = item; + ++kept; + } else { + to_destroy.push_back(item); } - break; - case Kind::image_view: - vk.vkDestroyImageView(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::image: - vk.vkDestroyImage(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::pooled_title_image: - delete reinterpret_cast(item.handle); - break; - case Kind::sparse_resource: - // Releases the resource and its page backing together after outstanding submissions. - delete reinterpret_cast*>(item.handle); - break; - case Kind::buffer: - vk.vkDestroyBuffer(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::device_memory: - vk.vkFreeMemory(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::image_memory: - delete reinterpret_cast(item.handle); - break; - case Kind::acceleration_structure: - if (vk.vkDestroyAccelerationStructureKHR) - vk.vkDestroyAccelerationStructureKHR( - device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::framebuffer: - vk.vkDestroyFramebuffer(device, reinterpret_cast(item.handle), nullptr); - break; } + count_ = kept; + tail_ = (head_ + kept) & mask; + } + for (const Item& item : to_destroy) destroy(item, device, vk, nullptr, nullptr); + } + + // Destroys one item now. A bindless slot is handed to release_fn. + static void destroy(const Item& item, VkDevice device, const VulkanDeviceFunctions& vk, + BindlessReleaseFn release_fn, void* release_user) { + switch (item.kind) { + case Kind::bindless_slot: + if (release_fn) { + release_fn(release_user, static_cast(item.handle >> 32), + static_cast(item.handle & 0xFFFFFFFFu)); + } + break; + case Kind::image_view: + vk.vkDestroyImageView(device, reinterpret_cast(item.handle), nullptr); + break; + case Kind::image: + vk.vkDestroyImage(device, reinterpret_cast(item.handle), nullptr); + break; + case Kind::pooled_title_image: + delete reinterpret_cast(item.handle); + break; + case Kind::sparse_resource: + // Releases the resource and its page backing together after outstanding submissions. + delete reinterpret_cast*>(item.handle); + break; + case Kind::buffer: + vk.vkDestroyBuffer(device, reinterpret_cast(item.handle), nullptr); + break; + case Kind::device_memory: + vk.vkFreeMemory(device, reinterpret_cast(item.handle), nullptr); + break; + case Kind::image_memory: + delete reinterpret_cast(item.handle); + break; + case Kind::acceleration_structure: + if (vk.vkDestroyAccelerationStructureKHR) + vk.vkDestroyAccelerationStructureKHR(device, reinterpret_cast(item.handle), + nullptr); + break; + case Kind::framebuffer: + vk.vkDestroyFramebuffer(device, reinterpret_cast(item.handle), nullptr); + break; } } @@ -1971,13 +1999,22 @@ class VulkanContext { void defer_destroy(DeferredDeletionQueue::Kind kind, VkHandle handle) { const auto raw = static_cast(reinterpret_cast(handle)); if (!raw) return; - std::lock_guard lock(submit_mutex_); - const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1; - deletion_queue_.push(safe_ticket, kind, raw); + defer_destroy(kind, raw); } void defer_destroy(DeferredDeletionQueue::Kind kind, std::uint64_t raw_handle) { if (!raw_handle && kind != DeferredDeletionQueue::Kind::bindless_slot) return; + // Once the device is lost no retire ticket completes again (completed_retire_ticket() answers 0 and acquire() + // returns before its drain), so a queued object would stay until the context goes and the queue would grow + // with everything the title releases. The lost device runs nothing more, and vkDestroy* and vkFreeMemory are + // valid on it: the object goes now, and the first time also everything queued before the loss. A bindless + // slot still waits: its release takes the device's descriptor lock, which the caller may hold (release() in + // d3d12_vulkan_device.cpp), and the set never hands out more slots than it has, so those entries stay bounded. + if (is_device_lost() && kind != DeferredDeletionQueue::Kind::bindless_slot) { + if (!lost_queue_drained_.exchange(true, std::memory_order_acq_rel)) deletion_queue_.drain_lost(device_, vk); + DeferredDeletionQueue::destroy({0, raw_handle, kind}, device_, vk, nullptr, nullptr); + return; + } std::lock_guard lock(submit_mutex_); const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1; deletion_queue_.push(safe_ticket, kind, raw_handle); @@ -2372,6 +2409,7 @@ class VulkanContext { RetireTickets retire_tickets_; std::atomic submitted_ticket_{0}; DeferredDeletionQueue deletion_queue_; + std::atomic lost_queue_drained_{false}; // defer_destroy emptied the queue once after the loss std::unique_ptr device_fault_; std::jthread progress_watch_; std::unique_ptr fence_dispatcher_; diff --git a/runtime/test/vk_deferred_destroy_lost_test.cpp b/runtime/test/vk_deferred_destroy_lost_test.cpp new file mode 100644 index 0000000000..6f57410be3 --- /dev/null +++ b/runtime/test/vk_deferred_destroy_lost_test.cpp @@ -0,0 +1,104 @@ +// The context's deferred deletion queue after a device loss (runtime/src/vulkan_backend.h, +// VulkanContext::defer_destroy). Once the device is lost no retire ticket completes again and acquire() returns before +// its drain, so an object queued then would stay until the context goes, and the queue would grow with every object +// the title releases. +// 1. Buffers deferred before the loss wait for a submission that never comes. +// 2. After the loss, the next deferred destruction frees them and every later one is freed at once: all 1000 buffers +// are gone while the context lives, and the context's own teardown destroys none of them twice. +// 3. A bindless slot, queued before the loss or after it, still waits in the queue (its release takes the device's +// descriptor lock, which the caller holds) and is released once, at teardown. +// vkDestroyBuffer is interposed on a real device's table to count the destructions. Skips with exit code 77 when no +// Vulkan 1.3 device is available; LEONIDA_VK_VALIDATION=1 runs it under the validation layer. No game data. +#include "vk_test_device.h" +#include "../src/vulkan_backend.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); std::_Exit(1); } \ +} while (0) + +namespace { + +namespace driver { +PFN_vkGetDeviceProcAddr real_get_device = nullptr; +PFN_vkDestroyBuffer real_destroy_buffer = nullptr; + +std::atomic destroyed_buffers{0}; + +VKAPI_ATTR void VKAPI_CALL destroy_buffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks* allocator) { + if (buffer) destroyed_buffers.fetch_add(1, std::memory_order_relaxed); + real_destroy_buffer(device, buffer, allocator); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { + if (std::string_view(name) == "vkDestroyBuffer") return reinterpret_cast(destroy_buffer); + return real_get_device(device, name); +} + +void install(PFN_vkGetDeviceProcAddr device_proc, VkDevice device) { + real_get_device = device_proc; + real_destroy_buffer = reinterpret_cast(device_proc(device, "vkDestroyBuffer")); +} +} // namespace driver + +} // namespace + +int main() { + using namespace leonida; + + vktest::Device d; + if (!d.create(false)) { + std::fprintf(stderr, "vk_deferred_destroy_lost_test: no Vulkan 1.3 device, skipped\n"); + return 77; + } + driver::install(d.device_proc, d.device); + const auto create_buffer = d.fn("vkCreateBuffer"); + EXPECT(create_buffer); + const auto make_buffer = [&] { + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = 256; + info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + VkBuffer buffer = VK_NULL_HANDLE; + EXPECT(create_buffer(d.device, &info, nullptr, &buffer) == VK_SUCCESS && buffer); + return buffer; + }; + + constexpr unsigned before_loss = 500; + constexpr unsigned total = 1000; + unsigned released_slots = 0; + { + VulkanContext context(driver::get_device, d.device, true); + EXPECT(context.loaded()); + context.set_bindless_release( + [](void* user, std::uint32_t, std::uint32_t) { ++*static_cast(user); }, &released_slots); + + // 1, with a bindless slot among the buffers + for (unsigned i = 0; i < before_loss; ++i) { + context.defer_destroy(DeferredDeletionQueue::Kind::buffer, make_buffer()); + if (i == before_loss / 2) + context.defer_destroy(DeferredDeletionQueue::Kind::bindless_slot, (std::uint64_t(1) << 32) | 3u); + } + EXPECT(driver::destroyed_buffers.load() == 0); + + // 2 + context.mark_device_lost("the test marks the device lost"); + for (unsigned i = before_loss; i < total; ++i) + context.defer_destroy(DeferredDeletionQueue::Kind::buffer, make_buffer()); + EXPECT(driver::destroyed_buffers.load() == total); + + // 3 + context.defer_destroy(DeferredDeletionQueue::Kind::bindless_slot, (std::uint64_t(1) << 32) | 7u); + EXPECT(released_slots == 0); + } + EXPECT(driver::destroyed_buffers.load() == total); + EXPECT(released_slots == 2); + EXPECT(d.validation_errors() == 0); + std::puts("vk_deferred_destroy_lost: ok"); + return 0; +} From 4b584bd5105a35f34c7d7856a5459b895f382c1f Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:01:49 +0100 Subject: [PATCH 42/49] leonida-hle: DirectStorage workers reuse their request buffers (RS-DSTORAGE-SCRATCH) Every compressed request allocated zero-filled buffers and freed them at the end: the source read from the file, the zlib output that BCPack then unpacks (intermediate_size), and the destination's bytes when its physical pages are not one allocation's in order. Blocks of 1 MiB and more come from the host's virtual memory, fresh and zero-filled each time, so streaming paid an allocation, page faults and a free per request. Each worker now keeps these buffers in its own frame (Scratch) and passes them to execute(). A buffer grows only when a request needs more than it holds. The source is read over what an earlier request left (read_into writes all of it or fails), the zlib output is used only as far as inflate wrote it, and the page buffer is zeroed as a new one was, so the bytes written are the same as before. Between requests a worker keeps at most 16 MiB, giving up its largest buffers first. staging_bytes now counts every buffer a request holds: besides the compressed source read from a file, the zlib output of a zlib+BCPack request and the destination's bytes of a request to pages (the source's for a raw copy). LEONIDA_DSTORAGE_STAGING_MB bounds all of them now. compressed_requests_reuse_the_workers_buffers counts, under a test-only counting allocator, the blocks of the three buffers' sizes over many requests: one per request before (72 of each in 72 requests on 16 workers), at most one per worker now. Two smaller tests check the staging accounting and the 16 MiB bound. --- .../leonida-hle/src/modules/dstorage.rs | 377 ++++++++++++++++-- 1 file changed, 334 insertions(+), 43 deletions(-) diff --git a/d3d12/crates/leonida-hle/src/modules/dstorage.rs b/d3d12/crates/leonida-hle/src/modules/dstorage.rs index 202d94e0bb..d43f4530d3 100644 --- a/d3d12/crates/leonida-hle/src/modules/dstorage.rs +++ b/d3d12/crates/leonida-hle/src/modules/dstorage.rs @@ -12,16 +12,16 @@ //! console's hardware runs them: in parallel, started in queue order, //! queues served by weighted round robin over their priorities (about 10x //! per level, counted in bytes), with at most the staging buffer's worth of -//! compressed source in flight. Each request reads its source (a file or -//! memory), inflates zlib data and/or unpacks BCPack data, and writes the -//! destination (an address, or physical pages). Completion is what stays -//! in order: a status entry is written once every request enqueued before -//! it on its queue has finished, with the first failure (in queue order) -//! since the previous status entry, or success. +//! buffered bytes in flight ([`staging_bytes`]). Each request reads its +//! source (a file or memory), inflates zlib data and/or unpacks BCPack data, +//! and writes the destination (an address, or physical pages), through +//! buffers its worker keeps from one request to the next ([`Scratch`]). +//! Completion is what stays in order: a status entry is written once every +//! request enqueued before it on its queue has finished, with the first +//! failure (in queue order) since the previous status entry, or success. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::ffi::{CStr, c_char, c_void}; use std::os::windows::fs::FileExt; @@ -229,7 +229,9 @@ extern "system" fn create_queue( /// The title asks for 32 MiB and stops if this fails. Give PC worker threads /// enough staging headroom (default 256 MiB) so multi-MB RPF chunks don't -/// starve the remaining cores. +/// starve the remaining cores. This is the largest bound on this module's +/// RAM: it caps the buffers of the requests running ([`staging_bytes`]); what +/// the workers keep between requests is apart from it ([`SCRATCH_KEPT`] each). extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT { static FLOOR_MB: std::sync::OnceLock = std::sync::OnceLock::new(); let floor = *FLOOR_MB.get_or_init(|| { @@ -776,6 +778,8 @@ pub(crate) mod stream_log { /// A worker: runs the next read of the most deserving queue. fn work(scheduler: &'static Scheduler) { + // This worker's buffers, in its own frame for as long as it runs. + let mut scratch = Scratch::default(); let mut lanes = scheduler.lock(); loop { let Some(job) = lanes.start() else { @@ -786,7 +790,8 @@ fn work(scheduler: &'static Scheduler) { let started = std::time::Instant::now(); let traced = Traced::start(&job); let reading = leonida_gpu::timeline::span("streaming: a request"); - let result = execute(&job.request); + let result = execute(&job.request, &mut scratch); + scratch.trim(); reading.end(); walls_request(&job.request, &result, started); stream_log::request(&job, started, &result); @@ -803,6 +808,58 @@ fn work(scheduler: &'static Scheduler) { } } +/// A worker's buffers between a request's source and its destination: a +/// compressed source read from its file, the zlib output that BCPack then +/// unpacks, and the bytes of a destination in pages that are not one +/// allocation's in order. They are kept from one request to the next: new +/// ones for every request cost an allocation each, and blocks of 1 MiB and +/// more come from the host's virtual memory, fresh and zero-filled each time +/// and given back at the end. +#[derive(Default)] +struct Scratch { + source: Vec, + packed: Vec, + pages: Vec, +} + +/// What a worker keeps of its buffers between requests. A request that needs +/// more has them for its own time, so at most this times the workers stays +/// allocated while nothing runs. +const SCRATCH_KEPT: usize = 16 << 20; + +impl Scratch { + /// Gives up buffers, largest first, until those kept hold at most + /// [`SCRATCH_KEPT`]. + fn trim(&mut self) { + let mut buffers = [&mut self.source, &mut self.packed, &mut self.pages]; + buffers.sort_unstable_by_key(|b| std::cmp::Reverse(b.capacity())); + let mut kept: usize = buffers.iter().map(|b| b.capacity()).sum(); + for buffer in buffers { + if kept <= SCRATCH_KEPT { + break; + } + kept -= buffer.capacity(); + *buffer = Vec::new(); + } + } +} + +/// `len` bytes of `buffer` for a request to overwrite. The buffer grows only +/// past what earlier requests left in it, so a reused one is neither +/// allocated nor cleared again; what those requests wrote stays in it, and +/// callers use only the bytes they write. One that is too small is replaced +/// rather than grown, since nothing in it needs copying. +fn room(buffer: &mut Vec, len: usize) -> &mut [u8] { + if buffer.capacity() < len { + // The old one goes first, so that both are never held at once. + *buffer = Vec::new(); + *buffer = vec![0; len]; + } else if buffer.len() < len { + buffer.resize(len, 0); + } + &mut buffer[..len] +} + impl Lanes { /// Counts a finished request; every 5 s a debug line sums them up. fn count(&mut self, job: &Job, started: std::time::Instant) { @@ -967,15 +1024,32 @@ impl Lane { } /// Staging bytes a request holds while it runs: what it buffers between -/// the file and the destination. Raw reads go straight to their -/// destination, memory sources need none (as on the console). +/// the source and the destination. That is a compressed source read from a +/// file, the zlib output that BCPack then unpacks, and for physical pages +/// the destination's bytes, which go through a buffer when the pages are +/// not one allocation's in order (rarely, but nothing tells beforehand). +/// Raw reads go straight to their destination, and memory sources are read +/// where they are (as on the console). fn staging_bytes(request: &Request) -> u64 { - let buffered = request.options & (ZLIB | BCPACK | PAGE_DESTINATION) != 0; - if buffered && request.options & MEMORY_SOURCE == 0 { - u64::from(request.source_size) + let options = request.options; + let compressed = options & (ZLIB | BCPACK) != 0; + let source = if compressed && options & MEMORY_SOURCE == 0 { + request.source_size } else { 0 - } + }; + let packed = if options & ZLIB != 0 && options & BCPACK != 0 { + request.intermediate_size + } else { + 0 + }; + // What `execute` writes: the decompressed bytes, or a raw copy's source. + let pages = match (options & PAGE_DESTINATION != 0, compressed) { + (false, _) => 0, + (true, true) => request.destination_size, + (true, false) => request.source_size, + }; + u64::from(source) + u64::from(packed) + u64::from(pages) } /// Ends a queue: what was not started is dropped, and this waits for the @@ -1018,7 +1092,8 @@ struct Request { source: *const c_void, offset: u64, source_size: u32, - /// Compressed size between two decompression stages; unused here. + /// Compressed size between two decompression stages: room for the zlib + /// output that BCPack then unpacks. intermediate_size: u32, /// Matched by cancellation; the title leaves it 0. tag: u64, @@ -1375,8 +1450,10 @@ extern "system" fn close(this: QueueRef) { close_lane(unsafe { &*this }.state.id); } -/// Reads, inflates and/or unpacks, and writes one request. -fn execute(request: &Request) -> Result<(), HRESULT> { +/// Reads, inflates and/or unpacks, and writes one request, through the +/// worker's buffers. +fn execute(request: &Request, scratch: &mut Scratch) -> Result<(), HRESULT> { + let Scratch { source: read, packed, pages } = scratch; let options = request.options; let fail = |hr: HRESULT, why: &str| { tracing::warn!( @@ -1404,7 +1481,7 @@ fn execute(request: &Request) -> Result<(), HRESULT> { if options & (ZLIB | BCPACK | MEMORY_SOURCE) == ZLIB && let Some(movie) = glyph_movie(request) { - return into_destination(request, size, |out| { + return into_destination(request, size, pages, |out| { let n = movie.len().min(out.len()); out[..n].copy_from_slice(&movie[..n]); out[n..].fill(0); @@ -1416,25 +1493,24 @@ fn execute(request: &Request) -> Result<(), HRESULT> { return Err(fail(E_INVALIDARG, "source larger than destination")); } let size = request.source_size as usize; - return into_destination(request, size, |out| read_into(request, out).map(|()| size)) + return into_destination(request, size, pages, |out| read_into(request, out).map(|()| size)) .map_err(|hr| fail(hr, "copying")); } let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; - let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; + let source = read_source(request, read).map_err(|hr| fail(hr, "reading the source"))?; // The console's order: zlib first, then BCPack. let source = if bc != 0 && options & ZLIB != 0 { - let mut packed = vec![0; request.intermediate_size as usize]; - let n = inflate(&source, &mut packed).map_err(|hr| fail(hr, "zlib"))?; - packed.truncate(n); - Cow::Owned(packed) + let out = room(packed, request.intermediate_size as usize); + let n = inflate(source, out).map_err(|hr| fail(hr, "zlib"))?; + &packed[..n] } else { source }; - into_destination(request, size, |out| match tables { - Some(tables) => bcpack::decode(bc, &source, out, tables) + into_destination(request, size, pages, |out| match tables { + Some(tables) => bcpack::decode(bc, source, out, tables) .map(|()| out.len()) .map_err(|e| fail(INVALID_DATA, &e.to_string())), - None => inflate(&source, out).map_err(|hr| fail(hr, "zlib")), + None => inflate(source, out).map_err(|hr| fail(hr, "zlib")), })?; tracing::trace!( options = format_args!("{options:#x}"), @@ -1539,18 +1615,19 @@ fn load_bcpack_tables() -> Result { Tables::parse(&bytes).map_err(|e| e.to_string()) } -/// A compressed request's source: borrowed from memory, or read from the -/// file. -fn read_source(request: &Request) -> Result, HRESULT> { +/// A compressed request's source: in memory where it is, or read from the +/// file into `buffer`. +fn read_source<'a>(request: &Request, buffer: &'a mut Vec) -> Result<&'a [u8], HRESULT> { let size = request.source_size as usize; if request.options & MEMORY_SOURCE != 0 { // SAFETY: the title's source holds `size` bytes until completion. - let bytes = unsafe { std::slice::from_raw_parts(request.source.cast(), size) }; - return Ok(Cow::Borrowed(bytes)); + return Ok(unsafe { std::slice::from_raw_parts(request.source.cast(), size) }); } - let mut bytes = vec![0; size]; - read_into(request, &mut bytes)?; - Ok(Cow::Owned(bytes)) + // `read_into` writes all of it or fails, so nothing an earlier request + // left in the buffer shows. + let bytes = room(buffer, size); + read_into(request, bytes)?; + Ok(bytes) } /// Nanoseconds workers spent reading files, for the debug summary. @@ -1611,10 +1688,11 @@ fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { /// many it produced. GPU-visible destinations are host memory like the /// rest (GPU address = CPU address), so an address is written in place; /// physical pages are too when they are consecutive pages of one -/// allocation, and otherwise go through a buffer. +/// allocation, and otherwise go through `buffer`. fn into_destination( request: &Request, len: usize, + buffer: &mut Vec, mut fill: impl FnMut(&mut [u8]) -> Result, ) -> Result<(), HRESULT> { if request.options & PAGE_DESTINATION == 0 { @@ -1644,7 +1722,7 @@ fn into_destination( // (Said aloud: by the title's protocol a submitted request's list stays // as it is.) for _ in 0..3 { - into_pages(&pages, offset, len, &mut fill)?; + into_pages(&pages, offset, len, buffer, &mut fill)?; let now = read_list(list, offset, len); if now == pages || !super::xmem::pages_known(&now, offset, len) { break; @@ -1662,11 +1740,13 @@ fn into_destination( Ok(()) } -/// Runs `fill` on `len` bytes of `pages`, from `offset` into the first. +/// Runs `fill` on `len` bytes of `pages`, from `offset` into the first; +/// through `buffer` when they are not one allocation's in order. fn into_pages( pages: &[usize], offset: usize, len: usize, + buffer: &mut Vec, mut fill: impl FnMut(&mut [u8]) -> Result, ) -> Result<(), HRESULT> { // Consecutive pages of one allocation (the usual case): written in @@ -1676,8 +1756,11 @@ fn into_pages( super::xmem::pages_written(pages, offset, len); return filled; } - let mut data = vec![0; len]; - let n = fill(&mut data)?; + let data = room(buffer, len); + // Zero as a new buffer would be, so that bytes a decoder leaves alone + // are not an earlier request's. + data.fill(0); + let n = fill(data)?; // A page the title has just made, or a view the host refuses for a moment (commit // or address space short while a load maps many at once), can come right a little // later: tried again before the request fails (`LEONIDA_DSTORAGE_RETRIES`, default 12, @@ -2097,7 +2180,7 @@ mod tests { let len = PAGE + 100; let r = request(PAGE_DESTINATION, at.cast(), len, std::ptr::null(), 0, len); let mut runs = 0; - let written = into_destination(&r, len, |out| { + let written = into_destination(&r, len, &mut Vec::new(), |out| { runs += 1; out.fill(0xa5); // SAFETY: our own list. @@ -2137,7 +2220,7 @@ mod tests { protect(PAGE_READWRITE) }); let r = request(0, at as *mut c_void, plain.len(), file, 0, plain.len()); - assert_eq!(execute(&r), Ok(())); + assert_eq!(execute(&r, &mut Scratch::default()), Ok(())); assert_ne!(opener.join().unwrap(), 0); // SAFETY: as above, all of it readable. assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, plain.len()) }, plain); @@ -2296,6 +2379,55 @@ mod tests { assert!(l.start().is_some()); } + /// What a request holds of the staging buffer is every buffer it fills + /// between the source and the destination. + #[test] + fn staging_counts_every_buffer_a_request_holds() { + let (to, from) = (std::ptr::null_mut(), std::ptr::null()); + // zlib then BCPack from a file: the source and the zlib output. + let mut both = request(ZLIB | 4 << 1, to, 4096, from, 0, 1000); + both.intermediate_size = 3000; + assert_eq!(staging_bytes(&both), 1000 + 3000); + // From memory the source is read where it is; the zlib output is not. + both.options |= MEMORY_SOURCE; + assert_eq!(staging_bytes(&both), 3000); + // Pages of several allocations take the destination's bytes through a + // buffer, so a request to pages holds that much too. + let to_pages = request(ZLIB | PAGE_DESTINATION, to, 4096, from, 0, 1000); + assert_eq!(staging_bytes(&to_pages), 1000 + 4096); + let raw_to_pages = request(PAGE_DESTINATION | MEMORY_SOURCE, to, 1000, from, 0, 1000); + assert_eq!(staging_bytes(&raw_to_pages), 1000); + // zlib alone and raw reads to an address hold what they did. + assert_eq!(staging_bytes(&request(ZLIB, to, 4096, from, 0, 1000)), 1000); + assert_eq!(staging_bytes(&request(0, to, 1000, from, 0, 1000)), 0); + } + + /// A worker's buffers are used again by smaller requests, and it keeps + /// at most `SCRATCH_KEPT` of them between requests, giving up the + /// largest first. + #[test] + fn a_worker_keeps_its_buffers_up_to_a_bound() { + let mut scratch = Scratch::default(); + room(&mut scratch.source, 1 << 20).fill(1); + room(&mut scratch.packed, 2 << 20); + scratch.trim(); + let (source, packed) = (scratch.source.as_ptr(), scratch.packed.as_ptr()); + // Smaller requests: the same buffers, and what they do not write + // stays as it was (nobody reads it). + assert_eq!(room(&mut scratch.source, 100).as_ptr(), source); + assert_eq!(room(&mut scratch.packed, 1 << 20).as_ptr(), packed); + assert_eq!(scratch.source.len(), 1 << 20); + room(&mut scratch.pages, SCRATCH_KEPT); + scratch.trim(); + assert_eq!(scratch.pages.capacity(), 0, "the largest goes"); + assert_eq!((scratch.source.as_ptr(), scratch.packed.as_ptr()), (source, packed)); + // A request larger than the bound has its buffer for its own time. + room(&mut scratch.source, SCRATCH_KEPT + 1); + scratch.trim(); + assert_eq!(scratch.source.capacity(), 0); + assert!(scratch.packed.capacity() >= 2 << 20); + } + #[test] fn a_status_waits_for_every_earlier_read() { let mut l = lanes(STAGING); @@ -2342,6 +2474,165 @@ mod tests { assert_eq!(out, bc4_blocks()); } + /// The test binary's allocator: the system's, counting the blocks of the + /// sizes a test watches (`compressed_requests_reuse_the_workers_buffers`). + /// Not with the features under which leonida-gpu installs an allocator + /// of its own, since a process has one. + #[cfg(not(any(feature = "diagnostics", feature = "mimalloc")))] + mod watched_blocks { + use std::alloc::{GlobalAlloc, Layout, System}; + use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; + + /// The sizes watched (0: none), and how many blocks of each were + /// allocated since. + pub(super) static SIZES: [AtomicUsize; 3] = [const { AtomicUsize::new(0) }; 3]; + pub(super) static BLOCKS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + + fn note(size: usize) { + for (watched, blocks) in SIZES.iter().zip(&BLOCKS) { + if size != 0 && watched.load(Relaxed) == size { + blocks.fetch_add(1, Relaxed); + } + } + } + + struct Counting; + + // SAFETY: every call goes to the system's allocator unchanged; only + // counters are kept beside it. + unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + note(layout.size()); + // SAFETY: the caller's contract, passed on. + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + note(layout.size()); + // SAFETY: the caller's contract, passed on. + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn dealloc(&self, at: *mut u8, layout: Layout) { + // SAFETY: the caller's contract, passed on. + unsafe { System.dealloc(at, layout) } + } + + unsafe fn realloc(&self, at: *mut u8, layout: Layout, size: usize) -> *mut u8 { + note(size); + // SAFETY: the caller's contract, passed on. + unsafe { System.realloc(at, layout, size) } + } + } + + #[global_allocator] + static HEAP: Counting = Counting; + } + + /// Compressed requests run on buffers their worker keeps: the source + /// read from the file, the zlib output that BCPack unpacks, and the + /// bytes of a destination in pages that are not one allocation's in + /// order are each allocated at most once per worker, not once per + /// request (blocks of 1 MiB and more come from the host's virtual + /// memory, new and zero-filled each time). + #[cfg(not(any(feature = "diagnostics", feature = "mimalloc")))] + #[test] + fn compressed_requests_reuse_the_workers_buffers() { + use crate::modules::xmem; + use watched_blocks::{BLOCKS, SIZES}; + with_test_tables(); + const BATCH: usize = 8; + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()); + // More requests of each kind than there are workers, several times. + let batches = 4 * workers.div_ceil(BATCH) + 1; + + // zlib from the file, with about 1 MiB of source: bytes that do not + // compress (xorshift), so that the stream is about as long. + let mut x = 0x9e37_79b9_7f4a_7c15_u64; + let plain: Vec = (0..(1 << 20) + 1234) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x >> 32) as u8 + }) + .collect(); + let packed = compress_zlib(&plain); + // zlib then BCPack from the file, with room for a BCPack stream far + // longer than this one (a stream may end short of it). + let bc4 = compress_zlib(&BC4_STREAM); + let intermediate = (1 << 20) + 4099; + let mut contents = packed.clone(); + contents.extend_from_slice(&bc4); + let (_dir, file) = file_with(&contents); + // zlib from memory into three pages listed backwards: through a buffer. + let paged = pattern(2 * PAGE + 4093); + let paged_packed = compress_zlib(&paged); + let mut pages = vec![0usize; 3 * BATCH]; + let mut n = pages.len(); + assert_eq!(xmem::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + let mut lists: Vec<[usize; 3]> = + pages.chunks_exact(3).map(|p| [p[2], p[1], p[0]]).collect(); + let mut inflated = vec![vec![0u8; plain.len()]; BATCH]; + let mut unpacked = [[0u8; 16]; BATCH]; + + let (queue, array) = (new_queue(0), status_array(1)); + // Sizes of their own: nothing else here allocates blocks of them. + let watch = [packed.len(), intermediate, paged.len()]; + assert!(watch.iter().all(|&size| size >= 2 * PAGE && size != plain.len())); + for ((watched, blocks), size) in SIZES.iter().zip(&BLOCKS).zip(watch) { + blocks.store(0, Ordering::Relaxed); + watched.store(size, Ordering::Relaxed); + } + // A page's bytes, from the start, and what of the destination it holds. + let pieces = |list: [usize; 3]| { + [(list[0], 0..PAGE), (list[1], PAGE..2 * PAGE), (list[2], 2 * PAGE..paged.len())] + }; + for _ in 0..batches { + for i in 0..BATCH { + inflated[i].fill(0); + unpacked[i] = [0; 16]; + for (page, _) in pieces(lists[i]) { + xmem::page_window(&[page], 0, PAGE).unwrap().bytes().fill(0); + } + let at = inflated[i].as_mut_ptr().cast(); + enqueue(queue, &request(ZLIB, at, plain.len(), file, 0, packed.len())); + let at = unpacked[i].as_mut_ptr().cast(); + let mut r = request(ZLIB | 4 << 1, at, 16, file, packed.len() as u64, bc4.len()); + r.intermediate_size = intermediate as u32; + enqueue(queue, &r); + let at = lists[i].as_mut_ptr().cast(); + let options = ZLIB | PAGE_DESTINATION | MEMORY_SOURCE; + let source = paged_packed.as_ptr().cast(); + enqueue(queue, &request(options, at, paged.len(), source, 0, paged_packed.len())); + } + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + for i in 0..BATCH { + assert!(inflated[i] == plain, "zlib request {i}"); + assert_eq!(unpacked[i], bc4_blocks(), "zlib then BCPack request {i}"); + for (page, bytes) in pieces(lists[i]) { + let mut window = xmem::page_window(&[page], 0, bytes.len()).unwrap(); + assert!(*window.bytes() == paged[bytes], "request {i} to pages"); + } + } + } + for watched in &SIZES { + watched.store(0, Ordering::Relaxed); + } + void(queue, 0x40); + assert_eq!(xmem::XMemFreePhysicalPages(pages.len(), pages.as_ptr()), 1); + let blocks = BLOCKS.each_ref().map(|b| b.load(Ordering::Relaxed)); + assert!( + blocks.iter().all(|&b| b <= workers as u64), + "buffers allocated for the source read from the file, the zlib output for BCPack \ + and the destination in pages: {blocks:?}, in {} requests of each kind on {workers} \ + workers", + batches * BATCH + ); + } + /// BCPack tables we made (uniform models; BC4 index pairs: low 3 bits, /// next 3 bits), in a folder kept for the test process. fn with_test_tables() { From 30b0e9d51d76fb29b15db9b2fd9761b2b18553fe Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:04:33 +0100 Subject: [PATCH 43/49] leonida-gpu: a translated shader lets its container go (RS-SHADER-CONTAINER-FREE) The shader table kept a private copy of every container the title passes (container: bytes.to_vec()) for the whole process, also after the shader was translated, when only small facts of it are still read. What is still read is now kept apart: the program's name and whether its immediate samplers are made linear go into the translation; what pipeline creation asks (a structure builder program, the names make leaves out) is answered once per shader, at the first creation or at the latest before the container goes; the pipeline book uses the stored BLAKE3. After a successful translation the container goes and the memory line's container counters follow it. A shader that stores keeps its container while LEONIDA_PICKED_WRITES is on, until crate::picked has read its programs. Shaders not translated (most of them: translation is lazy) and shaders that fail to translate keep theirs as before. The test translates 64 hand-built compute containers of 32 KB and checks that they keep no container bytes afterwards (all 2,107,648 on the parent), and that a pipeline created again from the first one shares the translated shader and is left out by name as the first was. --- d3d12/crates/leonida-gpu/src/picked.rs | 2 + d3d12/crates/leonida-gpu/src/pipeline.rs | 229 ++++++++++++++++-- d3d12/crates/leonida-gpu/src/pipeline/host.rs | 17 +- .../crates/leonida-gpu/src/pipeline/known.rs | 14 +- d3d12/crates/leonida-gpu/src/pipeline/make.rs | 20 +- 5 files changed, 253 insertions(+), 29 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/picked.rs b/d3d12/crates/leonida-gpu/src/picked.rs index 54985b813f..aedff1596a 100644 --- a/d3d12/crates/leonida-gpu/src/picked.rs +++ b/d3d12/crates/leonida-gpu/src/picked.rs @@ -129,6 +129,8 @@ fn ask(shader: Arc) { if let Some(t) = shader.translated() { t.picks.store(if yes { YES } else { NO }, Relaxed); } + // Its container was kept for this answer (`Shader::translated`). + shader.let_container_go(); } }); Mutex::new(send) diff --git a/d3d12/crates/leonida-gpu/src/pipeline.rs b/d3d12/crates/leonida-gpu/src/pipeline.rs index 709a4cc98a..a0045930ec 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline.rs @@ -7,7 +7,7 @@ //! The title creates some 60,000 pipelines in its first 20 //! seconds and draws with a few dozen (decision 0007, step 3). Shader //! containers are shared by content hash and translated once, on first -//! use (decision 0003). +//! use (decision 0003); a translated shader lets its container go. //! //! shortcut: only vertex plus pixel pipelines from streams and compute //! pipelines get host pipelines; mesh, tessellation and geometry stages, @@ -60,14 +60,40 @@ pub(crate) struct Shader { pub(crate) stage: &'static str, /// The first 8 bytes of its BLAKE3, as logged. pub(crate) hash: String, - container: Vec, + /// Its whole BLAKE3 (its key in [`SHADERS`]) and its size, which stay + /// when the container goes. + full: [u8; 32], + size: usize, + /// The container, until the shader is translated ([`Shader::translated`]). + /// The title passes one for each of its programs, and only a minority is + /// ever translated, but a translated one has every later read of its + /// container answered apart: the program's name and whether its samplers + /// are made linear in [`Translated`], what pipeline creation asks in + /// [`Facts`]. Readers take a reference, so that one that still reads it + /// (a translation, the pipeline book) does not hold the others up. + container: Mutex>>, /// Its part in the stand-in for the indirect light. #[cfg(windows)] pub(crate) ambient: Option, #[cfg(windows)] + facts: OnceLock, + #[cfg(windows)] translated: OnceLock>, } +/// What creating a pipeline asks of the containers of its shaders. It is +/// answered once per shader, at the first creation or at the latest when the +/// container goes ([`Shader::translated`]): a pipeline created afterwards +/// from the same bytes gets the shader, which no longer has its container. +#[cfg(windows)] +struct Facts { + /// A program of the ray-tracing structure builder ([`of_builder`]). + builder: bool, + /// Which of the programs `make` may leave out by name it is, a bit for + /// each of `make::NAMES`. + named: u8, +} + impl std::fmt::Debug for Shader { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} {}", self.stage, self.hash) @@ -78,7 +104,8 @@ impl std::fmt::Debug for Shader { static SHADERS: Mutex>>> = Mutex::new(None); /// For the memory lines: containers kept and their bytes, translations -/// kept and the bytes of their host code. None of them is ever let go. +/// kept and the bytes of their host code. A container is let go when its +/// shader is translated ([`Shader::translated`]); a translation never is. static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; /// What the shader table and the pipeline library keep in memory: @@ -130,16 +157,57 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { Arc::new(Shader { stage, hash: full.to_hex()[..16].to_owned(), - container: bytes.to_vec(), + full: *full.as_bytes(), + size: bytes.len(), + container: Mutex::new(Some(bytes.into())), #[cfg(windows)] ambient: (stage == "compute").then(|| crate::ambient::role(bytes)).flatten(), #[cfg(windows)] + facts: OnceLock::new(), + #[cfg(windows)] translated: OnceLock::new(), }) }) .clone() } +impl Shader { + /// The container, while the shader keeps it. + #[cfg_attr(not(windows), allow(dead_code))] + fn container(&self) -> Option> { + let kept = self.container.lock().unwrap_or_else(|e| e.into_inner()); + kept.clone() + } + + /// Lets the container go: what is read of it later is kept apart. + #[cfg(windows)] + pub(crate) fn let_container_go(&self) { + use std::sync::atomic::Ordering::Relaxed; + let mut kept = self.container.lock().unwrap_or_else(|e| e.into_inner()); + if kept.take().is_some() { + KEPT[0].fetch_sub(1, Relaxed); + KEPT[1].fetch_sub(self.size as u64, Relaxed); + } + } + + /// What creating a pipeline asks of the container ([`Facts`]). + #[cfg(windows)] + fn facts(&self) -> &Facts { + self.facts.get_or_init(|| { + let Some(container) = self.container().filter(|_| self.stage == "compute") else { + return Facts { + builder: false, + named: 0, + }; + }; + Facts { + builder: spilled(&container), + named: make::names(&container), + } + }) + } +} + /// A translated shader and the console resources its code reads. #[cfg(windows)] pub(crate) struct Translated { @@ -161,6 +229,11 @@ pub(crate) struct Translated { /// A compute program translated to run several console groups to a host group /// (`LEONIDA_GROUP_PACK`): where its console grid goes (`crate::draw::pack_of`). pub(crate) pack: Option, + /// The program's own name in its container ([`program_name`]), for the + /// logs of a refused host pipeline after the container has gone. + pub(crate) program: Option, + /// Whether its immediate samplers filter linearly (`host::linear_samplers`). + pub(crate) linear_samplers: bool, /// Whether a bound packed program was logged (`crate::draw::pack_of`). pub(crate) pack_logged: std::sync::atomic::AtomicBool, /// Whether it stores through a view it picks from the heap by an index, @@ -171,18 +244,21 @@ pub(crate) struct Translated { #[cfg(windows)] impl Shader { /// The translation, made on first use; a shader that does not - /// translate is logged once. + /// translate is logged once. A shader that translates lets its container + /// go then. pub(crate) fn translated(&self) -> Option<&Translated> { self.translated .get_or_init(|| { - let done = translate(&self.container); + // Still here: it goes below, once, after the translation. + let container = self.container()?; + let done = translate(&container, &self.hash); // `LEONIDA_SHADER_SAVE=`: each shader as the title gave it (`.cdxil`) and as // translated (`.dxil`), by the hash crash reports name it with if let Some(dir) = std::env::var_os("LEONIDA_SHADER_SAVE") { let dir = std::path::PathBuf::from(dir); let _ = std::fs::create_dir_all(&dir); let stem = format!("{}.{}", self.hash, self.stage); - let _ = std::fs::write(dir.join(format!("{stem}.cdxil")), &self.container); + let _ = std::fs::write(dir.join(format!("{stem}.cdxil")), &*container); if let Ok(t) = &done { let _ = std::fs::write(dir.join(format!("{stem}.dxil")), &t.host.dxil); } @@ -206,6 +282,16 @@ impl Shader { "shader does not translate; its pipelines' draws are dropped" ), } + // Nothing translates it again, and what is read of the container from here on + // was kept above or is in its facts, so the container goes. Not while + // `crate::picked` may still read the programs of a shader that stores: it lets + // the container go when it has its answer. + if let Ok(t) = &done { + self.facts(); + if !(t.stores && crate::picked::on()) { + self.let_container_go(); + } + } done.ok() }) .as_ref() @@ -214,17 +300,20 @@ impl Shader { #[cfg(windows)] impl Shader { - /// The console programs of the container; `None` if they are not known. + /// The console programs of the container; `None` if they are not known, + /// or if the container has gone ([`Shader::translated`] keeps it for + /// `crate::picked`, the one caller). pub(crate) fn programs(&self) -> Option> { use leonida_shader::{Container, FourCC}; - let c = Container::parse(&self.container).ok()?; + let container = self.container()?; + let c = Container::parse(&container).ok()?; let part = c.part(FourCC::DXIL).or(c.part(FourCC::ACCC))?; leonida_shader::native_programs(part.data).ok() } } #[cfg(windows)] -fn translate(container: &[u8]) -> Result { +fn translate(container: &[u8], hash: &str) -> Result { use leonida_shader::{Container, FourCC, HwStage}; // The translation depends on it (a view index past a capped heap). crate::descriptor::host::probe_view_limit(); @@ -267,6 +356,8 @@ fn translate(container: &[u8]) -> Result { stores_by_address, writes, pack, + program: program_name(container), + linear_samplers: crate::pipeline::host::linear_samplers(hash, container), pack_logged: Default::default(), picks: Default::default(), }) @@ -317,12 +408,16 @@ static BUILDER: Mutex = Mutex::new(Builder { /// Whether `shaders` are a pipeline of the structure builder. #[cfg(windows)] fn of_builder(shaders: &[Arc]) -> bool { - use leonida_shader::{Container, FourCC}; let [shader] = shaders else { return false }; - if shader.stage != "compute" { - return false; - } - let Ok(c) = Container::parse(&shader.container) else { + shader.facts().builder +} + +/// Whether a compute container has a program with a spilled user-data table, +/// as the structure builder's programs do ([`Facts::builder`]). +#[cfg(windows)] +fn spilled(container: &[u8]) -> bool { + use leonida_shader::{Container, FourCC}; + let Ok(c) = Container::parse(container) else { return false; }; c.part(FourCC::DXIL) @@ -499,7 +594,7 @@ pub(crate) fn bound(this: This) { } let frame = crate::frame::current(); for shader in &p.shaders { - tracing::info!(pipeline = ?this, frame, stage = shader.stage, size = shader.container.len(), hash = %shader.hash, "first bind"); + tracing::info!(pipeline = ?this, frame, stage = shader.stage, size = shader.size, hash = %shader.hash, "first bind"); } } @@ -959,7 +1054,7 @@ mod tests { pipeline(p) .shaders .iter() - .map(|s| (s.stage, s.container.clone())) + .map(|s| (s.stage, s.container().expect("not translated").to_vec())) .collect() } @@ -1005,6 +1100,106 @@ mod tests { assert_eq!(slot:: u32>(p, 0x10)(p), 0); } + /// The bytes of its container that a shader still keeps. + #[cfg(windows)] + fn held(shader: &Shader) -> usize { + shader.container().map_or(0, |c| c.len()) + } + + /// A console compute container as the title passes one: a `DXBC` header + /// and an `ACCC` part with an `FSPX` program of 64 threads that only ends + /// (`s_endpgm`), then `tail`, past the size the header gives (the parser + /// stops there), which tells containers apart. + #[cfg(windows)] + fn compute_container(tail: &[u8]) -> Vec { + fn put(out: &mut Vec, words: &[u32]) { + out.extend(words.iter().flat_map(|w| w.to_le_bytes())); + } + // The pipeline registers: threads 64x1x1 (+0x0c), wave32 (+0x12 bit 4). + let mut packet = vec![0u8; 0x1c]; + for (at, half) in [(0x0c, 64u16), (0x0e, 1), (0x10, 1), (0x12, 1 << 4)] { + packet[at..at + 2].copy_from_slice(&half.to_le_bytes()); + } + let code = 0xbf81_0000u32.to_le_bytes(); + // The program metadata: no records, one dword of code. + let mut meta = Vec::new(); + put(&mut meta, &[0x403, 0x18 - 0x14, 1, 0, 0, 0]); + let parts: [(u32, &[u8]); 3] = [(0, &packet), (6, &code), (7, &meta)]; + let mut fspx = b"FSPX".to_vec(); + let mut at = 0x10 + 16 * parts.len(); + let size = at + parts.iter().map(|(_, data)| data.len()).sum::(); + put(&mut fspx, &[1, parts.len() as u32, size as u32]); + for (kind, data) in parts { + put(&mut fspx, &[kind, at as u32, data.len() as u32, 0]); + at += data.len(); + } + for (_, data) in parts { + fspx.extend(data); + } + let mut out = b"DXBC".to_vec(); + out.extend([0; 16]); + put(&mut out, &[1, (0x24 + 8 + fspx.len()) as u32, 1, 0x24]); + out.extend(b"ACCC"); + put(&mut out, &[fspx.len() as u32]); + out.extend(fspx); + out.extend(tail); + out + } + + /// A translated shader keeps what is still read of its container, and + /// lets the container go: the title passes one for each of its tens of + /// thousands of programs, and every pipeline that shares the shader + /// shares the translation. A pipeline created afterwards from the same + /// bytes shares the shader, and pipeline creation answers for it what it + /// answered while the container was there. + #[cfg(windows)] + #[test] + fn translated_shaders_let_their_containers_go() { + const COUNT: usize = 64; + let tail = |n: usize| { + let mut tail = vec![0u8; 32 << 10]; + tail[..8].copy_from_slice(&(n as u64).to_le_bytes()); + // Each a program `make` leaves out by its name, as long as the + // ray-tracing structure builder is off (`make::left_out`). + tail[100..120].copy_from_slice(b"CS_RaytracingResolve"); + tail + }; + let containers: Vec> = (0..COUNT).map(|n| compute_container(&tail(n))).collect(); + let create = |container: &[u8]| { + let desc = ComputeHead { + root: std::ptr::null(), + stage: Bytecode { + code: container.as_ptr(), + size: container.len(), + }, + }; + let mut p = std::ptr::null(); + let hr = create_compute(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p); + assert_eq!(hr, S_OK); + p + }; + let pipelines: Vec = containers.iter().map(|c| create(c)).collect(); + let shaders: Vec<&Arc> = + pipelines.iter().map(|&p| &pipeline(p).shaders[0]).collect(); + let all_held = || shaders.iter().map(|s| held(s)).sum::(); + let total: usize = containers.iter().map(Vec::len).sum(); + assert_eq!(all_held(), total); + + for s in &shaders { + assert!(s.translated().is_some(), "{s:?} translates"); + } + assert_eq!(all_held(), 0, "of {total} bytes"); + + let again = create(&containers[0]); + assert!(Arc::ptr_eq(&pipeline(again).shaders[0], shaders[0])); + assert!(pipeline(again).shaders[0].translated().is_some()); + // Left out by its name, as the first pipeline with it was. + assert_eq!(why_gone(again), why_gone(pipelines[0])); + for p in pipelines.into_iter().chain([again]) { + assert_eq!(slot:: u32>(p, 0x10)(p), 0); + } + } + /// The stream layout the title builds (title+0x86f090): root /// signature, five shader slots (the first a mesh shader), blend, sample /// mask, rasterizer, depth-stencil 1, sample description, input layout, diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index 6776eab8e1..464bd55719 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/host.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/host.rs @@ -174,8 +174,10 @@ fn linear_filter(filter: u32) -> u32 { } } -/// The filter of an immediate sampler of `shader` ([`LinearScope`]). -fn static_filter(shader: &Shader, filter: u32) -> u32 { +/// Whether the immediate samplers of the program with `hash` and `container` +/// are made linear ([`LinearScope`]). Asked when it is translated, as its +/// container goes then (`Shader::translated`). +pub(super) fn linear_samplers(hash: &str, container: &[u8]) -> bool { static SCOPE: std::sync::OnceLock = std::sync::OnceLock::new(); let scope = SCOPE.get_or_init(|| { let scope = LinearScope::parse(&std::env::var("LEONIDA_STATIC_SAMPLERS_LINEAR").unwrap_or_default()); @@ -184,7 +186,12 @@ fn static_filter(shader: &Shader, filter: u32) -> u32 { } scope }); - if scope.takes(&shader.hash, &shader.container) { linear_filter(filter) } else { filter } + scope.takes(hash, container) +} + +/// The filter of an immediate sampler of `shader` ([`linear_samplers`]). +fn static_filter(shader: &Shader, filter: u32) -> u32 { + if shader.translated().is_some_and(|t| t.linear_samplers) { linear_filter(filter) } else { filter } } fn integer_format(f: DXGI_FORMAT) -> bool { @@ -829,7 +836,7 @@ impl HostPipeline { Err(e) => { { let names: Vec<_> = - stages.iter().filter_map(|(s, _)| crate::pipeline::program_name(&s.container)).collect(); + stages.iter().filter_map(|(s, _)| s.translated()?.program.clone()).collect(); tracing::warn!(error = %e, ?shaders, ?names, "host pipeline refused"); } host.log_messages(); @@ -997,7 +1004,7 @@ impl HostPipeline { Err(e) => { { let names: Vec<_> = - stages.iter().filter_map(|(s, _)| crate::pipeline::program_name(&s.container)).collect(); + stages.iter().filter_map(|(s, _)| s.translated()?.program.clone()).collect(); tracing::warn!(error = %e, ?shaders, ?names, "host pipeline refused"); } host.log_messages(); diff --git a/d3d12/crates/leonida-gpu/src/pipeline/known.rs b/d3d12/crates/leonida-gpu/src/pipeline/known.rs index e7c8558a34..c5cea2ed0b 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/known.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/known.rs @@ -101,16 +101,22 @@ pub(super) fn note(key: &str, shaders: &[Arc], graphics: Option<&Graphic let mut entry = id.to_vec(); entry.push(shaders.len() as u8); for s in shaders { - let hash = *blake3::hash(&s.container).as_bytes(); + let hash = s.full; let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u8; entry.push(stage); entry.extend(hash); - if book.shaders.insert(hash) { + // A translated shader has let its container go, but not before the first creation with + // it was noted here: `hand_out` notes a pipeline before it can start making one. (Were + // it gone, `make` would pass over the pipeline, whose shader the file would lack.) + if !book.shaders.contains(&hash) + && let Some(container) = s.container() + { + book.shaders.insert(hash); let new = &mut book.new[0]; new.push(stage); new.extend(hash); - new.extend((s.container.len() as u32).to_le_bytes()); - new.extend(&s.container); + new.extend((container.len() as u32).to_le_bytes()); + new.extend(&*container); } } entry.push(u8::from(graphics.is_some())); diff --git a/d3d12/crates/leonida-gpu/src/pipeline/make.rs b/d3d12/crates/leonida-gpu/src/pipeline/make.rs index 70588b4e20..95b7af156b 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/make.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/make.rs @@ -58,10 +58,24 @@ pub(crate) struct Pending { variant: OnceLock>, } -fn named(shaders: &[Arc], name: &[u8]) -> bool { - shaders +/// The compute programs [`left_out`] may leave out, by a name their container +/// holds. Looked for once per shader (`Shader::facts`): a translated shader +/// no longer has its container when the title creates another pipeline with it. +const NAMES: [&[u8]; 2] = [b"CS_RaytracingResolve", b"CS_ScreenProbes_ActivateRays"]; + +/// Which of [`NAMES`] `container` holds, a bit for each. +pub(super) fn names(container: &[u8]) -> u8 { + NAMES .iter() - .any(|s| s.stage == "compute" && s.container.windows(name.len()).any(|w| w == name)) + .enumerate() + .filter(|(_, name)| container.windows(name.len()).any(|w| w == **name)) + .fold(0, |bits, (n, _)| bits | 1 << n) +} + +/// Whether one of `shaders` is a compute program with `name`, one of [`NAMES`]. +fn named(shaders: &[Arc], name: &[u8]) -> bool { + let bit = NAMES.iter().position(|n| *n == name).map_or(0, |n| 1 << n); + shaders.iter().any(|s| s.facts().named & bit != 0) } fn left_out(shaders: &[Arc]) -> Option<&'static str> { From a685db40ec4b0a1177f517d326754df47f97d430 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:11:47 +0100 Subject: [PATCH 44/49] leonida-gpu: an arena of memory by address is in the PC's memory once (RS-ARENA-ONE-COPY) Every 64 MiB arena of title memory by address (memory.rs) was held twice in the PC's memory: the arena itself (committed, write-watched) and the CPU side of its copy on the card, a shared buffer of the same size that by_address made and that every refresh compared with the arena. memory.rs already takes only the dwords title memory changed into the arena, so the two held the same bytes. That is 64 MiB more commit per arena; reads alone make a few arenas, the structure builder (LEONIDA_BVH_BUILDER=1) up to 48. Now Memory::another() makes the copy with shadow::by_address_opened: the arena is opened as a host heap (inplace::place_part, as the in-place windows do) and is itself the CPU side, with Card::staging a buffer placed over it. Such a copy is never refreshed or compared; bring() and take() resend exactly the dword runs they change, so the card side keeps what the builder made of the other dwords, as before. The whole arena goes up once when it is made, as a new copy's first refresh sent it. If the host does not open the memory, the copy is made as before. The directory and the windows of title memory keep the old path. USED in by_address is only ever added to; since copies by address are never let go it is a live total apart from attempts over the limit, left as it is. Tests: an_arena_is_in_the_pcs_memory_once (fails on main: the CPU side is a buffer of its own, 192 MiB more commit per arena on an RX 7900 XT, whose driver charges the card side too; 128 MiB with this change) and an_arena_sends_up_only_the_dwords_the_title_changed (the card keeps its own dword beside the one the title changed, with and without LEONIDA_SEND_OWN). --- d3d12/crates/leonida-gpu/src/memory.rs | 188 ++++++++++++++++++++++--- d3d12/crates/leonida-gpu/src/shadow.rs | 87 +++++++++++- 2 files changed, 255 insertions(+), 20 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/memory.rs b/d3d12/crates/leonida-gpu/src/memory.rs index 223f760ce3..2aee650bdd 100644 --- a/d3d12/crates/leonida-gpu/src/memory.rs +++ b/d3d12/crates/leonida-gpu/src/memory.rs @@ -402,7 +402,9 @@ impl Memory { let Some(at) = crate::upload::reserve(ARENA as usize) else { return false; }; - let Some(n) = crate::shadow::by_address(at as u64, ARENA).and_then(|s| self.number(s)) else { + // Its copy's CPU side is the arena itself where the host opens it: + // what changes in it goes up as `bring` and `take` find it. + let Some(n) = crate::shadow::by_address_opened(at as u64, ARENA).and_then(|s| self.number(s)) else { return false; }; self.arenas.push((n, at)); @@ -538,6 +540,9 @@ impl Memory { let never = std::mem::replace(&mut held.taken, now.max(1)) == 0; let shadow = &self.copies[held.copy]; let base = held.at - shadow.span().0 as usize; + // Of an arena that is its copy's CPU side the dwords that + // changed go up as they are found here: nothing compares it. + let mut changed = Vec::new(); let mut title = [0u8; PIECE]; for piece in (0..PAGE as usize).step_by(PIECE) { let from = (page * PAGE) as usize + piece; @@ -545,10 +550,16 @@ impl Memory { crate::host::copy_mapped(title.as_mut_ptr(), from as *const u8, PIECE, false); // SAFETY: a page of an arena of ours, under the mutex. let ours = unsafe { std::slice::from_raw_parts_mut((held.at + piece) as *mut u8, PIECE) }; - self.stats.changed += merge(&title, ours, never) as u64 * 4; + let runs = merge(&title, ours, never); + self.stats.changed += runs.iter().map(|r| r.1 as u64).sum::(); + if shadow.side_is_memory() && !never { + changed.extend(runs.into_iter().map(|(at, n)| (base + piece + at, base + piece + at + n))); + } } if never { shadow.resend(base, base + PAGE as usize); + } else if !changed.is_empty() { + shadow.resend_runs(changed.into_iter()); } } self.stats.micros += started.elapsed().as_micros() as u64; @@ -663,6 +674,9 @@ impl Memory { let Some(held) = self.pages.get(&page) else { return }; let shadow = &self.copies[held.copy]; let base = held.at - shadow.span().0 as usize; + // (As in `bring`: of an arena that is its copy's CPU side the dwords + // that changed go up from here.) + let mut changed = Vec::new(); let mut title = [0u8; PIECE]; let mut at = from; while at < to { @@ -670,14 +684,19 @@ impl Memory { crate::host::copy_mapped(title.as_mut_ptr(), (page as usize * PAGE as usize + at) as *const u8, n, false); // SAFETY: a page of an arena of ours, under the mutex. let ours = unsafe { std::slice::from_raw_parts_mut((held.at + at) as *mut u8, n) }; - if *ours != title[..n] { - ours.copy_from_slice(&title[..n]); + let runs = merge(&title[..n], ours, false); + if !runs.is_empty() { crate::watch::wrote(held.at + at, n); } + if shadow.side_is_memory() && !whole { + changed.extend(runs.into_iter().map(|(a, len)| (base + at + a, base + at + a + len))); + } at += n; } if whole { shadow.resend(base + from, base + to); + } else if !changed.is_empty() { + shadow.resend_runs(changed.into_iter()); } } @@ -894,24 +913,28 @@ fn packed_len(header: u64) -> Option { (version & 0xFFFF == 6 && marks & 0x8100 == 0x8100 && nodes > 0 && len <= PACKED).then_some(len) } -/// Puts what `title` holds into `ours` (what was last taken): the dwords that -/// differ. How many. -fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> usize { +/// Puts what `title` holds into `ours` (what was last taken; as long as +/// `title`): the dwords that differ, all of it if `never`. The runs that +/// changed, as (offset, bytes) in order. +fn merge(title: &[u8], ours: &mut [u8], never: bool) -> Vec<(usize, usize)> { if never { ours.copy_from_slice(title); - return PIECE / 4; + return if title.is_empty() { Vec::new() } else { vec![(0, title.len())] }; } if ours == title { - return 0; + return Vec::new(); } - let mut changed = 0; - for (t, o) in title.chunks_exact(4).zip(ours.chunks_exact_mut(4)) { + let mut runs: Vec<(usize, usize)> = Vec::new(); + for (i, (t, o)) in title.chunks(4).zip(ours.chunks_mut(4)).enumerate() { if t != o { o.copy_from_slice(t); - changed += 1; + match runs.last_mut() { + Some((at, n)) if *at + *n == i * 4 => *n += t.len(), + _ => runs.push((i * 4, t.len())), + } } } - changed + runs } /// Before a draw whose shader reads title memory by address: what its @@ -1307,15 +1330,148 @@ mod tests { fn a_piece_takes_what_changed() { let mut title = [7u8; PIECE]; let mut ours = vec![0u8; PIECE]; - assert_eq!(merge(&title, &mut ours, true), PIECE / 4); + assert_eq!(merge(&title, &mut ours, true), [(0, PIECE)]); assert_eq!(ours, title); - assert_eq!(merge(&title, &mut ours, false), 0); + assert_eq!(merge(&title, &mut ours, false), []); // A dword of it. title[41] = 8; - assert_eq!(merge(&title, &mut ours, false), 1); + assert_eq!(merge(&title, &mut ours, false), [(40, 4)]); + assert_eq!(ours, title); + // Dwords side by side are one run, and the runs are in order. + title[4..12].fill(9); + title[100] = 9; + assert_eq!(merge(&title, &mut ours, false), [(4, 8), (100, 4)]); assert_eq!(ours, title); } + /// The process's commit charge (its private bytes). + fn commit() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { cb: size_of::() as u32, ..Default::default() }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + c.PagefileUsage as u64 + } + + /// The tests here that make arenas, one at a time: what one makes is + /// not counted in another's commit. + fn arenas_turn() -> std::sync::MutexGuard<'static, ()> { + static TURN: Mutex<()> = Mutex::new(()); + TURN.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// An arena is in the PC's memory once: the CPU's side of its copy on + /// the card is the arena itself, not a second buffer of its size with + /// the same bytes (64 MiB more commit per arena, and the structure + /// builder keeps up to 48). On the host's card, as the other tests that + /// need one. + #[test] + fn an_arena_is_in_the_pcs_memory_once() { + let Some(host) = host() else { return }; + if !crate::shadow::cards() || !host.card_ready() { + return; + } + let _turn = arenas_turn(); + // Three times each, as other tests make and free memory meanwhile. + // First what the copy's side on the card costs by itself (some + // drivers charge the process for the card's memory too: 64 MiB on an + // AMD RX 7900 XT): the most of three, all kept until the end, as the + // driver hands memory let go of out again without a charge. + let mut cards = Vec::new(); + let mut card = 0; + for _ in 0..3 { + let before = commit(); + cards.push(host.uav_buffer(ARENA).expect("a buffer on the card")); + card = card.max(commit().saturating_sub(before)); + } + // Then an arena, the least of three. + let mut m = Memory::new().expect("title memory by address"); + let mut sides = Vec::new(); + let mut grew = u64::MAX; + for _ in 0..3 { + let before = commit(); + assert!(m.another(), "an arena"); + grew = grew.min(commit().saturating_sub(before)); + let &(n, at) = m.arenas.last().expect("an arena"); + sides.push((at, m.copies[n].card_data() as usize)); + } + eprintln!( + "an arena of {} MiB: {} MiB more commit, its side on the card {} MiB; (arena, CPU side): {sides:x?}", + ARENA >> 20, + grew >> 20, + card >> 20 + ); + for (at, side) in sides { + assert_eq!(side, at, "the CPU's side of the arena's copy is the arena itself"); + } + assert!( + grew < card + ARENA + ARENA / 2, + "an arena of {} MiB took {} MiB of commit beside its side on the card", + ARENA >> 20, + grew.saturating_sub(card) >> 20 + ); + } + + /// What the title changed in a page of an arena goes up by the dword, + /// and what the card's side holds beside it stays (the structure + /// builder's work is only there): with the arena as its copy's CPU side + /// nothing compares the two, so `bring` says what it changed. On the + /// host's card. + #[test] + fn an_arena_sends_up_only_the_dwords_the_title_changed() { + let Some(host) = host() else { return }; + if !crate::shadow::cards() || !host.card_ready() { + return; + } + let _turn = arenas_turn(); + let mut m = Memory::new().expect("title memory by address"); + assert!(m.another(), "an arena"); + // A page of title memory of the test's own, where the directory + // reaches. + let title = crate::upload::reserve(PAGE as usize).expect("a page"); + // SAFETY: the test's own page, never let go. + let words = unsafe { std::slice::from_raw_parts_mut(title as *mut u32, PAGE as usize / 4) }; + for (i, word) in words.iter_mut().enumerate() { + *word = i as u32; + } + let page = title as u64 / PAGE; + let (copy, at) = m.free.pop().expect("a free page"); + m.hold(page, at, copy); + let shadow = m.copies[copy].clone(); + let offset = at as u64 - shadow.span().0; + // Taken whole the first time. + m.frame = 1; + m.bring(page, page + 1); + let (aside, data) = host.shared_buffer(PAGE).expect("a buffer"); + // A list that brings every copy up to date when it is submitted, as + // a list that reads memory by address does. + let run = |m: &Memory, record: &dyn Fn(&ID3D12GraphicsCommandList)| { + let list = host.new_list().expect("a host list"); + m.bring_up(&list); + record(&list.list); + list.close(); + host.execute(&[&list]); + }; + // A store on the card's side alone, as the builder's: dword 10. + // SAFETY: the mapping of the buffer just made. + unsafe { data.cast::().write(0xb11d) }; + // SAFETY: an open list; live buffers, the ranges inside them. + run(&m, &|list| unsafe { list.CopyBufferRegion(&shadow.buffer, offset + 40, &aside, 0, 4) }); + // The title changes dword 20, and the page is taken again. + words[20] = 0x7171; + m.frame = 2; + m.bring(page, page + 1); + // SAFETY: as above. + run(&m, &|list| unsafe { list.CopyBufferRegion(&aside, 0, &shadow.buffer, offset, PAGE) }); + // SAFETY: the mapping; `execute` waited for the copy. + let got = unsafe { std::slice::from_raw_parts(data.cast::().cast_const(), PAGE as usize / 4) }; + assert_eq!(got[20], 0x7171, "the dword the title changed went up"); + assert_eq!(got[10], 0xb11d, "the card's own dword stayed"); + assert_eq!(&got[..10], &words[..10], "the page went up whole the first time"); + assert_eq!(&got[21..], &words[21..]); + } + #[test] fn a_packed_structure_is_known_by_its_header() { let header = |version: u32, nodes: u32| u64::from(version) | u64::from(nodes) << 32; diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 8415889fac..283668dc4e 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -401,6 +401,15 @@ pub(crate) struct Shadow { /// and the bytes from the buffer's first byte to `start` (the heap /// begins on a 64 KiB line; a title buffer need not). place: Option<(windows::Win32::Graphics::Direct3D12::ID3D12Heap, u64)>, + /// Of a copy with two sides over memory of ours ([`by_address_opened`]): + /// the memory itself is the CPU's side, opened as this heap, and + /// `Card::staging` is a buffer placed over all of it. Nothing is copied + /// into that side and nothing compares it with the memory: whoever + /// writes the memory says which bytes changed ([`Shadow::resend`]). It + /// may write while a submission takes bytes out of the side to send + /// them; what it changed is resent after it wrote, so the next send has + /// it. + opened: Option, } /// What a copy in the card's memory ([`cards`]) has beside the buffer @@ -3859,6 +3868,7 @@ impl Shadow { wc: AtomicU8::new(0), mapped: false, place: None, + opened: None, } } @@ -4603,8 +4613,9 @@ impl Shadow { /// since it was last copied (all of it if the memory is not /// write-watched). Returns the bytes copied. pub(crate) fn update(&self, address: usize, len: usize) -> usize { - // In place: the card reads title memory itself. - if self.place.is_some() { + // In place: the card reads title memory itself. Opened: the CPU's + // side is the memory, and its writer said what goes up. + if self.place.is_some() || self.opened.is_some() { return 0; } let (start, end) = (self.start as usize, (self.start + self.len) as usize); @@ -4646,7 +4657,7 @@ impl Shadow { /// nothing, and knows it without asking anything /// (`crate::watch::nothing_new`). `false` if it would have to ask. pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool { - if self.place.is_some() { + if self.place.is_some() || self.opened.is_some() { return true; } let (start, end) = (self.start as usize, (self.start + self.len) as usize); @@ -5050,6 +5061,17 @@ impl Shadow { self.card_changed(from, to); } + /// [`Shadow::resend`] of each of `runs` (offsets `[from, to)`). + pub(crate) fn resend_runs(&self, runs: impl Iterator) { + self.card_changed_runs(runs); + } + + /// Whether the CPU's side is the memory itself ([`by_address_opened`]): + /// then only what its writer resends goes up. + pub(crate) fn side_is_memory(&self) -> bool { + self.opened.is_some() + } + /// The CPU side's bytes at offsets `[from, to)` changed: they go to the /// card's side before the next submission. fn card_changed(&self, from: usize, to: usize) { @@ -6296,6 +6318,23 @@ pub(crate) fn small_buffer_in(address: u64, len: u64, most: u64) -> bool { /// the only place that has it. The CPU's side holds the bytes as they were /// last taken, and only dwords that changed since go up. pub(crate) fn by_address(start: u64, len: u64) -> Option> { + by_address_with(start, len, false) +} + +/// [`by_address`] of memory of ours that one writer changes, and that writer +/// resends what it changed ([`Shadow::resend`]): an arena of +/// [`crate::memory`]'s, which takes only the dwords title memory changed. +/// The memory is opened as a heap of the host's and is itself the CPU's +/// side, so its bytes are in the PC's memory once. That side was a buffer +/// of the same size with the same bytes, which every refresh compared with +/// the arena: 64 MiB more commit per arena, and with the structure builder +/// (`LEONIDA_BVH_BUILDER=1`) up to 48 arenas. If the host does not open the +/// memory, the copy is made as [`by_address`] makes it. +pub(crate) fn by_address_opened(start: u64, len: u64) -> Option> { + by_address_with(start, len, true) +} + +fn by_address_with(start: u64, len: u64, open: bool) -> Option> { let host = host()?; if !cards() || !host.card_ready() { return None; @@ -6310,7 +6349,13 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option> { mb.unwrap_or(4096) << 20 }); let room = host.video_memory().is_none_or(|[budget, used, ..]| used + len < budget / 100 * 97); - let (staging, data) = host.shared_buffer(len)?; + let (staging, data, opened) = match open.then(|| opened_side(host, start, len)).flatten() { + Some(placed) => (placed.buffer, start as *mut u8, Some(placed.heap)), + None => { + let (staging, data) = host.shared_buffer(len)?; + (staging, data, None) + } + }; let on_card = if room && USED.fetch_add(len, Ordering::Relaxed) + len <= most { host.uav_buffer(len) } else { @@ -6339,12 +6384,46 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option> { has_sent: Default::default(), size: len, }); + if opened.is_some() { + // Nothing asks the write watch about it (`Shadow::asked_ahead`): its + // writer tells. + *shadow.watched.get_mut() = NOT_WATCHED; + shadow.opened = opened; + } let shadow = Arc::new(shadow); note_carded(&shadow); elide::made(&shadow); + if shadow.opened.is_some() { + // All of it goes up once, as a new copy's first refresh sends it. + // (Once it is noted: the queue of changed copies names it by its + // place.) + shadow.resend(0, len as usize); + } Some(shadow) } +/// For [`by_address_opened`]: `[start, start + len)` opened as a heap, with +/// a buffer placed over it from its first byte, so that the buffer's offsets +/// are the copy's (the card's side is filled from it at the same offsets). +fn opened_side(host: &crate::host::Host, start: u64, len: u64) -> Option { + match crate::inplace::place_part(&host.device, start, len) { + Ok(placed) if placed.bias == 0 => Some(placed), + Ok(_) => None, + Err(e) => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!( + start = format_args!("{start:#x}"), + len, + error = ?e, + "memory by address not opened as its copy's CPU side: that side is a buffer of its own, as before" + ); + }); + None + } + } +} + /// Copies of title memory outside buffers, by (start, length). static LOOSE: std::sync::RwLock>> = std::sync::RwLock::new(BTreeMap::new()); From 8960d4159a8b8c6759abe8ef18b7d5375f695bca Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:19:23 +0100 Subject: [PATCH 45/49] vulkan: image views wait with their bindless slot after a device loss (RT-DEVICE-LOST-DRAIN) DeviceState::release defers a bindless slot and then the image views paired with it, and until the slot is released the set's pending writes and shadow copy may still name those views. Before this the deferred queue drained in order, so the slot's write was swapped for the fallback before the views went. After a loss the previous commit destroyed the views at once (and drain_lost destroyed those queued before the loss) while the slot stayed queued, so a flush that still ran could hand a destroyed view to vkUpdateDescriptorSets. Image views now stay queued after the loss like the slots, in their order, and go at teardown after their slot. That stays bounded: no slot comes back before its release, a slot has at most four views, and the context's view cache grows only while batches replay. The test now also defers a slot and its view before and after the loss and expects no view destroyed before teardown, then each slot released before its view. It counts only the buffers and views it made. --- runtime/src/vulkan_backend.h | 25 ++-- .../test/vk_deferred_destroy_lost_test.cpp | 125 +++++++++++++++--- 2 files changed, 122 insertions(+), 28 deletions(-) diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 470251eeb7..ef864b4e15 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -532,8 +532,17 @@ class DeferredDeletionQueue { for (const Item& item : to_destroy) destroy(item, device, vk, release_fn, release_user); } - // After a device loss: destroys every item now, whatever its ticket, except the bindless slots, which stay queued - // in their order. Releasing a slot takes the device's descriptor lock, which a caller of this may hold. + // What still waits for a drain after a device loss, in its order, instead of being destroyed at once. Releasing a + // bindless slot takes the device's descriptor lock, which the caller that defers it holds (DeviceState::release in + // d3d12_vulkan_device.cpp). An image view is deferred right after its slot, and until the slot is released the + // set's pending writes and shadow copy may still name the view; a flush hands those to vkUpdateDescriptorSets, + // which must not see a destroyed view. So views go at teardown too, after their slot. Both stay bounded: the set + // never hands out more slots than it has (a slot comes back only through its release), a slot has at most four + // views, and the context's own view cache grows only while batches replay, which stops at the loss. + static bool kept_after_loss(Kind kind) { return kind == Kind::bindless_slot || kind == Kind::image_view; } + + // After a device loss: destroys every item now, whatever its ticket, except those kept_after_loss(), which stay + // queued in their order. void drain_lost(VkDevice device, const VulkanDeviceFunctions& vk) { std::vector to_destroy; { @@ -542,7 +551,7 @@ class DeferredDeletionQueue { std::size_t kept = 0; for (std::size_t i = 0; i < count_; ++i) { const Item& item = pending_[(head_ + i) & mask]; - if (item.kind == Kind::bindless_slot) { + if (kept_after_loss(item.kind)) { // Kept items move towards the front only, so this never overwrites one not yet read. pending_[(head_ + kept) & mask] = item; ++kept; @@ -576,7 +585,8 @@ class DeferredDeletionQueue { delete reinterpret_cast(item.handle); break; case Kind::sparse_resource: - // Releases the resource and its page backing together after outstanding submissions. + // Releases the resource and its page backing together: after outstanding submissions, or at once after a + // device loss. delete reinterpret_cast*>(item.handle); break; case Kind::buffer: @@ -2007,10 +2017,9 @@ class VulkanContext { // Once the device is lost no retire ticket completes again (completed_retire_ticket() answers 0 and acquire() // returns before its drain), so a queued object would stay until the context goes and the queue would grow // with everything the title releases. The lost device runs nothing more, and vkDestroy* and vkFreeMemory are - // valid on it: the object goes now, and the first time also everything queued before the loss. A bindless - // slot still waits: its release takes the device's descriptor lock, which the caller may hold (release() in - // d3d12_vulkan_device.cpp), and the set never hands out more slots than it has, so those entries stay bounded. - if (is_device_lost() && kind != DeferredDeletionQueue::Kind::bindless_slot) { + // valid on it: the object goes now, and the first time also everything queued before the loss. Bindless slots + // and image views still wait, in their order (DeferredDeletionQueue::kept_after_loss says why). + if (is_device_lost() && !DeferredDeletionQueue::kept_after_loss(kind)) { if (!lost_queue_drained_.exchange(true, std::memory_order_acq_rel)) deletion_queue_.drain_lost(device_, vk); DeferredDeletionQueue::destroy({0, raw_handle, kind}, device_, vk, nullptr, nullptr); return; diff --git a/runtime/test/vk_deferred_destroy_lost_test.cpp b/runtime/test/vk_deferred_destroy_lost_test.cpp index 6f57410be3..67e3e79f9d 100644 --- a/runtime/test/vk_deferred_destroy_lost_test.cpp +++ b/runtime/test/vk_deferred_destroy_lost_test.cpp @@ -5,18 +5,24 @@ // 1. Buffers deferred before the loss wait for a submission that never comes. // 2. After the loss, the next deferred destruction frees them and every later one is freed at once: all 1000 buffers // are gone while the context lives, and the context's own teardown destroys none of them twice. -// 3. A bindless slot, queued before the loss or after it, still waits in the queue (its release takes the device's -// descriptor lock, which the caller holds) and is released once, at teardown. -// vkDestroyBuffer is interposed on a real device's table to count the destructions. Skips with exit code 77 when no -// Vulkan 1.3 device is available; LEONIDA_VK_VALIDATION=1 runs it under the validation layer. No game data. +// 3. A bindless slot and the image view released with it (DeviceState::release in d3d12_vulkan_device.cpp defers +// the slot, then its views), queued before the loss or after it, both wait in the queue. Releasing the slot +// takes the device's descriptor lock, which the caller holds; and until the slot is released the set's pending +// writes and shadow copy may still name the view, which a flush hands to vkUpdateDescriptorSets. At teardown the +// slot is released first, then its view is destroyed. +// vkDestroyBuffer and vkDestroyImageView are interposed on a real device's table; only the buffers and views the test +// made are counted. Skips with exit code 77 when no Vulkan 1.3 device is available; +// LEONIDA_VK_VALIDATION=1 runs it under the validation layer. No game data. #include "vk_test_device.h" #include "../src/vulkan_backend.h" -#include #include #include #include +#include +#include #include +#include #define EXPECT(condition) do { \ if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); std::_Exit(1); } \ @@ -24,25 +30,67 @@ namespace { +template +std::uint64_t key(Handle handle) { + return static_cast(reinterpret_cast(handle)); +} + namespace driver { PFN_vkGetDeviceProcAddr real_get_device = nullptr; PFN_vkDestroyBuffer real_destroy_buffer = nullptr; +PFN_vkDestroyImageView real_destroy_view = nullptr; + +std::mutex mutex; +std::set ours; // the buffers and views the test made +unsigned destroyed_buffers = 0; // of ours +unsigned destroyed_views = 0; // of ours +std::vector events; // bindless slot releases and destructions of our views, in order + +void adopt(std::uint64_t handle) { + std::lock_guard lock(mutex); + ours.insert(handle); +} -std::atomic destroyed_buffers{0}; +unsigned buffers() { + std::lock_guard lock(mutex); + return destroyed_buffers; +} + +unsigned views() { + std::lock_guard lock(mutex); + return destroyed_views; +} VKAPI_ATTR void VKAPI_CALL destroy_buffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks* allocator) { - if (buffer) destroyed_buffers.fetch_add(1, std::memory_order_relaxed); + { + std::lock_guard lock(mutex); + if (ours.erase(key(buffer))) ++destroyed_buffers; + } real_destroy_buffer(device, buffer, allocator); } +VKAPI_ATTR void VKAPI_CALL destroy_view(VkDevice device, VkImageView view, const VkAllocationCallbacks* allocator) { + { + std::lock_guard lock(mutex); + if (ours.erase(key(view))) { + ++destroyed_views; + events.push_back(key(view)); + } + } + real_destroy_view(device, view, allocator); +} + VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { - if (std::string_view(name) == "vkDestroyBuffer") return reinterpret_cast(destroy_buffer); + const std::string_view n(name); + if (n == "vkDestroyBuffer") return reinterpret_cast(destroy_buffer); + if (n == "vkDestroyImageView") return reinterpret_cast(destroy_view); return real_get_device(device, name); } void install(PFN_vkGetDeviceProcAddr device_proc, VkDevice device) { real_get_device = device_proc; real_destroy_buffer = reinterpret_cast(device_proc(device, "vkDestroyBuffer")); + real_destroy_view = reinterpret_cast(device_proc(device, "vkDestroyImageView")); } } // namespace driver @@ -58,7 +106,8 @@ int main() { } driver::install(d.device_proc, d.device); const auto create_buffer = d.fn("vkCreateBuffer"); - EXPECT(create_buffer); + const auto create_view = d.fn("vkCreateImageView"); + EXPECT(create_buffer && create_view); const auto make_buffer = [&] { VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = 256; @@ -66,38 +115,74 @@ int main() { info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VkBuffer buffer = VK_NULL_HANDLE; EXPECT(create_buffer(d.device, &info, nullptr, &buffer) == VK_SUCCESS && buffer); + driver::adopt(key(buffer)); return buffer; }; + const VkImage image = d.image(VK_FORMAT_R8G8B8A8_UNORM, 4, 4, 1, VK_IMAGE_USAGE_SAMPLED_BIT); // d destroys it + EXPECT(image); + const auto make_view = [&] { + VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + info.image = image; + info.viewType = VK_IMAGE_VIEW_TYPE_2D; + info.format = VK_FORMAT_R8G8B8A8_UNORM; + info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + VkImageView view = VK_NULL_HANDLE; + EXPECT(create_view(d.device, &info, nullptr, &view) == VK_SUCCESS && view); + driver::adopt(key(view)); + return view; + }; constexpr unsigned before_loss = 500; constexpr unsigned total = 1000; - unsigned released_slots = 0; + constexpr std::uint64_t slot_before = (std::uint64_t(1) << 32) | 3u; + constexpr std::uint64_t slot_after = (std::uint64_t(1) << 32) | 7u; + const VkImageView view_before = make_view(), view_after = make_view(); { VulkanContext context(driver::get_device, d.device, true); EXPECT(context.loaded()); context.set_bindless_release( - [](void* user, std::uint32_t, std::uint32_t) { ++*static_cast(user); }, &released_slots); + [](void*, std::uint32_t dimension, std::uint32_t index) { + std::lock_guard lock(driver::mutex); + driver::events.push_back((std::uint64_t(dimension) << 32) | index); + }, + nullptr); - // 1, with a bindless slot among the buffers + // 1, with a bindless slot and its view among the buffers for (unsigned i = 0; i < before_loss; ++i) { context.defer_destroy(DeferredDeletionQueue::Kind::buffer, make_buffer()); - if (i == before_loss / 2) - context.defer_destroy(DeferredDeletionQueue::Kind::bindless_slot, (std::uint64_t(1) << 32) | 3u); + if (i == before_loss / 2) { + context.defer_destroy(DeferredDeletionQueue::Kind::bindless_slot, slot_before); + context.defer_destroy(DeferredDeletionQueue::Kind::image_view, view_before); + } } - EXPECT(driver::destroyed_buffers.load() == 0); + EXPECT(driver::buffers() == 0); + EXPECT(driver::views() == 0); // 2 context.mark_device_lost("the test marks the device lost"); for (unsigned i = before_loss; i < total; ++i) context.defer_destroy(DeferredDeletionQueue::Kind::buffer, make_buffer()); - EXPECT(driver::destroyed_buffers.load() == total); + EXPECT(driver::buffers() == total); + EXPECT(driver::views() == 0); // the view queued before the loss still waits behind its slot // 3 - context.defer_destroy(DeferredDeletionQueue::Kind::bindless_slot, (std::uint64_t(1) << 32) | 7u); - EXPECT(released_slots == 0); + context.defer_destroy(DeferredDeletionQueue::Kind::bindless_slot, slot_after); + context.defer_destroy(DeferredDeletionQueue::Kind::image_view, view_after); + context.defer_destroy(DeferredDeletionQueue::Kind::buffer, make_buffer()); // still freed at once + EXPECT(driver::buffers() == total + 1); + EXPECT(driver::views() == 0); + std::lock_guard lock(driver::mutex); + EXPECT(driver::events.empty()); + } + EXPECT(driver::buffers() == total + 1); + EXPECT(driver::views() == 2); + { + std::lock_guard lock(driver::mutex); + const std::vector expected{slot_before, key(view_before), slot_after, key(view_after)}; + EXPECT(driver::events == expected); } - EXPECT(driver::destroyed_buffers.load() == total); - EXPECT(released_slots == 2); + std::puts("deferred deletion after a loss: buffers freed at once; bindless slots and their views kept, in order"); + EXPECT(d.validation_errors() == 0); std::puts("vk_deferred_destroy_lost: ok"); return 0; From defc55eee260833cf6b2819cac0787f673a798a8 Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:22:22 +0100 Subject: [PATCH 46/49] vulkan: a batch that takes the tracker lock after a device loss stops before the bindless flush (RT-DEVICE-LOST-DRAIN) A queue holds tracker_mutex_ through its vkQueueSubmit, so it can find the device lost while another queue's ExecuteCommandLists waits for that lock, past its own checks of the loss (the first one and acquire()). Once lost, defer_destroy destroys released objects at once and also what was queued before the loss, so an image may be gone whose view the bindless set's pending writes or shadow copy still name until its slot is released. The waiting batch then flushed the set and handed that view to vkUpdateDescriptorSets. execute_now now checks the loss again right after it takes tracker_mutex_, before the bindless prepare, and returns as its other checks do. The batch would not have reached the queue anyway, since submit() refuses a lost device, so nothing the title sees changes. The test marks the device lost from an interposed vkBeginCommandBuffer, after the batch's own checks, and expects the bindless prepare not to run. --- runtime/src/vulkan_backend.h | 10 ++++ .../test/vk_deferred_destroy_lost_test.cpp | 60 ++++++++++++++++++- 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index ef864b4e15..42e185c841 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -3681,6 +3681,16 @@ class VulkanQueue : private QueueHolds::Holder { VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, nullptr); } if (!tracker_lock.owns_lock()) tracker_lock.lock(); + // Another queue holds tracker_mutex_ through its vkQueueSubmit, so it can find the device lost while this batch + // waits here, past its own checks above. Once the device is lost, defer_destroy destroys released objects at + // once rather than after the next submission, and also what was queued before the loss. An image may then be + // gone whose view the bindless set's pending writes or shadow copy still name until its slot is released, and + // the flush below would hand that view to vkUpdateDescriptorSets. Nothing this batch records would reach the + // queue anyway: submit() refuses a lost device. + if (context_.is_device_lost()) { + discard(); + return queue_unsupported(__LINE__); + } if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), "vkEndCommandBuffer") == VK_SUCCESS; diff --git a/runtime/test/vk_deferred_destroy_lost_test.cpp b/runtime/test/vk_deferred_destroy_lost_test.cpp index 67e3e79f9d..daa9ad7685 100644 --- a/runtime/test/vk_deferred_destroy_lost_test.cpp +++ b/runtime/test/vk_deferred_destroy_lost_test.cpp @@ -10,15 +10,20 @@ // takes the device's descriptor lock, which the caller holds; and until the slot is released the set's pending // writes and shadow copy may still name the view, which a flush hands to vkUpdateDescriptorSets. At teardown the // slot is released first, then its view is destroyed. -// vkDestroyBuffer and vkDestroyImageView are interposed on a real device's table; only the buffers and views the test -// made are counted. Skips with exit code 77 when no Vulkan 1.3 device is available; +// 4. A batch that takes the tracker lock after the loss (another queue's vkQueueSubmit found it while this one +// waited for that lock) stops before it flushes the bindless set or records its lists: the loss is marked from +// the interposed vkBeginCommandBuffer, after the batch's first check of it. +// vkDestroyBuffer, vkDestroyImageView and vkBeginCommandBuffer are interposed on a real device's table; only the +// buffers and views the test made are counted. Skips with exit code 77 when no Vulkan 1.3 device is available; // LEONIDA_VK_VALIDATION=1 runs it under the validation layer. No game data. #include "vk_test_device.h" #include "../src/vulkan_backend.h" +#include #include #include #include +#include #include #include #include @@ -39,12 +44,14 @@ namespace driver { PFN_vkGetDeviceProcAddr real_get_device = nullptr; PFN_vkDestroyBuffer real_destroy_buffer = nullptr; PFN_vkDestroyImageView real_destroy_view = nullptr; +PFN_vkBeginCommandBuffer real_begin = nullptr; std::mutex mutex; std::set ours; // the buffers and views the test made unsigned destroyed_buffers = 0; // of ours unsigned destroyed_views = 0; // of ours std::vector events; // bindless slot releases and destructions of our views, in order +std::atomic lose_at_begin{nullptr}; void adopt(std::uint64_t handle) { std::lock_guard lock(mutex); @@ -80,10 +87,18 @@ VKAPI_ATTR void VKAPI_CALL destroy_view(VkDevice device, VkImageView view, const real_destroy_view(device, view, allocator); } +// As another queue's vkQueueSubmit returning VK_ERROR_DEVICE_LOST would, while this batch is past its own checks. +VKAPI_ATTR VkResult VKAPI_CALL begin(VkCommandBuffer command_buffer, const VkCommandBufferBeginInfo* info) { + const VkResult result = real_begin(command_buffer, info); + if (auto* context = lose_at_begin.exchange(nullptr)) context->mark_device_lost("the test marks the device lost"); + return result; +} + VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { const std::string_view n(name); if (n == "vkDestroyBuffer") return reinterpret_cast(destroy_buffer); if (n == "vkDestroyImageView") return reinterpret_cast(destroy_view); + if (n == "vkBeginCommandBuffer") return reinterpret_cast(begin); return real_get_device(device, name); } @@ -91,6 +106,7 @@ void install(PFN_vkGetDeviceProcAddr device_proc, VkDevice device) { real_get_device = device_proc; real_destroy_buffer = reinterpret_cast(device_proc(device, "vkDestroyBuffer")); real_destroy_view = reinterpret_cast(device_proc(device, "vkDestroyImageView")); + real_begin = reinterpret_cast(device_proc(device, "vkBeginCommandBuffer")); } } // namespace driver @@ -183,6 +199,46 @@ int main() { } std::puts("deferred deletion after a loss: buffers freed at once; bindless slots and their views kept, in order"); + // 4 + { + VulkanContext context(driver::get_device, d.device, true); + EXPECT(context.loaded()); + unsigned prepared = 0; + context.set_bindless_prepare([&](VkCommandBuffer) { + ++prepared; + return true; + }); + constexpr VkDeviceSize size = 4096; + const VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + void* map = nullptr; + const VkBuffer a = d.buffer(size, usage, &map), b = d.buffer(size, usage, &map); // d destroys them + EXPECT(a && b); + ResourceBinding binding; + binding.size = size; + binding.buffer = a; + context.add_resource(1, binding); + binding.buffer = b; + context.add_resource(2, binding); + CommandList copy; + EXPECT(copy.copy_buffer({2, 0, 1, 0, size})); + EXPECT(copy.close()); + const CommandList* lists[] = {©}; + auto queue = std::make_unique(context, d.queue, d.family); + EXPECT(queue->ok()); + EXPECT(queue->execute(lists) == ReplayResult::success); + EXPECT(prepared == 1); // a batch on a live device flushes the set + + driver::lose_at_begin = &context; + EXPECT(queue->execute(lists) == ReplayResult::unsupported); + EXPECT(driver::lose_at_begin.load() == nullptr); // the interposer marked the loss, past the first check + EXPECT(context.is_device_lost()); + EXPECT(prepared == 1); + queue.reset(); + context.remove_resource(1); + context.remove_resource(2); + } + std::puts("a batch that takes the tracker lock after the loss stops before the bindless flush"); + EXPECT(d.validation_errors() == 0); std::puts("vk_deferred_destroy_lost: ok"); return 0; From 04d2c93617d96ffc530c21090fad49b420b714fa Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:35:36 +0100 Subject: [PATCH 47/49] leonida-gpu: an arena's take finds the changed dwords only where they go up (RS-ARENA-ONE-COPY) Memory::take runs at a submission, under the memory lock. It had become the scalar dword merge for every page, which builds the runs that changed. Only one case uses those runs: a page that is not taken whole, in an arena whose copy has the arena as its CPU side. Every whole take (each placed page, each packed structure) and every arena on the old path threw them away, at about 2.5 times the cost of the compare and copy that was there before. Now that case finds its runs with shadow's AVX2 word_runs_put, as a refresh finds them. Every other case compares and copies as before. The write watch is no longer told about writes to an opened arena, since nothing asks it about one. The arena test now also takes a page as land() does and checks that the dword the title changed goes up beside the card's own dword. --- d3d12/crates/leonida-gpu/src/memory.rs | 33 ++++++++++++++++++++++---- d3d12/crates/leonida-gpu/src/shadow.rs | 2 +- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/memory.rs b/d3d12/crates/leonida-gpu/src/memory.rs index 2aee650bdd..9fa93f3074 100644 --- a/d3d12/crates/leonida-gpu/src/memory.rs +++ b/d3d12/crates/leonida-gpu/src/memory.rs @@ -684,12 +684,21 @@ impl Memory { crate::host::copy_mapped(title.as_mut_ptr(), (page as usize * PAGE as usize + at) as *const u8, n, false); // SAFETY: a page of an arena of ours, under the mutex. let ours = unsafe { std::slice::from_raw_parts_mut((held.at + at) as *mut u8, n) }; - let runs = merge(&title[..n], ours, false); - if !runs.is_empty() { - crate::watch::wrote(held.at + at, n); - } if shadow.side_is_memory() && !whole { + // Only here do the dwords that changed matter: they are what + // goes up. Found 32 bytes at a time, as a refresh finds them + // (this runs at a submission). + let runs = crate::shadow::word_runs_put(held.at + at, &title[..n], ours); changed.extend(runs.into_iter().map(|(a, len)| (base + at + a, base + at + a + len))); + } else if *ours != title[..n] { + // Sent whole, or compared at the next refresh: what differs + // is not needed here. + ours.copy_from_slice(&title[..n]); + // (Nothing asks the write watch about an arena that is its + // copy's CPU side.) + if !shadow.side_is_memory() { + crate::watch::wrote(held.at + at, n); + } } at += n; } @@ -1470,6 +1479,22 @@ mod tests { assert_eq!(got[10], 0xb11d, "the card's own dword stayed"); assert_eq!(&got[..10], &words[..10], "the page went up whole the first time"); assert_eq!(&got[21..], &words[21..]); + // The same of a page taken at a submission (`land`, of a page not + // in a packed structure): dword 11 on the card's side alone, dword + // 30 changed by the title. + // SAFETY: the mapping, which no copy uses now. + unsafe { data.cast::().write(0xb11e) }; + // SAFETY: as above. + run(&m, &|list| unsafe { list.CopyBufferRegion(&shadow.buffer, offset + 44, &aside, 0, 4) }); + words[30] = 0x7172; + m.take(page, 0, PAGE as usize, false); + // SAFETY: as above. + run(&m, &|list| unsafe { list.CopyBufferRegion(&aside, 0, &shadow.buffer, offset, PAGE) }); + // SAFETY: as above. + let got = unsafe { std::slice::from_raw_parts(data.cast::().cast_const(), PAGE as usize / 4) }; + assert_eq!(got[30], 0x7172, "the dword the title changed went up from `take`"); + assert_eq!((got[10], got[11]), (0xb11d, 0xb11e), "the card's own dwords stayed"); + assert_eq!(got[20], 0x7171); } #[test] diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 283668dc4e..793bd3df36 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -2957,7 +2957,7 @@ unsafe fn word_runs_avx2_in(at: usize, title: &[u8], held: *mut } /// [`word_runs`] of `title` and `held`, and `held` is `title` afterwards. -fn word_runs_put(at: usize, title: &[u8], held: &mut [u8]) -> Vec<(usize, usize)> { +pub(crate) fn word_runs_put(at: usize, title: &[u8], held: &mut [u8]) -> Vec<(usize, usize)> { #[cfg(target_arch = "x86_64")] if title.len() == held.len() && std::arch::is_x86_feature_detected!("avx2") { // SAFETY: the processor has AVX2, and the lengths are the same; `held` From d1fc186929d74bd035143e55c387373953282e2a Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:36:04 +0100 Subject: [PATCH 48/49] leonida-gpu: an opened arena's first send and its race are where they belong (RS-ARENA-ONE-COPY) The whole arena now goes up from Memory::another, once the copy has a number. Before, by_address_with queued it, and a copy that number() then refused left a dead entry in the queue of changed copies. opened_side logs, once, why an arena was not opened, also when the host placed it off a 64 KiB line. Before, that case fell back without a word. It cannot happen for upload::reserve's memory. The SAFETY comment in host/send.rs said that only the thread that asked writes a CPU side. That is no longer true for an opened arena: a recording thread may write it while a submission reads it to send. The comment now says so, and why the card still gets the new bytes. The arena test returns early on a host that cannot open memory as a heap, as the inplace tests do, since the old path is the design there. It also checks that the process memory counters were read. --- d3d12/crates/leonida-gpu/src/host/send.rs | 18 +++++++--- d3d12/crates/leonida-gpu/src/memory.rs | 18 +++++++++- d3d12/crates/leonida-gpu/src/shadow.rs | 44 +++++++++++------------ 3 files changed, 51 insertions(+), 29 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/host/send.rs b/d3d12/crates/leonida-gpu/src/host/send.rs index 32cb70473a..d454f7b082 100644 --- a/d3d12/crates/leonida-gpu/src/host/send.rs +++ b/d3d12/crates/leonida-gpu/src/host/send.rs @@ -232,10 +232,20 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc, Vec<(usize, us let mut to = to as *mut [u32; 2]; for &(a, b) in ranges.iter().filter(|r| short(r)) { for offset in (a..b).step_by(4) { - // SAFETY: inside the copy's mapping (its CPU side, which - // the thread that asked, and waits, alone writes in these - // ranges) and inside the memory, which has room for every - // pair, a piece of work's behind the last one's. + // SAFETY: inside the copy's mapping (its CPU side) and + // inside the memory, which has room for every pair, a piece + // of work's behind the last one's. The thread that asked, + // and waits, alone writes in these ranges of a CPU side, + // but for a side that is memory of ours (`Shadow::opened`, + // an arena of `crate::memory`'s): there a recording thread + // may write a word while it is read here, or while + // `copy_all` below reads its run. Two plain accesses at + // once are a race the language leaves undefined. What the + // processor reads is the old bytes or the new ones, and + // the writer resends what it wrote after it wrote it, so + // the next submission sends the new ones. (Before, a + // refresh read the arena through the kernel while it was + // written, with the same outcome.) unsafe { let word = ((from + offset) as *const u32).read_unaligned(); to.write([offset as u32, word]); diff --git a/d3d12/crates/leonida-gpu/src/memory.rs b/d3d12/crates/leonida-gpu/src/memory.rs index 9fa93f3074..d660c61cf5 100644 --- a/d3d12/crates/leonida-gpu/src/memory.rs +++ b/d3d12/crates/leonida-gpu/src/memory.rs @@ -407,6 +407,11 @@ impl Memory { let Some(n) = crate::shadow::by_address_opened(at as u64, ARENA).and_then(|s| self.number(s)) else { return false; }; + if self.copies[n].side_is_memory() { + // All of it goes up once, as a new copy's first refresh sends it. + // (Once it is numbered: a copy refused here is dropped.) + self.copies[n].resend(0, ARENA as usize); + } self.arenas.push((n, at)); // The lowest first. self.free.extend((0..(ARENA / PAGE) as usize).rev().map(|i| (n, at + i * PAGE as usize))); @@ -1359,7 +1364,9 @@ mod tests { use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut c = PROCESS_MEMORY_COUNTERS { cb: size_of::() as u32, ..Default::default() }; // SAFETY: our own process and a sized structure. - unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + let read = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + // (Failed, every reading would be 0 and nothing measured.) + assert_ne!(read, 0, "the process's memory counters"); c.PagefileUsage as u64 } @@ -1381,6 +1388,15 @@ mod tests { if !crate::shadow::cards() || !host.card_ready() { return; } + // A host that does not open memory as a heap of its own (no + // ID3D12Device13, or a driver that refuses) keeps the CPU's side a + // buffer of its own, as designed. (The block is never let go: the + // heap lets go of its pages a moment after its last reference.) + let block = crate::upload::reserve(1 << 16).expect("a block"); + if let Err(e) = crate::inplace::place_part(&host.device, block as u64, 1 << 16) { + eprintln!("memory is not opened as a heap here ({e:?}): an arena's copy keeps a CPU side of its own"); + return; + } let _turn = arenas_turn(); // Three times each, as other tests make and free memory meanwhile. // First what the copy's side on the card costs by itself (some diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 793bd3df36..0bd3d35f63 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -6328,8 +6328,10 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option> { /// side, so its bytes are in the PC's memory once. That side was a buffer /// of the same size with the same bytes, which every refresh compared with /// the arena: 64 MiB more commit per arena, and with the structure builder -/// (`LEONIDA_BVH_BUILDER=1`) up to 48 arenas. If the host does not open the -/// memory, the copy is made as [`by_address`] makes it. +/// (`LEONIDA_BVH_BUILDER=1`) up to 48 arenas. Its caller resends all of it +/// once it keeps the copy, as a new copy's first refresh sends it. If the +/// host does not open the memory, the copy is made as [`by_address`] makes +/// it. pub(crate) fn by_address_opened(start: u64, len: u64) -> Option> { by_address_with(start, len, true) } @@ -6393,12 +6395,6 @@ fn by_address_with(start: u64, len: u64, open: bool) -> Option> { let shadow = Arc::new(shadow); note_carded(&shadow); elide::made(&shadow); - if shadow.opened.is_some() { - // All of it goes up once, as a new copy's first refresh sends it. - // (Once it is noted: the queue of changed copies names it by its - // place.) - shadow.resend(0, len as usize); - } Some(shadow) } @@ -6406,22 +6402,22 @@ fn by_address_with(start: u64, len: u64, open: bool) -> Option> { /// a buffer placed over it from its first byte, so that the buffer's offsets /// are the copy's (the card's side is filled from it at the same offsets). fn opened_side(host: &crate::host::Host, start: u64, len: u64) -> Option { - match crate::inplace::place_part(&host.device, start, len) { - Ok(placed) if placed.bias == 0 => Some(placed), - Ok(_) => None, - Err(e) => { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!( - start = format_args!("{start:#x}"), - len, - error = ?e, - "memory by address not opened as its copy's CPU side: that side is a buffer of its own, as before" - ); - }); - None - } - } + let why = match crate::inplace::place_part(&host.device, start, len) { + Ok(placed) if placed.bias == 0 => return Some(placed), + // (Not for an arena: `upload::reserve` gives 64 KiB lines.) + Ok(placed) => format!("it begins {:#x} bytes after a 64 KiB line", placed.bias), + Err(e) => format!("{e:?}"), + }; + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!( + start = format_args!("{start:#x}"), + len, + why = %why, + "memory by address not opened as its copy's CPU side: that side is a buffer of its own, as before" + ); + }); + None } /// Copies of title memory outside buffers, by (start, length). From eb145de6fdfaa50cecfc1b12b15691606a69bfff Mon Sep 17 00:00:00 2001 From: adrianmjim <11887815+adrianmjim@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:42:02 +0100 Subject: [PATCH 49/49] leonida-hle: the tests that count allocations share one allocator RS-APU-SCRATCH (apu.rs) and RS-DSTORAGE-SCRATCH (dstorage.rs) each installed a counting #[global_allocator] in their test module, and a binary has one: with both merged, the leonida-hle tests no longer build ("cannot define multiple global allocators"). The allocator moves to src/test_alloc.rs and tells both counters of each block; each module keeps only its counter (apu::tests::counting::note, dstorage::tests::watched_blocks::note). Same features as before: not with diagnostics or mimalloc, where leonida-gpu installs its own. cargo test -p leonida-hle --lib: 189 passed, 2 ignored, including packets_decode_without_memory_of_their_own, compressed_requests_reuse_the_workers_buffers and staging_counts_every_buffer_a_request_holds. --- d3d12/crates/leonida-hle/src/lib.rs | 2 + d3d12/crates/leonida-hle/src/modules/apu.rs | 43 +++-------------- .../leonida-hle/src/modules/dstorage.rs | 47 +++---------------- d3d12/crates/leonida-hle/src/test_alloc.rs | 46 ++++++++++++++++++ 4 files changed, 61 insertions(+), 77 deletions(-) create mode 100644 d3d12/crates/leonida-hle/src/test_alloc.rs diff --git a/d3d12/crates/leonida-hle/src/lib.rs b/d3d12/crates/leonida-hle/src/lib.rs index 57f66b38e6..9493d014f5 100644 --- a/d3d12/crates/leonida-hle/src/lib.rs +++ b/d3d12/crates/leonida-hle/src/lib.rs @@ -19,6 +19,8 @@ pub use leonida_gpu::frame_phase; pub mod modules; mod registry; pub mod runtime; +#[cfg(all(test, not(any(feature = "diagnostics", feature = "mimalloc"))))] +mod test_alloc; pub use host::HostPolicy; pub use registry::{HleExport, HleModule, registry}; diff --git a/d3d12/crates/leonida-hle/src/modules/apu.rs b/d3d12/crates/leonida-hle/src/modules/apu.rs index 81e5bfcaa2..6462444385 100644 --- a/d3d12/crates/leonida-hle/src/modules/apu.rs +++ b/d3d12/crates/leonida-hle/src/modules/apu.rs @@ -434,7 +434,7 @@ pub(crate) fn module() -> HleModule { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use opus_pure::{Application, OpusEncoder}; @@ -559,54 +559,23 @@ mod tests { } /// Counts this thread's allocations of a stereo packet's PCM or larger, - /// for what a packet costs. Not with the allocators the features bring. + /// for what a packet costs. The test binary's allocator (`test_alloc`) + /// tells it of each block. Not with the allocators the features bring. #[cfg(not(any(feature = "diagnostics", feature = "mimalloc")))] - mod counting { - use std::alloc::{GlobalAlloc, Layout, System}; + pub(crate) mod counting { use std::cell::Cell; const LARGE: usize = super::MAX_FRAMES * 2 * size_of::(); std::thread_local! { - pub(super) static COUNT: Cell = const { Cell::new(0) }; + pub(crate) static COUNT: Cell = const { Cell::new(0) }; } - fn note(size: usize) { + pub(crate) fn note(size: usize) { if size >= LARGE { let _ = COUNT.try_with(|n| n.set(n.get() + 1)); } } - - struct Counting; - - // SAFETY: everything goes to the system allocator as it came. - unsafe impl GlobalAlloc for Counting { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - note(layout.size()); - // SAFETY: the caller's contract, passed on. - unsafe { System.alloc(layout) } - } - - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - note(layout.size()); - // SAFETY: as above. - unsafe { System.alloc_zeroed(layout) } - } - - unsafe fn realloc(&self, at: *mut u8, layout: Layout, size: usize) -> *mut u8 { - note(size); - // SAFETY: as above. - unsafe { System.realloc(at, layout, size) } - } - - unsafe fn dealloc(&self, at: *mut u8, layout: Layout) { - // SAFETY: as above. - unsafe { System.dealloc(at, layout) } - } - } - - #[global_allocator] - static HEAP: Counting = Counting; } /// A packet decodes into memory the connection keeps: each of the 50 diff --git a/d3d12/crates/leonida-hle/src/modules/dstorage.rs b/d3d12/crates/leonida-hle/src/modules/dstorage.rs index d43f4530d3..38e3a3bd6e 100644 --- a/d3d12/crates/leonida-hle/src/modules/dstorage.rs +++ b/d3d12/crates/leonida-hle/src/modules/dstorage.rs @@ -1866,7 +1866,7 @@ pub(crate) fn module() -> HleModule { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use std::os::windows::ffi::OsStrExt; use std::time::{Duration, Instant}; @@ -2474,13 +2474,12 @@ mod tests { assert_eq!(out, bc4_blocks()); } - /// The test binary's allocator: the system's, counting the blocks of the - /// sizes a test watches (`compressed_requests_reuse_the_workers_buffers`). - /// Not with the features under which leonida-gpu installs an allocator - /// of its own, since a process has one. + /// Counts the blocks of the sizes a test watches + /// (`compressed_requests_reuse_the_workers_buffers`). The test binary's + /// allocator (`test_alloc`) tells it of each block. Not with the features + /// under which leonida-gpu installs an allocator of its own. #[cfg(not(any(feature = "diagnostics", feature = "mimalloc")))] - mod watched_blocks { - use std::alloc::{GlobalAlloc, Layout, System}; + pub(crate) mod watched_blocks { use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; /// The sizes watched (0: none), and how many blocks of each were @@ -2488,45 +2487,13 @@ mod tests { pub(super) static SIZES: [AtomicUsize; 3] = [const { AtomicUsize::new(0) }; 3]; pub(super) static BLOCKS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; - fn note(size: usize) { + pub(crate) fn note(size: usize) { for (watched, blocks) in SIZES.iter().zip(&BLOCKS) { if size != 0 && watched.load(Relaxed) == size { blocks.fetch_add(1, Relaxed); } } } - - struct Counting; - - // SAFETY: every call goes to the system's allocator unchanged; only - // counters are kept beside it. - unsafe impl GlobalAlloc for Counting { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - note(layout.size()); - // SAFETY: the caller's contract, passed on. - unsafe { System.alloc(layout) } - } - - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - note(layout.size()); - // SAFETY: the caller's contract, passed on. - unsafe { System.alloc_zeroed(layout) } - } - - unsafe fn dealloc(&self, at: *mut u8, layout: Layout) { - // SAFETY: the caller's contract, passed on. - unsafe { System.dealloc(at, layout) } - } - - unsafe fn realloc(&self, at: *mut u8, layout: Layout, size: usize) -> *mut u8 { - note(size); - // SAFETY: the caller's contract, passed on. - unsafe { System.realloc(at, layout, size) } - } - } - - #[global_allocator] - static HEAP: Counting = Counting; } /// Compressed requests run on buffers their worker keeps: the source diff --git a/d3d12/crates/leonida-hle/src/test_alloc.rs b/d3d12/crates/leonida-hle/src/test_alloc.rs new file mode 100644 index 0000000000..dc0036f1ad --- /dev/null +++ b/d3d12/crates/leonida-hle/src/test_alloc.rs @@ -0,0 +1,46 @@ +//! The test binary's allocator: the system's, telling the tests that count +//! allocations of each block (`modules::apu`'s packet test and +//! `modules::dstorage`'s worker buffer test). A process has one allocator, so +//! they share it. Not with the features under which leonida-gpu installs an +//! allocator of its own. + +use std::alloc::{GlobalAlloc, Layout, System}; + +use crate::modules::{apu, dstorage}; + +fn note(size: usize) { + apu::tests::counting::note(size); + dstorage::tests::watched_blocks::note(size); +} + +struct Counting; + +// SAFETY: every call goes to the system's allocator unchanged; only counters +// are kept beside it. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + note(layout.size()); + // SAFETY: the caller's contract, passed on. + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + note(layout.size()); + // SAFETY: the caller's contract, passed on. + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn realloc(&self, at: *mut u8, layout: Layout, size: usize) -> *mut u8 { + note(size); + // SAFETY: the caller's contract, passed on. + unsafe { System.realloc(at, layout, size) } + } + + unsafe fn dealloc(&self, at: *mut u8, layout: Layout) { + // SAFETY: the caller's contract, passed on. + unsafe { System.dealloc(at, layout) } + } +} + +#[global_allocator] +static HEAP: Counting = Counting;