From 71e83d7e2eae29849063dc1eb460ed998a8cd0cb Mon Sep 17 00:00:00 2001 From: requiemsnkrp <317543573+requiemsnkrp@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:58:21 +0100 Subject: [PATCH 1/2] Give a released default-heap buffer's arena range back only after the GPU is done with it (D3D-475) A default-heap buffer is a range of the GPU address arena, and ~Resource handed the range back at once. The next buffer placed there is zero-filled through the arena's host mapping, so a read still in flight saw zeros. Repro (d3d12_arena_retire_test, behaviour of origin/main): queue A copies a 1 MiB buffer to a readback buffer behind a GPU Wait for a fence queue C signals after ~300 ms of copies (C's Signal is submitted first, so nothing is held on the CPU); the buffer is released and a 1 MiB buffer made while the gate is closed: it gets the same VA (0x10000) and the read finds 262144 of 262144 words zero. - vulkan_backend.h: DeferredDeletionQueue::Kind::arena_range ((offset << 32) | bytes, the arena is below 4 GiB) handed to an ArenaReleaseFn set by the device; VulkanContext::set_arena_release and reclaim_retired(wait): with resource_mutex_ and tracker_mutex_ held no submission is between resolving and recording its ticket, so after the last recorded submission completed a later release needs no next one; with `wait` it first waits for the device to go idle. - d3d12_vulkan_device.cpp: ~Resource retires the range through defer_destroy (arena_retire, arena.retiring bytes); the deletion queue gives it back (arena_retired). arena_allocate is unchanged when the range fits; out of room while ranges are retiring it reclaims, then reclaims after a device wait, then fails as before. - d3d12_arena_retire_test (new): the gated read keeps its data and the new buffer gets another range (0x110000); after the read and the submission after it, the next buffer gets 0x10000 back; with LEONIDA_ARENA_MB=16, a 12 MiB buffer made and released 4 times with nothing submitted keeps its range, and one made while a released 12 MiB buffer waits for a gated read waits for the GPU (~280 ms) and gets that range with the read intact (before: 1.4 ms, same range, 3145728 words zero). - docs/d3d12_vulkan.md 3.2: arena ranges of released buffers, the full-arena path, what is not covered. RTX 3060 / 617.14, LEONIDA_VK_VALIDATION=1 with sync validation: 0 messages. AI-assisted. --- docs/d3d12_vulkan.md | 26 +- runtime/CMakeLists.txt | 9 + runtime/shims/d3d12_vulkan_device.cpp | 55 +++- runtime/src/vulkan_backend.h | 43 ++- runtime/test/d3d12_arena_retire_test.cpp | 334 +++++++++++++++++++++++ 5 files changed, 457 insertions(+), 10 deletions(-) create mode 100644 runtime/test/d3d12_arena_retire_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 07db247b0..b3cd3bb97 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -650,6 +650,26 @@ The compute path, end to end: device-addressable buffer, 256 MiB by default (`LEONIDA_ARENA_MB`, at most 4095 MiB, so every VA fits 32-bit table pointers). - Default-heap buffers are 64 KiB-aligned ranges in it, zeroed through its mapping; their console VA is the offset. + - A released default-heap buffer's range goes back through the device's deletion queue, as the buffer's Vulkan + objects do (`DeferredDeletionQueue::Kind::arena_range`, D3D-475): once every submission made before the release, + on any queue, has completed, and the one after it, since a submission that has already resolved the buffer may + still be on its way to `vkQueueSubmit`. It used to go back at once, so the next buffer placed there was + zero-filled through the mapping under a read still in flight. An allocation that finds no room while such ranges + are on their way takes back those the GPU is done with (`VulkanContext::reclaim_retired`: with the resource and + tracker locks held no submission is half-recorded, so a range released after the last recorded submission is + free once that one has completed), then waits for the device to go idle and tries once more; only then is it + `E_OUTOFMEMORY`. Allocations that fit cost what they did. Measured (`d3d12_arena_retire_test`, RTX 3060, driver + 617.14, `LEONIDA_VK_VALIDATION=1` with sync validation, 0 messages): queue A copies a 1 MiB buffer to a readback + buffer behind a `Wait` for a fence queue C signals after about 300 ms of 64 MiB copies, C's `Signal` submitted + first so A's batch is submitted (a GPU wait, not a batch held on the CPU); the buffer is released and a 1 MiB + buffer made while the gate is closed. Before: the new buffer got the released range (VA 0x10000) and the read + found all 262144 words zero. Now: it gets 0x110000, the read matches, and once the read and the submission after + it have completed the next buffer gets 0x10000 back. With a 16 MiB arena, a 12 MiB buffer made and released four + times with nothing submitted gets the same range each time, and one made while a released 12 MiB buffer waits for + a gated read waits for the device (280 ms) and gets that range, where before it took it at once (1.4 ms) and the + read found 3145728 of 3145728 words zero. Not covered: heaps (`CreateHeap`, whose placed buffers are ranges of + the heap's range), shader-visible descriptor heaps and shader code still go back to the arena when the object is + destroyed, as D3D12 lets the layer require of the application for those objects. - 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. @@ -742,9 +762,9 @@ The compute path, end to end: - Only the first viewport and scissor are used, and primitive restart is not modelled yet. **Resources and heaps:** - - A buffer of 0 bytes, or one whose size wraps when aligned, is `E_INVALIDARG`. One the arena cannot hold is - `E_OUTOFMEMORY`, and so is a shader-visible descriptor heap the arena cannot hold (in host memory its GPU - handle would be 0). + - A buffer of 0 bytes, or one whose size wraps when aligned, is `E_INVALIDARG`. One the arena cannot hold, even + after the ranges of released buffers have come back (GPU address arena above, D3D-475), is `E_OUTOFMEMORY`, and + so is a shader-visible descriptor heap the arena cannot hold (in host memory its GPU handle would be 0). - If the arena cannot be created, its buffer is released, so other buffers keep their own memory and get no VA. - With `VK_EXT_conditional_rendering`, the arena is created with the conditional-rendering usage, and `SetPredication` on a default-heap buffer reads at the buffer's offset in the arena plus the call's offset. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index ed946d115..1b9e11e12 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1096,6 +1096,15 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_queue_handover COMMAND d3d12_queue_handover_test) set_tests_properties(d3d12_queue_handover PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 400 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # A default-heap buffer released under a GPU-gated read keeps its arena range until the read is done, and a full + # arena waits for such ranges instead of failing (docs/d3d12_vulkan.md section 4.4, D3D-475). + add_executable(d3d12_arena_retire_test test/d3d12_arena_retire_test.cpp) + target_link_libraries(d3d12_arena_retire_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_arena_retire_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_arena_retire_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_arena_retire COMMAND d3d12_arena_retire_test) + set_tests_properties(d3d12_arena_retire PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") # XDXR acceleration structures through BuildRaytracingAccelerationStructure (docs/d3d12_vulkan.md 4.8): the # device builds them, tools/xdxr_bvh.py checks them. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 2b6d1c806..d31fb74f4 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -467,6 +467,8 @@ struct DeviceState { VkDeviceSize in_use = 0, peak_in_use = 0, peak_end = 0; VkDeviceSize use_in_use[4] = {}, use_peak[4] = {}; std::uint64_t allocations = 0, failures = 0; + // Bytes of released buffers that wait for the submissions made before their release (arena_retire). + VkDeviceSize retiring = 0; } arena; std::uint32_t sparse_buffer_memory_types = 0; @@ -492,9 +494,27 @@ struct DeviceState { // A zero-size range is refused: it would share its offset with the next range, and its release would collide // with that range's free entry. The fit test cannot wrap: free blocks lie inside the arena (below 4 GiB). + // A released buffer's range comes back only once the GPU is done with it (arena_retire); out of room while some + // are on their way, this takes back what is done, then waits for the device to finish and tries once more. bool arena_allocate(VkDeviceSize bytes, VkDeviceSize alignment, VkDeviceSize& out, ArenaUse use) { if (!bytes || bytes > arena.size) return false; - std::lock_guard lock(arena.mutex); + for (int pass = 0;; ++pass) { + { + std::lock_guard lock(arena.mutex); + if (arena_take_locked(bytes, alignment, out, use)) return true; + if (pass == 2 || !arena.retiring || !context) { + ++arena.failures; + if (arena.log) + std::fprintf(stderr, "[rt] d3d12: arena %s: no room for 0x%llx bytes\n", kArenaUseNames[use], + (unsigned long long)bytes); + return false; + } + } + context->reclaim_retired(pass == 1); + } + } + + bool arena_take_locked(VkDeviceSize bytes, VkDeviceSize alignment, VkDeviceSize& out, ArenaUse use) { for (auto it = arena.free.begin(); it != arena.free.end(); ++it) { const VkDeviceSize start = (it->first + alignment - 1) / alignment * alignment; const VkDeviceSize end = it->first + it->second; @@ -515,10 +535,6 @@ struct DeviceState { (unsigned long long)start, (unsigned long long)bytes); return true; } - ++arena.failures; - if (arena.log) - std::fprintf(stderr, "[rt] d3d12: arena %s: no room for 0x%llx bytes\n", kArenaUseNames[use], - (unsigned long long)bytes); return false; } @@ -547,6 +563,10 @@ struct DeviceState { void arena_release(VkDeviceSize offset, VkDeviceSize bytes, ArenaUse use) { if (!bytes) return; std::lock_guard lock(arena.mutex); + arena_release_locked(offset, bytes, use); + } + + void arena_release_locked(VkDeviceSize offset, VkDeviceSize bytes, ArenaUse use) { arena.in_use -= bytes; arena.use_in_use[use] -= bytes; auto it = arena.free.emplace(offset, bytes).first; @@ -562,6 +582,27 @@ struct DeviceState { } } + // A default-heap buffer is destroyed: work submitted before may still read or write its range, and the next + // buffer placed there is zero-filled through the host mapping at once. So the range goes back through the + // device's deletion queue (VulkanContext::defer_destroy, D3D-475) with the buffer's other objects, once every + // submission made before has completed. Offset and size fit the item's 64 bits: the arena is below 4 GiB. + void arena_retire(VkDeviceSize offset, VkDeviceSize bytes) { + if (!bytes) return; + { + std::lock_guard lock(arena.mutex); + arena.retiring += bytes; + } + context->defer_destroy(leonida::DeferredDeletionQueue::Kind::arena_range, (offset << 32) | bytes); + } + + // The deletion queue's DeferredDeletionQueue::ArenaReleaseFn: `user` is the DeviceState. + static void arena_retired(void* user, std::uint64_t offset, std::uint64_t bytes) { + auto& device = *static_cast(user); + std::lock_guard lock(device.arena.mutex); + device.arena.retiring -= bytes; + device.arena_release_locked(offset, bytes, arena_buffer); + } + // The translator's output, loaded on first use. std::mutex library_mutex; bool library_tried = false; @@ -1461,7 +1502,7 @@ class Resource final } if (image_address_) device_.forget_image(image_address_); device_.context->remove_resource(id()); - if (in_arena_) device_.arena_release(arena_offset_, desc_.Width, DeviceState::arena_buffer); + if (in_arena_) device_.arena_retire(arena_offset_, desc_.Width); // back once the GPU is done with it if (image_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image, image_); if (buffer_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::buffer, buffer_); if (memory_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::device_memory, memory_); @@ -4353,6 +4394,7 @@ class Device final arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; state_.context->set_heap_base(arena.address); state_.context->set_zero_page(arena.buffer, 0, kArenaReserved); + state_.context->set_arena_release(&DeviceState::arena_retired, &state_); return true; } @@ -4364,6 +4406,7 @@ class Device final } state_.context->drain_deleted_resources(UINT64_MAX); state_.context->set_bindless_release(nullptr, nullptr); + state_.context->set_arena_release(nullptr, nullptr); } state_.staging_queue.reset(); // it uses the context if (state_.context && state_.bindless) { diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 03ab7ba26..23e2bb5fa 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -389,15 +389,19 @@ class DeferredDeletionQueue { buffer, device_memory, acceleration_structure, + arena_range, // a default-heap buffer's range of the GPU address arena (D3D-475) }; struct Item { std::uint64_t ticket = 0; - std::uint64_t handle = 0; // for bindless_slot: (uint64_t(dimension) << 32) | index + // for bindless_slot: (uint64_t(dimension) << 32) | index; for arena_range: (offset << 32) | bytes, both below + // 4 GiB as the arena is + std::uint64_t handle = 0; Kind kind = Kind::image_view; }; using BindlessReleaseFn = void (*)(void* user, std::uint32_t dimension, std::uint32_t index); + using ArenaReleaseFn = void (*)(void* user, std::uint64_t offset, std::uint64_t bytes); explicit DeferredDeletionQueue(std::size_t initial_capacity = 256) : pending_(next_pow2(initial_capacity)) {} @@ -407,6 +411,13 @@ class DeferredDeletionQueue { bindless_release_user_ = user; } + // Who takes arena_range items back: the device that owns the arena. + void set_arena_release(ArenaReleaseFn fn, void* user) { + std::lock_guard lock(mutex_); + arena_release_fn_ = fn; + arena_release_user_ = user; + } + void push(std::uint64_t retire_ticket, Kind kind, std::uint64_t handle) { if (!handle && kind != Kind::bindless_slot) return; std::lock_guard lock(mutex_); @@ -430,12 +441,16 @@ class DeferredDeletionQueue { void drain(std::uint64_t current_ticket, VkDevice device, const VulkanDeviceFunctions& vk) { BindlessReleaseFn release_fn = nullptr; void* release_user = nullptr; + ArenaReleaseFn arena_fn = nullptr; + void* arena_user = nullptr; std::vector to_destroy; { std::lock_guard lock(mutex_); if (count_ == 0 || pending_[head_].ticket > current_ticket) return; release_fn = bindless_release_fn_; release_user = bindless_release_user_; + arena_fn = arena_release_fn_; + arena_user = arena_release_user_; const std::size_t mask = pending_.size() - 1; while (count_ > 0 && pending_[head_].ticket <= current_ticket) { to_destroy.push_back(pending_[head_]); @@ -473,6 +488,9 @@ class DeferredDeletionQueue { vk.vkDestroyAccelerationStructureKHR( device, reinterpret_cast(item.handle), nullptr); break; + case Kind::arena_range: + if (arena_fn) arena_fn(arena_user, item.handle >> 32, item.handle & 0xFFFFFFFFu); + break; } } } @@ -491,6 +509,8 @@ class DeferredDeletionQueue { std::size_t count_ = 0; BindlessReleaseFn bindless_release_fn_ = nullptr; void* bindless_release_user_ = nullptr; + ArenaReleaseFn arena_release_fn_ = nullptr; + void* arena_release_user_ = nullptr; }; // Centralized single-thread fence dispatcher using Vulkan 1.2 vkWaitSemaphores(VK_SEMAPHORE_WAIT_ANY_BIT). @@ -1205,6 +1225,10 @@ class VulkanContext { deletion_queue_.set_bindless_release(fn, user); } + void set_arena_release(DeferredDeletionQueue::ArenaReleaseFn fn, void* user) { + deletion_queue_.set_arena_release(fn, user); + } + template void defer_destroy(DeferredDeletionQueue::Kind kind, VkHandle handle) { const auto raw = static_cast(reinterpret_cast(handle)); @@ -1244,6 +1268,23 @@ class VulkanContext { retire_tickets_.queue_idle(progress); } + // For an allocator out of room (the GPU address arena, D3D-475): destroys and gives back what is retired now, + // having first waited for the device to finish everything submitted when `wait` is set. With resource_mutex_ and + // tracker_mutex_ held no submission is between resolving resources and recording its ticket, so once every + // recorded submission has completed, what was released after the last of them no longer waits for the next one. + void reclaim_retired(bool wait) { + std::unique_lock resource_lock(resource_mutex_); + std::lock_guard tracker_lock(tracker_mutex_); + if (wait && !is_device_lost()) { + std::lock_guard submit(submit_mutex_); // vkDeviceWaitIdle needs every VkQueue externally synchronized + if (vk.vkDeviceWaitIdle(device_) == VK_ERROR_DEVICE_LOST) mark_device_lost(); + } + const std::uint64_t submitted = submitted_ticket_.load(std::memory_order_acquire); + const std::uint64_t done = completed_retire_ticket(); + if (is_device_lost()) return; + deletion_queue_.drain(done == submitted ? done + 1 : done, device_, vk); + } + VulkanDeviceFunctions vk; // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. diff --git a/runtime/test/d3d12_arena_retire_test.cpp b/runtime/test/d3d12_arena_retire_test.cpp new file mode 100644 index 000000000..9a800cfad --- /dev/null +++ b/runtime/test/d3d12_arena_retire_test.cpp @@ -0,0 +1,334 @@ +// A default-heap buffer released while a submission that reads it is still in flight (D3D-475, docs/d3d12_vulkan.md +// sections 3.3 and 4.4). Such buffers are ranges of the GPU address arena, zero-filled through its host mapping when +// they are made, so a released buffer's range must not go to the next buffer before the GPU is done with it. +// +// The read is held back by the GPU, not by the CPU: queue A waits for a fence that queue C signals after a run of +// 64 MiB copies between host buffers (the gate, sized from a measured run to last about 300 ms). C's Signal is +// submitted first, so A's batch is submitted at once with a Vulkan wait (nothing is held, queue_holds.h). While the +// gate is closed the buffer is released and one of the same size is made. Checked: +// 1. the new buffer gets another range and A reads the released buffer's data, not the new buffer's zeros; +// 2. once A has completed (and the submission after the release), the next buffer gets the released range back; +// 3. with a 16 MiB arena: a 12 MiB buffer made and released four times with nothing submitted gets the same range +// each time, and one made while a released 12 MiB buffer still waits for a gated read waits for the GPU and +// gets that range, instead of failing or taking it under the read. +// No game data. +#include "../shims/d3d12_com.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace { + +constexpr UINT64 kGateBytes = 64ull << 20; +constexpr double kGateMs = 300; +bool skipped = false; // no Vulkan device or queues: exit 77 + +#define CHECK(c) \ + do { \ + if (!(c)) { \ + std::fprintf(stderr, "line %d: check failed: %s\n", __LINE__, #c); \ + return false; \ + } \ + } while (0) + +std::uint32_t pattern(std::uint32_t seed, std::uint64_t i) { + std::uint32_t x = seed * 0x9e3779b1u + std::uint32_t(i) * 0x85ebca6bu + 0x1234567u; + x ^= x >> 15; x *= 0x2c1b3c6du; x ^= x >> 12; x *= 0x297a2d39u; x ^= x >> 15; + return x | 0x01000000u; // never zero, so a zero-filled range cannot match +} + +double ms_since(std::chrono::steady_clock::time_point start) { + return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); +} + +ComPtr make_buffer(ID3D12Device* device, D3D12_HEAP_TYPE type, UINT64 bytes) { + D3D12_HEAP_PROPERTIES heap{type}; + 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; + const D3D12_RESOURCE_STATES state = type == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ + : type == D3D12_HEAP_TYPE_READBACK ? D3D12_RESOURCE_STATE_COPY_DEST + : D3D12_RESOURCE_STATE_COMMON; + ComPtr resource; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(&resource)))) + return {}; + return resource; +} + +bool fill(ID3D12Resource* upload, std::uint32_t seed, UINT64 bytes) { + std::uint32_t* words = nullptr; + const D3D12_RANGE none{0, 0}; + if (FAILED(upload->Map(0, &none, reinterpret_cast(&words)))) return false; + for (UINT64 i = 0; i < bytes / 4; ++i) words[i] = pattern(seed, i); + upload->Unmap(0, nullptr); + return true; +} + +// The number of words of `readback` that differ from the pattern (3 printed). +UINT64 differences(ID3D12Resource* readback, std::uint32_t seed, UINT64 bytes) { + void* data = nullptr; + if (FAILED(readback->Map(0, nullptr, &data))) return bytes / 4; + const auto* words = static_cast(data); + UINT64 bad = 0; + for (UINT64 i = 0; i < bytes / 4; ++i) + if (words[i] != pattern(seed, i) && bad++ < 3) + std::fprintf(stderr, "word %llu: got %08x want %08x\n", static_cast(i), words[i], + pattern(seed, i)); + const D3D12_RANGE none{0, 0}; + readback->Unmap(0, &none); + return bad; +} + +void wait(ID3D12Fence* fence, UINT64 value) { + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (event && SUCCEEDED(fence->SetEventOnCompletion(value, event)) && + WaitForSingleObject(event, 30000) == WAIT_OBJECT_0) { + CloseHandle(event); + return; + } + // A stuck queue can keep the destructors blocked: end the process without cleaning up. + std::fprintf(stderr, "fence never reached %llu (completed %llu)\n", static_cast(value), + static_cast(fence->GetCompletedValue())); + std::fflush(stderr); + std::_Exit(1); +} + +D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, + D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + return barrier; +} + +// One device: a COPY queue that runs the gate and a DIRECT queue (the reader) that copies behind it. +struct Rig { + ComPtr device; + ComPtr gate_queue, reader; + ComPtr gate, done; + UINT64 gate_value = 0, done_value = 0; + ComPtr gate_src, gate_dst; + UINT gate_copies = 2; + std::vector> allocators; + std::vector> lists; + + // 77: no Vulkan device (skipped), 1: failure, 0: ready. + int init() { + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device)))) return 77; + D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_COPY}; + if (FAILED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&gate_queue)))) return 77; + desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + if (FAILED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&reader)))) return 77; + if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done)))) + return 1; + gate_src = make_buffer(device.Get(), D3D12_HEAP_TYPE_UPLOAD, kGateBytes); + gate_dst = make_buffer(device.Get(), D3D12_HEAP_TYPE_READBACK, kGateBytes); + return gate_src && gate_dst ? 0 : 1; + } + + ID3D12GraphicsCommandList* begin(D3D12_COMMAND_LIST_TYPE type) { + ComPtr allocator; + ComPtr list; + if (FAILED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator))) || + FAILED(device->CreateCommandList(0, type, allocator.Get(), nullptr, IID_PPV_ARGS(&list)))) + return nullptr; + allocators.push_back(allocator); + lists.push_back(list); + return list.Get(); + } + + // A closed reader list that copies `bytes` from `src` to `dst`, moving a default-heap side out of COMMON and back. + ID3D12GraphicsCommandList* copy(ID3D12Resource* dst, ID3D12Resource* src, UINT64 bytes, bool dst_default) { + ID3D12GraphicsCommandList* list = begin(D3D12_COMMAND_LIST_TYPE_DIRECT); + if (!list) return nullptr; + ID3D12Resource* side = dst_default ? dst : src; + const D3D12_RESOURCE_STATES state = + dst_default ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COPY_SOURCE; + const auto in = transition(side, D3D12_RESOURCE_STATE_COMMON, state); + const auto out = transition(side, state, D3D12_RESOURCE_STATE_COMMON); + list->ResourceBarrier(1, &in); + list->CopyBufferRegion(dst, 0, src, 0, bytes); + list->ResourceBarrier(1, &out); + return SUCCEEDED(list->Close()) ? list : nullptr; + } + + // Submits `list` on the reader followed by Signal(done); returns the value, 0 on failure. + UINT64 submit(ID3D12GraphicsCommandList* list) { + if (!list) return 0; + ID3D12CommandList* batch[] = {list}; + reader->ExecuteCommandLists(1, batch); + return SUCCEEDED(reader->Signal(done.Get(), ++done_value)) ? done_value : 0; + } + + bool run(ID3D12GraphicsCommandList* list) { + const UINT64 value = submit(list); + if (value) wait(done.Get(), value); + return value != 0; + } + + // The gate on the COPY queue: `gate_copies` copies of 64 MiB from an upload to a readback buffer, one after the + // other (a null aliasing barrier between them is a full memory barrier), then Signal(gate). Returns the value. + UINT64 submit_gate() { + ID3D12GraphicsCommandList* list = begin(D3D12_COMMAND_LIST_TYPE_COPY); + if (!list) return 0; + D3D12_RESOURCE_BARRIER between{}; + between.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + for (UINT i = 0; i < gate_copies; ++i) { + if (i) list->ResourceBarrier(1, &between); + list->CopyBufferRegion(gate_dst.Get(), 0, gate_src.Get(), 0, kGateBytes); + } + if (FAILED(list->Close())) return 0; + ID3D12CommandList* batch[] = {list}; + gate_queue->ExecuteCommandLists(1, batch); + return SUCCEEDED(gate_queue->Signal(gate.Get(), ++gate_value)) ? gate_value : 0; + } + + // Times two gate copies and sizes the gate to about kGateMs. + bool calibrate() { + gate_copies = 2; + const auto start = std::chrono::steady_clock::now(); + const UINT64 value = submit_gate(); + if (!value) return false; + wait(gate.Get(), value); + const double ms = std::max(ms_since(start), 0.5); + gate_copies = std::clamp(UINT(2 * kGateMs / ms) + 1, 2u, 400u); + std::printf("gate: 2 copies of 64 MiB took %.1f ms, so %u copies\n", ms, gate_copies); + return true; + } + + // Puts `list` (the read) on the reader behind the gate. Returns the read's done value. + UINT64 gated(ID3D12GraphicsCommandList* list, UINT64& gate_at) { + gate_at = submit_gate(); + if (!gate_at || FAILED(reader->Wait(gate.Get(), gate_at))) return 0; + return submit(list); + } + + bool gate_closed(UINT64 at) const { return gate->GetCompletedValue() < at; } +}; + +// 1 and 2: a 1 MiB buffer released under a gated read, on the default arena. +bool in_flight_read() { + Rig rig; + if (const int status = rig.init()) return skipped = status == 77; + ID3D12Device* device = rig.device.Get(); + constexpr UINT64 bytes = 1ull << 20; + auto upload = make_buffer(device, D3D12_HEAP_TYPE_UPLOAD, bytes); + auto readback = make_buffer(device, D3D12_HEAP_TYPE_READBACK, bytes); + auto released = make_buffer(device, D3D12_HEAP_TYPE_DEFAULT, bytes); + CHECK(upload && readback && released && fill(upload.Get(), 1, bytes)); + CHECK(rig.run(rig.copy(released.Get(), upload.Get(), bytes, true))); + CHECK(rig.calibrate()); + + UINT64 gate = 0; + const UINT64 read = rig.gated(rig.copy(readback.Get(), released.Get(), bytes, false), gate); + CHECK(read); + CHECK(rig.gate_closed(gate)); // else the gate is too short to show anything + const D3D12_GPU_VIRTUAL_ADDRESS va = released->GetGPUVirtualAddress(); + released.Reset(); + auto next = make_buffer(device, D3D12_HEAP_TYPE_DEFAULT, bytes); // zero-filled through the host mapping + CHECK(next); + const D3D12_GPU_VIRTUAL_ADDRESS next_va = next->GetGPUVirtualAddress(); + const bool closed = rig.gate_closed(gate); + wait(rig.done.Get(), read); + const UINT64 bad = differences(readback.Get(), 1, bytes); + std::printf("in-flight read: released buffer at VA 0x%llx; a buffer of the same size made while the gate was %s " + "got VA 0x%llx; the gated read found %llu of %llu words wrong\n", + static_cast(va), closed ? "closed" : "already open", + static_cast(next_va), static_cast(bad), + static_cast(bytes / 4)); + CHECK(closed); + CHECK(next_va != va); + CHECK(bad == 0); + + // The read has completed. The release also waits for the submission after the last one made before it: the + // next run is that one, and the one after it gives the range back when it starts. + CHECK(rig.run(rig.copy(next.Get(), upload.Get(), bytes, true))); + CHECK(rig.run(rig.copy(next.Get(), upload.Get(), bytes, true))); + auto again = make_buffer(device, D3D12_HEAP_TYPE_DEFAULT, bytes); + CHECK(again); + std::printf("after the read completed: the next 1 MiB buffer got VA 0x%llx\n", + static_cast(again->GetGPUVirtualAddress())); + CHECK(again->GetGPUVirtualAddress() == va); + return true; +} + +// 3: a 16 MiB arena, 12 MiB buffers. +bool small_arena() { + Rig rig; + _putenv_s("LEONIDA_ARENA_MB", "16"); + const int status = rig.init(); + _putenv_s("LEONIDA_ARENA_MB", ""); + if (status) return skipped = status == 77; + ID3D12Device* device = rig.device.Get(); + constexpr UINT64 bytes = 12ull << 20; + + D3D12_GPU_VIRTUAL_ADDRESS churn_va = 0; + for (int i = 0; i < 4; ++i) { // nothing submitted: each release is free for the next buffer at once + auto buffer = make_buffer(device, D3D12_HEAP_TYPE_DEFAULT, bytes); + CHECK(buffer); + if (!i) churn_va = buffer->GetGPUVirtualAddress(); + CHECK(buffer->GetGPUVirtualAddress() == churn_va); + } + std::printf("16 MiB arena: a 12 MiB buffer made and released 4 times with nothing submitted: VA 0x%llx each time\n", + static_cast(churn_va)); + + auto upload = make_buffer(device, D3D12_HEAP_TYPE_UPLOAD, bytes); + auto readback = make_buffer(device, D3D12_HEAP_TYPE_READBACK, bytes); + auto released = make_buffer(device, D3D12_HEAP_TYPE_DEFAULT, bytes); + CHECK(upload && readback && released && fill(upload.Get(), 2, bytes)); + CHECK(!make_buffer(device, D3D12_HEAP_TYPE_DEFAULT, bytes)); // the arena holds one such buffer, not two + CHECK(rig.run(rig.copy(released.Get(), upload.Get(), bytes, true))); + CHECK(rig.calibrate()); + + UINT64 gate = 0; + const UINT64 read = rig.gated(rig.copy(readback.Get(), released.Get(), bytes, false), gate); + CHECK(read); + CHECK(rig.gate_closed(gate)); + const D3D12_GPU_VIRTUAL_ADDRESS va = released->GetGPUVirtualAddress(); + released.Reset(); + const auto start = std::chrono::steady_clock::now(); + auto next = make_buffer(device, D3D12_HEAP_TYPE_DEFAULT, bytes); + const double ms = ms_since(start); + const bool waited = !rig.gate_closed(gate); + CHECK(next); + wait(rig.done.Get(), read); + const UINT64 bad = differences(readback.Get(), 2, bytes); + std::printf("16 MiB arena: a 12 MiB buffer made while a released one waited for a gated read took %.1f ms " + "(gate %s when it returned), got VA 0x%llx (released: 0x%llx); the read found %llu of %llu words " + "wrong\n", + ms, waited ? "open" : "still closed", static_cast(next->GetGPUVirtualAddress()), + static_cast(va), static_cast(bad), + static_cast(bytes / 4)); + CHECK(waited); + CHECK(next->GetGPUVirtualAddress() == va); + CHECK(bad == 0); + return true; +} + +} // namespace + +int main() { + const bool in_flight = in_flight_read(); + const bool arena_16 = !skipped && small_arena(); + if (skipped) { + std::puts("no Vulkan device with a COPY and a DIRECT queue: skipped"); + return 77; + } + const bool ok = in_flight && arena_16; + std::puts(ok ? "arena ranges of released buffers came back only after the GPU was done with them" : "FAILED"); + return ok ? 0 : 1; +} From 10993a6fa71e85ae28139e2e97950d5ffffae176 Mon Sep 17 00:00:00 2001 From: requiemsnkrp <317543573+requiemsnkrp@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:34:37 +0100 Subject: [PATCH 2/2] d3d12_arena_retire_test: run the gate on the DIRECT queue when the device gives no second queue Review of #4607 (@ligmaSec): llvmpipe exposes one Vulkan queue, so creating the COPY gate queue failed and the test exited 77. Rig::init() now creates the DIRECT reader first, then tries a COPY queue for the gate; without one the gate runs on the reader itself, recorded as DIRECT lists in submit_gate(), ahead of the gated read, so the host-write regression is still caught. The test prints which mode it used. RTX 3060 / 617.14, LEONIDA_VK_VALIDATION=1 with sync validation, 0 messages in every run: - two queues: new buffer 0x110000 (released 0x10000), 0 of 262144 words wrong, range back after the read; 16 MiB arena wait 288.6 ms, 0 of 3145728 wrong; exit 0. - one queue (COPY creation skipped by a local, uncommitted override): 0x110000, 0 of 262144 wrong, range back; wait 296.3 ms, 0 of 3145728 wrong; exit 0. With the range released at once in ~Resource (control): 0x10000 under the closed gate, 262144 of 262144 wrong; 1.4 ms, 3145728 of 3145728 wrong; exit 1. AI-assisted. --- runtime/test/d3d12_arena_retire_test.cpp | 27 +++++++++++++++--------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/runtime/test/d3d12_arena_retire_test.cpp b/runtime/test/d3d12_arena_retire_test.cpp index 9a800cfad..b139e136c 100644 --- a/runtime/test/d3d12_arena_retire_test.cpp +++ b/runtime/test/d3d12_arena_retire_test.cpp @@ -4,8 +4,9 @@ // // The read is held back by the GPU, not by the CPU: queue A waits for a fence that queue C signals after a run of // 64 MiB copies between host buffers (the gate, sized from a measured run to last about 300 ms). C's Signal is -// submitted first, so A's batch is submitted at once with a Vulkan wait (nothing is held, queue_holds.h). While the -// gate is closed the buffer is released and one of the same size is made. Checked: +// submitted first, so A's batch is submitted at once with a Vulkan wait (nothing is held, queue_holds.h). C is a COPY +// queue; on a device that gives a single queue (llvmpipe) the gate runs on A itself, DIRECT, ahead of the read. While +// the gate is closed the buffer is released and one of the same size is made. Checked: // 1. the new buffer gets another range and A reads the released buffer's data, not the new buffer's zeros; // 2. once A has completed (and the submission after the release), the next buffer gets the released range back; // 3. with a 16 MiB arena: a 12 MiB buffer made and released four times with nothing submitted gets the same range @@ -30,7 +31,7 @@ namespace { constexpr UINT64 kGateBytes = 64ull << 20; constexpr double kGateMs = 300; -bool skipped = false; // no Vulkan device or queues: exit 77 +bool skipped = false; // no Vulkan device or no DIRECT queue: exit 77 #define CHECK(c) \ do { \ @@ -118,6 +119,7 @@ D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATE struct Rig { ComPtr device; ComPtr gate_queue, reader; + D3D12_COMMAND_LIST_TYPE gate_type = D3D12_COMMAND_LIST_TYPE_COPY; ComPtr gate, done; UINT64 gate_value = 0, done_value = 0; ComPtr gate_src, gate_dst; @@ -128,10 +130,15 @@ struct Rig { // 77: no Vulkan device (skipped), 1: failure, 0: ready. int init() { if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device)))) return 77; - D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_COPY}; - if (FAILED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&gate_queue)))) return 77; - desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; if (FAILED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&reader)))) return 77; + desc.Type = D3D12_COMMAND_LIST_TYPE_COPY; + if (FAILED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&gate_queue)))) { + gate_queue = reader; // one queue: the gate goes ahead of the read on it + gate_type = D3D12_COMMAND_LIST_TYPE_DIRECT; + } + std::printf("gate on %s\n", gate_queue == reader ? "the reader's DIRECT queue (no second queue)" + : "a COPY queue, the read on a DIRECT one"); if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate))) || FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done)))) return 1; @@ -180,10 +187,10 @@ struct Rig { return value != 0; } - // The gate on the COPY queue: `gate_copies` copies of 64 MiB from an upload to a readback buffer, one after the - // other (a null aliasing barrier between them is a full memory barrier), then Signal(gate). Returns the value. + // The gate on its queue: `gate_copies` copies of 64 MiB from an upload to a readback buffer, one after the other + // (a null aliasing barrier between them is a full memory barrier), then Signal(gate). Returns the value. UINT64 submit_gate() { - ID3D12GraphicsCommandList* list = begin(D3D12_COMMAND_LIST_TYPE_COPY); + ID3D12GraphicsCommandList* list = begin(gate_type); if (!list) return 0; D3D12_RESOURCE_BARRIER between{}; between.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; @@ -325,7 +332,7 @@ int main() { const bool in_flight = in_flight_read(); const bool arena_16 = !skipped && small_arena(); if (skipped) { - std::puts("no Vulkan device with a COPY and a DIRECT queue: skipped"); + std::puts("no Vulkan device with a DIRECT queue: skipped"); return 77; } const bool ok = in_flight && arena_16;