diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 7bd8dd2555..2401c50067 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1727,10 +1727,17 @@ The copies: one included, and on the thread whose copy faulted it does not take that lock again (an SRW lock is not recursive; on 621.40 the title's submitting thread hung there for good, the main loop frozen with no device loss). Up to 8,192 ranges and 64 MiB a submission (a V# has no read/write bit, so every view - reached is compared; past the caps the ranges are left behind, logged once). `LEONIDA_TITLE_WRITEBACK=0` turns it off. A batch is fenced: it is kept with the ticket - of the submission that will use it and copied back only when the context reports that ticket retired, so a range - another submission is still writing is never read half done. A queue held deep (console ordering) can leave batches - waiting: past 64 of them the oldest go back without their ticket, logged once. + reached is compared; past the caps the ranges are left behind, logged once). `LEONIDA_TITLE_WRITEBACK=0` turns it off. + Each batch records the predicted next submission ticket (`submitted_retire_ticket() + 1`) before its writer + submits. Copy-back waits until the context's completed retirement prefix reaches that recorded ticket. This + removes the backlog-based bypass; it does not establish per-writer isolation across concurrent queues or snapshot + the shadow bytes, which later overlapping writers may change. A queue held deep (console ordering) can leave more + than 64 batches waiting even while another queue finishes its own work: those ranges stay pending until their + recorded tickets retire. The refresh does not wait for them while holding the shadow lock, which another queue may need + to submit the work that releases the dependency. Pending range metadata can grow during a stall; queue length + never substitutes for GPU completion. `d3d12_writeback_retirement` holds one of two Vulkan queues at a timeline + semaphore, checks that 130 batches on the other queue do not write back early, then releases it and checks that + a refresh with no new reached range copies the retained result back. No shaders or game files are needed. - A **window that is refused** (the budget is spent, the arena is full, or the pages are not committed yet) is backed by a persistent geometry copy of exactly the requested range (`LEONIDA_GEOMETRY_MB`) instead; when no copy can be made either, the view is written with **no base and no records** — loads return 0 and stores are dropped. A raw diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 4cbe50acb2..40b9ae462c 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3027,6 +3027,14 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_descriptor COMMAND d3d12_descriptor_test) set_tests_properties(d3d12_descriptor PROPERTIES SKIP_RETURN_CODE 77) + # A held queue must not let >64 pending title-shadow batches bypass retirement (no shader tools needed). + add_executable(d3d12_writeback_retirement_test test/d3d12_writeback_retirement_test.cpp) + target_link_libraries(d3d12_writeback_retirement_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_writeback_retirement_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_writeback_retirement_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_writeback_retirement COMMAND d3d12_writeback_retirement_test) + set_tests_properties(d3d12_writeback_retirement PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + # Console descriptor heap T# binding rules and per-reason refusal tracking (RT-UNBOUND-TSHARP-REASONS). add_executable(d3d12_unbound_tsharp_rules_test test/d3d12_unbound_tsharp_rules_test.cpp) target_link_libraries(d3d12_unbound_tsharp_rules_test PRIVATE gta6rt_d3d12_com) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 37d1d007ee..1f9dde9c7f 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3065,8 +3065,6 @@ struct DeviceState { std::uint64_t title_write_back_bytes = 0; // queued for this submission std::uint64_t title_write_back_total = 0; // copied back, all submissions std::uint64_t title_write_back_calls = 0; // log line count - std::uint64_t title_write_back_unfenced = 0; - static constexpr std::size_t kTitleWriteBackBatches = 64; // pending batches before the oldest goes back unfenced static constexpr std::size_t kTitleWriteBackRanges = 8192; // ranges kept per submission static constexpr std::uint64_t kTitleWriteBackBytes = 64ull << 20; // bytes copied back per submission // The stream pools' mappings (title_gpu_views): one per readable run of a pool. A window is kept for the device's @@ -3333,20 +3331,15 @@ struct DeviceState { title_write_back.clear(); title_write_back_bytes = 0; } - bool forced = false; + // Backlog is not completion: another queue may finish arbitrarily many submissions while the oldest + // ticket waits on a console dependency. Keep their ranges until the completed prefix reaches them. + // Do not wait here: shadow_mutex is held, and the queue that releases that dependency may need it. while (!title_write_back_pending.empty() && - (title_write_back_pending.front().first <= done || - title_write_back_pending.size() > kTitleWriteBackBatches)) { - forced = forced || title_write_back_pending.front().first > done; + title_write_back_pending.front().first <= done) { for (const auto& [begin, end] : title_write_back_pending.front().second) finished.push_back({begin, end}); title_write_back_pending.pop_front(); } - // A queue held deep (console ordering) can leave batches waiting: the oldest go back anyway, once each. - if (forced && !title_write_back_unfenced++) - log_once("more than 64 title write-back batches wait on their submissions: the oldest are copied " - "back without their ticket; batches:", - 1); } if (finished.empty()) return; std::uint64_t written = 0, ranges = 0; diff --git a/runtime/test/d3d12_writeback_retirement_test.cpp b/runtime/test/d3d12_writeback_retirement_test.cpp new file mode 100644 index 0000000000..42a4f04a7a --- /dev/null +++ b/runtime/test/d3d12_writeback_retirement_test.cpp @@ -0,0 +1,200 @@ +// A held queue keeps the global retirement prefix behind >64 completed submissions on another queue. +// Title-shadow writeback must wait for that prefix, without blocking the queue that can release it. +// Synthetic buffers and transfer commands only: no shaders or game data. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../src/title_va_alias.h" + +#include +#include +#include + +#define CHECK(expr) do { if (!(expr)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0) + +namespace { +constexpr std::uint32_t kBatches = 130; +constexpr std::uint32_t kStride = 4096; // separate tracker pages; range-coalescing behavior is outside this test +constexpr std::uint32_t kBytes = ((kBatches + 15) / 16) * 65536; +template struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T* operator->() const { return p; } +}; + +D3D12_RESOURCE_DESC buffer_desc() { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = kBytes; + desc.Height = 1; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return desc; +} + +// Declared after the D3D12 objects: even a failed assertion releases the native queue before their teardown waits. +struct Gate { + vktest::Device& vk; + VkSemaphore semaphore = VK_NULL_HANDLE; + bool released = false; + template T proc(const char* name) { return reinterpret_cast(vk.device_proc(vk.device, name)); } + bool release() { + if (!semaphore || released) return true; + VkSemaphoreSignalInfo signal{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; + signal.semaphore = semaphore; + signal.value = 1; + released = proc("vkSignalSemaphore")(vk.device, &signal) == VK_SUCCESS; + return released; + } + ~Gate() { + if (semaphore) { + release(); + proc("vkDeviceWaitIdle")(vk.device); + proc("vkDestroySemaphore")(vk.device, semaphore, nullptr); + } + } +}; + +int run(vktest::Device& vk) { + 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.command_queues = vk.queues; + info.buffer_device_address = true; + // No host imports: the title buffer must have a shadow, regardless of driver import support. + info.host_pointer_alignment = 0; + Ref device; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + Ref held, running; + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&held.p)))); + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&running.p)))); + Ref held_allocator, allocator; + Ref held_list, list; + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&held_allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, held_allocator.p, nullptr, + IID_PPV_ARGS(&held_list.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + Ref fence; + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + CHECK(event); + struct Event { HANDLE value; ~Event() { CloseHandle(value); } } close_event{event}; + struct Pages { + void* value = VirtualAlloc(nullptr, kBytes, MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE); + Pages() { + if (value) leonida::title_va_aliases().add_title_memory(reinterpret_cast(value), kBytes); + } + ~Pages() { + if (value) { + leonida::title_va_aliases().remove_title_memory(reinterpret_cast(value)); + VirtualFree(value, 0, MEM_RELEASE); + } + } + } pages; + CHECK(pages.value); + auto* words = static_cast(pages.value); + const auto va = reinterpret_cast(pages.value); + Ref title, upload, other; + const auto desc = buffer_desc(); + CHECK(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, pages.value, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&title.p)))); + CHECK(rt::d3d12::title_shadow_buffer(title.p)); + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + CHECK(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + CHECK(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&other.p)))); + constexpr std::uint32_t expected = 0x12345678; + void* mapped = nullptr; + CHECK(SUCCEEDED(upload->Map(0, nullptr, &mapped))); + for (std::uint32_t i = 0; i < kBatches; ++i) { + const std::uint32_t word = expected + i; + std::memcpy(static_cast(mapped) + kStride * i, &word, sizeof(word)); + } + upload->Unmap(0, nullptr); + + // Block queue 0 at a real timeline semaphore, outside D3D12's host-held console waits. + Gate gate{vk}; + VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; + type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; + VkSemaphoreCreateInfo create{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; + CHECK(gate.proc("vkCreateSemaphore")(vk.device, &create, nullptr, &gate.semaphore) == VK_SUCCESS); + const std::uint64_t value = 1; + VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + timeline.waitSemaphoreValueCount = 1; + timeline.pWaitSemaphoreValues = &value; + const VkPipelineStageFlags stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + VkSubmitInfo wait{VK_STRUCTURE_TYPE_SUBMIT_INFO, &timeline}; + wait.waitSemaphoreCount = 1; + wait.pWaitSemaphores = &gate.semaphore; + wait.pWaitDstStageMask = &stage; + CHECK(gate.proc("vkQueueSubmit")(vk.queues[0], 1, &wait, VK_NULL_HANDLE) == VK_SUCCESS); + held_list->CopyBufferRegion(other.p, 0, upload.p, 0, sizeof(expected)); + CHECK(held_list->Close() == S_OK); + ID3D12CommandList* held_lists[] = {held_list.p}; + held->ExecuteCommandLists(1, held_lists); + CHECK(rt::d3d12::last_execute_result(held.p) == leonida::ReplayResult::success); + + CHECK(list->Close() == S_OK); + for (std::uint64_t pass = 1; pass <= kBatches; ++pass) { + const auto offset = kStride * (pass - 1); // distinct pages: dropping the oldest ranges must also fail + CHECK(allocator->Reset() == S_OK); + CHECK(list->Reset(allocator.p, nullptr) == S_OK); + list->CopyBufferRegion(title.p, offset, upload.p, offset, sizeof(expected)); + CHECK(list->Close() == S_OK); + // The notification a bound title-memory V# would make; the transfer supplies its synthetic GPU write. + leonida::title_va_aliases().note_reached(va + offset, sizeof(expected)); + ID3D12CommandList* lists[] = {list.p}; + running->ExecuteCommandLists(1, lists); + CHECK(rt::d3d12::last_execute_result(running.p) == leonida::ReplayResult::success); + CHECK(SUCCEEDED(running->Signal(fence.p, pass))); + CHECK(SUCCEEDED(fence->SetEventOnCompletion(pass, event))); + CHECK(WaitForSingleObject(event, 5000) == WAIT_OBJECT_0); + for (std::uint32_t i = 0; i < kBatches; ++i) + if (words[(kStride / 4) * i] != 0) { + std::fprintf(stderr, "premature title writeback on refresh %llu (first queue still held)\n", + static_cast(pass)); + return 1; + } + } + CHECK(gate.release()); + CHECK(gate.proc("vkDeviceWaitIdle")(vk.device) == VK_SUCCESS); + // No new range is noted: a refresh must drain the retained backlog even without a current write. + CHECK(allocator->Reset() == S_OK); + CHECK(list->Reset(allocator.p, nullptr) == S_OK); + CHECK(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + running->ExecuteCommandLists(1, lists); + CHECK(rt::d3d12::last_execute_result(running.p) == leonida::ReplayResult::success); + std::uint32_t matched = 0; + for (std::uint32_t i = 0; i < kBatches; ++i) matched += words[(kStride / 4) * i] == expected + i; + std::printf("retired writeback results: %u/%u matched\n", matched, kBatches); + CHECK(matched == kBatches); + std::puts("130 pending writeback batches stayed fenced and drained after release"); + return 0; +} +} // namespace + +int main() { + vktest::Device vk; + vk.queue_count_wanted = 2; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + if (vk.queues.size() < 2) { + std::puts("SKIP: needs two graphics-family Vulkan queues"); + return 77; + } + const int result = run(vk); + return result || vk.validation_errors() ? 1 : 0; +}