From 969fa03da7db21ea0fd572c81e12d9c9708e785b Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:27:18 +0500 Subject: [PATCH 1/5] startup: reuse completed upload ring chunks after GPU execution In #2823 (commit 7256cecf), uncompleted reuse of the shared upload ring was removed to prevent GPU in-flight memory corruption. However, because chunks were never recycled once GPU submissions finished, total reservations permanently froze upon reaching the 256 MiB cap, refusing every subsequent upload and leading to black screens and hundreds of thousands of null buffer bindings in long startup runs. Track queue submission fence values on upload chunks that receive unsubmitted writes. When active chunks and free tails cannot satisfy a reservation, inspect completed fence values and reset completed, idle chunks, guaranteeing storage still in flight on the GPU is never reused before completion. Add the gate-ring-reuse fixture to verify that upload reservations succeed once earlier GPU submissions complete, while gate and gate-ring continue to enforce in-flight safety and exhaustion limits. Fixes #2837 Refs #2823 --- CMakeLists.txt | 3 +- docs/startup-runtime.md | 6 +- src/startup_stubs/d3d12_xs_device.cpp | 97 ++++++++++++++++++++------ src/startup_stubs/upload_reservation.h | 13 ++++ tests/startup_address_console_check.py | 46 +++++++++++- tests/startup_stream_draw.cpp | 9 +++ tests/upload_reservation_check.cpp | 6 ++ 7 files changed, 151 insertions(+), 29 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f21a657696..5ae09e0d78 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4820,7 +4820,8 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_address_console_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) # Uploads of by-address textures recorded while the queue waits on a fence keep their bytes until the # queue has run them. The ring control fills them from the shared upload ring and must lose the first. - foreach(gate IN ITEMS gate gate-ring) + # gate-ring-reuse: once those submits have completed, the ring must accept new uploads again. + foreach(gate IN ITEMS gate gate-ring gate-ring-reuse) string(REPLACE "-" "_" gate_name "${gate}") add_test(NAME startup_address_console_${gate_name}_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_console_check.py" diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 78175b4c39..6b403e80e2 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3297,9 +3297,9 @@ uncovered prefix, and right before `OpenExistingHeapFromAddress` opens the heap). Anything else gets a committed default buffer that does not alias the title memory, holds zeros and is reported as success (`not aliased` in the log). `reserve_upload_ring` grows in demand -chunks from 16 MiB up to the 256 MiB total cap. A reservation owns its mapped -bytes for the process; the allocator may use an older unused tail but -refuses exhaustion or allocation failure rather than resetting live storage. +chunks from 16 MiB up to the 256 MiB total cap. Completed chunks whose queue +submissions have finished on the GPU are reused; storage still in flight is +never reused, and exhaustion refuses new reservations. `upload_reservation` exercises the shared cursor and returned-pointer contract without D3D12; on non-Windows hosts run `c++ -std=c++17 -Isrc tests/upload_reservation_check.cpp -o out/upload_reservation_check && out/upload_reservation_check`. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 50a22badfc..4cfb8d3051 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1647,6 +1647,8 @@ bool submit_fence_fails() // draw_lock and allocator_lock held, after the lists were executed on queue. Each list's allocator holds a fence value // the queue must pass before the allocator can be reset. If that fence cannot be created or // signalled, the work is on the GPU all the same: the allocators are marked untracked instead. +void note_upload_ring_submit(ID3D12Fence* fence, UINT64 value); + void note_submits(ID3D12CommandQueue* queue, const std::vector& lists) { auto& [fence, value] = queue_submits[queue]; @@ -1659,6 +1661,7 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector& lists) } if (fence && SUCCEEDED(queue->Signal(fence, value + 1))) { ++value; + note_upload_ring_submit(fence, value); for (Wrapper* list : lists) { const auto found = list_recordings.find(list); if (found == list_recordings.end()) continue; @@ -2413,8 +2416,44 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES } // Transient guest data is copied into mapped upload chunks. Chunks grow from -// 16 MiB up to 256 MiB in total and stay alive for the process. Exhaustion -// refuses new reservations rather than reusing storage without completion. +// 16 MiB up to 256 MiB in total and stay alive for the process. Completed chunks +// whose queue submissions have finished on the GPU are reused; storage still in +// flight is never reused, and exhaustion refuses new reservations. + +static SRWLOCK upload_ring_lock = SRWLOCK_INIT; +static std::vector upload_ring_chunks; +static std::size_t upload_ring_active = 0; +static u64 upload_ring_total_bytes = 0; + +void note_upload_ring_submit(ID3D12Fence* fence, UINT64 value) +{ + if (!fence) return; + AcquireSRWLockExclusive(&upload_ring_lock); + for (auto& chunk : upload_ring_chunks) { + if (chunk.unsubmitted) { + const auto it = std::find_if(chunk.submits.begin(), chunk.submits.end(), + [fence](const auto& s) { return s.first == fence; }); + if (it != chunk.submits.end()) { + it->second = value; + } else { + chunk.submits.emplace_back(fence, value); + } + chunk.unsubmitted = false; + } + } + ReleaseSRWLockExclusive(&upload_ring_lock); +} + +static bool is_upload_chunk_idle(const UploadRingChunk& chunk) +{ + if (chunk.unsubmitted) return false; + if (chunk.submits.empty()) return chunk.used == 0; + for (const auto& submit : chunk.submits) { + if (!submit.first) return false; + if (submit.first->GetCompletedValue() < submit.second) return false; + } + return true; +} UploadReservation reserve_upload_ring(std::size_t bytes) { @@ -2425,23 +2464,18 @@ UploadReservation reserve_upload_ring(std::size_t bytes) if (bytes == 0 || bytes > max_alloc_bytes) return reservation; const u64 rounded = (static_cast(bytes) + 511) & ~u64{511}; - static SRWLOCK lock = SRWLOCK_INIT; - static std::vector chunks; - static std::size_t active = 0; - static u64 total_bytes = 0; - - AcquireSRWLockExclusive(&lock); - if (!chunks.empty()) { - reservation = reserve_upload_chunk(chunks[active], rounded); + AcquireSRWLockExclusive(&upload_ring_lock); + if (!upload_ring_chunks.empty()) { + reservation = reserve_upload_chunk(upload_ring_chunks[upload_ring_active], rounded); if (reservation.mapped) { - ReleaseSRWLockExclusive(&lock); + ReleaseSRWLockExclusive(&upload_ring_lock); return reservation; } } - const u64 remaining = total_bytes < max_total_bytes ? max_total_bytes - total_bytes : 0; + const u64 remaining = upload_ring_total_bytes < max_total_bytes ? max_total_bytes - upload_ring_total_bytes : 0; if (rounded <= remaining) { - u64 chunk_bytes = chunks.empty() ? initial_chunk_bytes : chunks.back().capacity * 2; + u64 chunk_bytes = upload_ring_chunks.empty() ? initial_chunk_bytes : upload_ring_chunks.back().capacity * 2; if (chunk_bytes < rounded) chunk_bytes = rounded; if (chunk_bytes > remaining) chunk_bytes = remaining; auto* device = the_device ? device_of(the_device) : nullptr; @@ -2462,11 +2496,11 @@ UploadReservation reserve_upload_ring(std::size_t bytes) auto* budget = x2w_budget::committed(device, created, D3D12_HEAP_TYPE_UPLOAD); if (SUCCEEDED(created->Map(0, nullptr, &base))) { try { - chunks.push_back(UploadRingChunk{created, static_cast(base), chunk_bytes, 0}); - total_bytes += chunk_bytes; - active = chunks.size() - 1; - reservation = reserve_upload_chunk(chunks.back(), rounded); - ReleaseSRWLockExclusive(&lock); + upload_ring_chunks.push_back(UploadRingChunk{created, static_cast(base), chunk_bytes, 0}); + upload_ring_total_bytes += chunk_bytes; + upload_ring_active = upload_ring_chunks.size() - 1; + reservation = reserve_upload_chunk(upload_ring_chunks.back(), rounded); + ReleaseSRWLockExclusive(&upload_ring_lock); return reservation; } catch (const std::bad_alloc&) { created->Unmap(0, nullptr); @@ -2481,16 +2515,33 @@ UploadReservation reserve_upload_ring(std::size_t bytes) } } // Allocation failed or the cap was reached. Older unused tails are still safe. - for (std::size_t index = 0; index < chunks.size(); ++index) { - reservation = reserve_upload_chunk(chunks[index], rounded); + for (std::size_t index = 0; index < upload_ring_chunks.size(); ++index) { + reservation = reserve_upload_chunk(upload_ring_chunks[index], rounded); if (reservation.mapped) { - active = index; - ReleaseSRWLockExclusive(&lock); + upload_ring_active = index; + ReleaseSRWLockExclusive(&upload_ring_lock); return reservation; } } - ReleaseSRWLockExclusive(&lock); + // Check if any chunk whose GPU work has completed can be reset. + for (std::size_t step = 0; step < upload_ring_chunks.size(); ++step) { + const std::size_t index = (upload_ring_active + 1 + step) % upload_ring_chunks.size(); + auto& chunk = upload_ring_chunks[index]; + if (is_upload_chunk_idle(chunk)) { + reset_upload_chunk(chunk); + if (chunk.capacity >= rounded) { + reservation = reserve_upload_chunk(chunk, rounded); + if (reservation.mapped) { + upload_ring_active = index; + ReleaseSRWLockExclusive(&upload_ring_lock); + return reservation; + } + } + } + } + + ReleaseSRWLockExclusive(&upload_ring_lock); static LONG refused; if (first_calls(refused, 8)) log("x2w-draw upload ring reservation refused: no unused capacity"); diff --git a/src/startup_stubs/upload_reservation.h b/src/startup_stubs/upload_reservation.h index 991beab79b..7e244fa806 100644 --- a/src/startup_stubs/upload_reservation.h +++ b/src/startup_stubs/upload_reservation.h @@ -1,14 +1,19 @@ #pragma once #include +#include +#include struct ID3D12Resource; +struct ID3D12Fence; struct UploadRingChunk { ID3D12Resource* resource = nullptr; unsigned char* mapped = nullptr; std::uint64_t capacity = 0; std::uint64_t used = 0; + std::vector> submits{}; + bool unsubmitted = false; }; struct UploadReservation { @@ -23,5 +28,13 @@ inline UploadReservation reserve_upload_chunk(UploadRingChunk& chunk, std::uint6 if (chunk.used > chunk.capacity || rounded > chunk.capacity - chunk.used) return {}; const auto start = chunk.used; chunk.used += rounded; + chunk.unsubmitted = true; return {chunk.mapped + start, start, chunk.resource}; } + +inline void reset_upload_chunk(UploadRingChunk& chunk) +{ + chunk.used = 0; + chunk.submits.clear(); + chunk.unsubmitted = false; +} diff --git a/tests/startup_address_console_check.py b/tests/startup_address_console_check.py index d36db04448..2c0aedb77e 100644 --- a/tests/startup_address_console_check.py +++ b/tests/startup_address_console_check.py @@ -8,6 +8,8 @@ gate-ring the same draws with X2W_TEST_ADDRESS_UPLOAD_RING=1: the 256 MiB ring refuses the uploads past its cap, the refused draws read the null view and the left half keeps payload 0 + gate-ring-reuse gate-ring, then once every submit has completed one more payload from + the ring, which must not be refused The backing bytes are built here, independently of src/startup_stubs/gfx10_layout.h, from the address equations of AMD addrlib's GFX10 pattern tables, written out below. Reference: addrlib as Mesa carries it @@ -217,6 +219,43 @@ def gate_colour(payload): return bytes(((17 * payload + 3) & 255, (255 - 9 * payload) & 255, payload ^ 0x5a, 255)) +def check_gate_ring_reuse(directory, consumer, backend): + """After the gate-ring sequence has completed, one more payload must find ring capacity again. + + The fixture runs the gate-ring draws, waits until every submit has completed, then draws payload 18 over + the right half from the ring. Nothing is in flight any more, so the reservation must succeed: the left half + holds payload 0 and the right half payload 18, not the null view. + """ + hlsl = ("Texture2D t : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " return t.Load(int3(uint(p.x) % 2048, uint(p.y) % 2048, 0));\n}\n") + trap_log = directory / "trap.log" + modes = {"X2W_TEST_CONSOLE_GATE": "1", "X2W_TRAP_LOG": str(trap_log), + "X2W_TEST_ADDRESS_UPLOAD_RING": "1", "X2W_TEST_ADDRESS_UPLOAD_RING_REUSE": "1"} + actual = draw_texture(directory, consumer, backend, hlsl, modes) + if actual is None: + return 77 + if len(actual) != TARGET_W * TARGET_H * 4: + raise AssertionError(f"gate-ring-reuse: readback length {len(actual)}") + first, last = gate_colour(0), gate_colour(GATE_PAYLOADS) + wrong = {"left": 0, "right": 0} + seen = set() + for y in range(TARGET_H): + for x in range(TARGET_W): + pixel = actual[4 * (y * TARGET_W + x):4 * (y * TARGET_W + x) + 4] + side = "left" if x < TARGET_W // 2 else "right" + if pixel != (first if side == "left" else last): + wrong[side] += 1 + seen.add(pixel.hex()) + if wrong["left"] or wrong["right"]: + raise AssertionError(f"gate-ring-reuse: {wrong} wrong pixels, found {sorted(seen)[:4]}; expected " + f"{first.hex()} left, {last.hex()} right (payload {GATE_PAYLOADS} after completion)") + half = TARGET_W * TARGET_H // 2 + print(f"{backend} gate-ring-reuse: after all submits completed, payload {GATE_PAYLOADS} was uploaded from the ring; " + f"{half} left pixels hold payload 0 and {half} right pixels payload {GATE_PAYLOADS}") + return 0 + + def check_gate(directory, consumer, backend, ring): """Uploads recorded while the queue cannot run must still hold their bytes when it does. @@ -282,9 +321,12 @@ def check_gate(directory, consumer, backend, ring): if __name__ == "__main__": - if len(sys.argv) not in (3, 4) or (len(sys.argv) == 4 and sys.argv[3] not in ("gate", "gate-ring")): - usage = "usage: startup_address_console_check.py [gate | gate-ring]\n" + if len(sys.argv) not in (3, 4) or (len(sys.argv) == 4 and sys.argv[3] not in ("gate", "gate-ring", "gate-ring-reuse")): + usage = "usage: startup_address_console_check.py [gate | gate-ring | gate-ring-reuse]\n" sys.exit(usage + "\n\n".join(__doc__.split("\n\n")[:2])) + if len(sys.argv) == 4 and sys.argv[3] == "gate-ring-reuse": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check_gate_ring_reuse(Path(temporary), sys.argv[1], sys.argv[2])) if len(sys.argv) == 4: with tempfile.TemporaryDirectory() as temporary: sys.exit(check_gate(Path(temporary), sys.argv[1], sys.argv[2], sys.argv[3] == "gate-ring")) diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 78f925f39d..dbea4a7408 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -503,6 +503,15 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* invoke(list, 9); invoke(queue, 10, 1, arg(&list)); if (FAILED(static_cast(invoke(queue, 14, arg(fence), payloads + 1))) || !reached(payloads + 1)) return 25; + // X2W_TEST_ADDRESS_UPLOAD_RING_REUSE: every earlier upload has now completed, so one more payload over + // the right half must find ring capacity again (refs #2823). + if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_UPLOAD_RING_REUSE", nullptr, 0)) { + if (!next_recording()) return 35; + if (const int result = draw_gated_console_payload(guest, list, payloads, false)) return result; + invoke(list, 9); + invoke(queue, 10, 1, arg(&list)); + if (FAILED(static_cast(invoke(queue, 14, arg(fence), payloads + 2))) || !reached(payloads + 2)) return 25; + } return read_stream_target(desktop.Get(), frame, pixels); } else if (bc) { extern int draw_bc_address_srvs(void*, void*); diff --git a/tests/upload_reservation_check.cpp b/tests/upload_reservation_check.cpp index 8a20ad4367..4be17edf56 100644 --- a/tests/upload_reservation_check.cpp +++ b/tests/upload_reservation_check.cpp @@ -63,6 +63,12 @@ int main() storage_a[2 * kAlign - 1] == 0x5a && storage_a[2 * kAlign] == 0x7d, "existing reservations survive exhaustion"); + reset_upload_chunk(chunks[0]); + check(chunks[0].used == 0 && !chunks[0].unsubmitted, "reset clears cursor and unsubmitted flag"); + const auto recycled = reserve_upload_chunk(chunks[0], kAlign); + check(recycled.mapped == storage_a && recycled.offset == 0 && chunks[0].unsubmitted, + "recycled chunk reserves from start"); + std::puts("upload_reservation_check: all checks passed"); return 0; } From 895a7c0d02a305b2669ca460db6b3540d6efd745 Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:51:01 +0500 Subject: [PATCH 2/5] startup: tie upload ring chunk reuse to command list execution Address review feedback on #2847 (tedin7): 1. Tie chunk reuse to the command lists that actually reserve from them. Track recorded chunks per command list in recorded_upload_chunks. Chunks maintain an unsubmitted_lists count and are bound to queue submit fence values only when the lists using them are executed. When a recording is discarded on Reset or failed Close, its reservations are dropped. 2. In upload_reservation_check.cpp, test unsubmitted lists, pending and completed fence values, and multi-queue submissions. 3. In gate-ring-reuse, add a negative control draw while the queue is held behind the gate fence. Verify it is refused and preserves payload 0 on the left half, and verify mutation of the fence check fails the fixture. --- src/startup_stubs/d3d12_draw.inl | 23 +++--- src/startup_stubs/d3d12_xs_device.cpp | 109 ++++++++++++++++++------- src/startup_stubs/upload_reservation.h | 16 +++- tests/startup_address_console_check.py | 11 ++- tests/startup_stream_draw.cpp | 18 +++- tests/upload_reservation_check.cpp | 40 ++++++++- 6 files changed, 167 insertions(+), 50 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 122df58e1e..26a62e9393 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1232,7 +1232,7 @@ std::unordered_map& frame_copies() { static std::unordered_mapsecond.content.data(), title, bytes) == 0) { *offset = found->second.offset; if (resource) *resource = found->second.resource; + if (list && found->second.resource) note_upload_ring_use(found->second.resource, list); return true; } u64 fresh = 0; ID3D12Resource* chunk = nullptr; - auto* ring = reserve_upload_ring(bytes, &fresh, &chunk); + auto* ring = reserve_upload_ring(bytes, &fresh, &chunk, list); if (!ring || !chunk) return false; // Cache insertion and snapshot allocation are optional. Fill the ring directly if they fail. const unsigned char* source = title; @@ -1436,7 +1437,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) if (owned.cpu) { owned.cursor += (bytes + placement - 1) & ~(placement - 1); } else { - rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk); + rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, list); if (!rows || !chunk) { state.done = false; return false; @@ -1458,7 +1459,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) const u64 bytes = plan.bytes(i); u64 offset = 0; ID3D12Resource* chunk = nullptr; - auto* rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk); + auto* rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, list); if (!rows || !chunk) { state.done = false; return true; @@ -1472,7 +1473,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) u64 offset = 0; const auto bytes = plan.bytes(0); ID3D12Resource* chunk = nullptr; - auto* rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk); + auto* rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, list); if (!rows || !chunk) { state.done = false; return true; @@ -1488,7 +1489,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) u64 offset = 0; ID3D12Resource* chunk = nullptr; if (is_compact) { - auto* const rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk); + auto* const rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, list); if (!rows || !chunk) { state.done = false; return true; @@ -1497,7 +1498,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) for (u64 y = 0; y < level.rows; ++y) std::memcpy(rows + y * fp.Footprint.RowPitch, memory + level.offset + y * level.row_bytes, static_cast(level.row_bytes)); - } else if (!ring_copy(reinterpret_cast(memory) + stride * s + fp.Offset, static_cast(bytes), &offset, &chunk) || !chunk) { + } else if (!ring_copy(reinterpret_cast(memory) + stride * s + fp.Offset, static_cast(bytes), &offset, &chunk, list) || !chunk) { state.done = false; return true; } @@ -2522,7 +2523,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI // to a DWORD, so initialise its final padding without reading the guest. const auto padded = (bytes + 3) & ~std::size_t{3}; ID3D12Resource* chunk = nullptr; - auto* target = readable_window(address, bytes) >= bytes ? reserve_upload_ring(padded, &offset, &chunk) : nullptr; + auto* target = readable_window(address, bytes) >= bytes ? reserve_upload_ring(padded, &offset, &chunk, list) : nullptr; if (target) { std::memcpy(target, reinterpret_cast(address), bytes); std::memset(target + bytes, 0, padded - bytes); @@ -2537,7 +2538,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI continue; } ID3D12Resource* chunk = nullptr; - bool have = address && bytes && readable_window(address, bytes) >= bytes && frame_copy(address, bytes, &offset, &chunk); + bool have = address && bytes && readable_window(address, bytes) >= bytes && frame_copy(address, bytes, &offset, &chunk, list); // Experiment (X2W_DRAW_NULL_IDENTITY=1): an empty buffer slot reads as repeated identity // matrices instead of zeros. The start-up screen's last pass takes its world matrix from a // slot the title leaves empty here; why is not known yet. @@ -2555,7 +2556,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI for (int k = 0; k < 64; ++k) identity[k] = (k % 16) % 5 == 0 ? 1.0f : 0.0f; address = reinterpret_cast(identity); bytes = sizeof(identity); - have = frame_copy(address, bytes, &offset, &chunk); + have = frame_copy(address, bytes, &offset, &chunk, list); } buffer_view(dest, have ? chunk : nullptr, offset, bytes); count_buffer(have); @@ -2660,7 +2661,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI auto view = live_indices; if (live_index_resource) { require_state(self, live_index_resource, D3D12_RESOURCE_STATE_INDEX_BUFFER); - } else if (indices_ok && frame_copy(index_address, index_total, &offset, &index_chunk) && index_chunk) { + } else if (indices_ok && frame_copy(index_address, index_total, &offset, &index_chunk, list) && index_chunk) { view = {index_chunk->GetGPUVirtualAddress() + offset, static_cast(index_total), index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 4cfb8d3051..fbadf2e1a2 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1647,9 +1647,10 @@ bool submit_fence_fails() // draw_lock and allocator_lock held, after the lists were executed on queue. Each list's allocator holds a fence value // the queue must pass before the allocator can be reset. If that fence cannot be created or // signalled, the work is on the GPU all the same: the allocators are marked untracked instead. -void note_upload_ring_submit(ID3D12Fence* fence, UINT64 value); +void note_upload_ring_submits(ID3D12Fence* fence, UINT64 value, const std::vector& lists); +void discard_upload_ring(ID3D12CommandList* list); -void note_submits(ID3D12CommandQueue* queue, const std::vector& lists) +void note_submits(ID3D12CommandQueue* queue, const std::vector& lists, const std::vector& native_lists) { auto& [fence, value] = queue_submits[queue]; if (!fence && !submit_fence_fails()) { @@ -1661,7 +1662,7 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector& lists) } if (fence && SUCCEEDED(queue->Signal(fence, value + 1))) { ++value; - note_upload_ring_submit(fence, value); + note_upload_ring_submits(fence, value, native_lists); for (Wrapper* list : lists) { const auto found = list_recordings.find(list); if (found == list_recordings.end()) continue; @@ -1806,6 +1807,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) discard_list_gpu_writes(self); discard_draw_sampler_heaps(previous); discard_address_uploads(previous); + discard_upload_ring(previous); discard_mesh_lease_recording(previous); retire_drop_recording(self); if (draw_dump_frame()) draw_dumps().discard(previous); @@ -1844,6 +1846,7 @@ HRESULT __stdcall list_close(Wrapper* self) discard_list_gpu_writes(self); discard_draw_sampler_heaps(list); discard_address_uploads(list); + discard_upload_ring(list); discard_mesh_lease_recording(list); retire_drop_recording(self); if (draw_dump_frame()) draw_dumps().discard(list); @@ -2424,38 +2427,75 @@ static SRWLOCK upload_ring_lock = SRWLOCK_INIT; static std::vector upload_ring_chunks; static std::size_t upload_ring_active = 0; static u64 upload_ring_total_bytes = 0; +static std::unordered_map> recorded_upload_chunks; -void note_upload_ring_submit(ID3D12Fence* fence, UINT64 value) +void note_upload_ring_submits(ID3D12Fence* fence, UINT64 value, const std::vector& lists) { if (!fence) return; AcquireSRWLockExclusive(&upload_ring_lock); - for (auto& chunk : upload_ring_chunks) { - if (chunk.unsubmitted) { - const auto it = std::find_if(chunk.submits.begin(), chunk.submits.end(), - [fence](const auto& s) { return s.first == fence; }); - if (it != chunk.submits.end()) { - it->second = value; - } else { - chunk.submits.emplace_back(fence, value); + for (auto* list : lists) { + const auto it = recorded_upload_chunks.find(list); + if (it == recorded_upload_chunks.end()) continue; + for (std::size_t chunk_idx : it->second) { + if (chunk_idx < upload_ring_chunks.size()) { + auto& chunk = upload_ring_chunks[chunk_idx]; + if (chunk.unsubmitted_lists > 0) --chunk.unsubmitted_lists; + const auto sub = std::find_if(chunk.submits.begin(), chunk.submits.end(), + [fence](const auto& s) { return s.first == fence; }); + if (sub != chunk.submits.end()) { + sub->second = value; + } else { + chunk.submits.emplace_back(fence, value); + } } - chunk.unsubmitted = false; } + recorded_upload_chunks.erase(it); } ReleaseSRWLockExclusive(&upload_ring_lock); } -static bool is_upload_chunk_idle(const UploadRingChunk& chunk) +void discard_upload_ring(ID3D12CommandList* list) { - if (chunk.unsubmitted) return false; - if (chunk.submits.empty()) return chunk.used == 0; - for (const auto& submit : chunk.submits) { - if (!submit.first) return false; - if (submit.first->GetCompletedValue() < submit.second) return false; + if (!list) return; + AcquireSRWLockExclusive(&upload_ring_lock); + const auto it = recorded_upload_chunks.find(list); + if (it != recorded_upload_chunks.end()) { + for (std::size_t chunk_idx : it->second) { + if (chunk_idx < upload_ring_chunks.size()) { + auto& chunk = upload_ring_chunks[chunk_idx]; + if (chunk.unsubmitted_lists > 0) --chunk.unsubmitted_lists; + } + } + recorded_upload_chunks.erase(it); } - return true; + ReleaseSRWLockExclusive(&upload_ring_lock); +} + +void note_upload_ring_use(ID3D12Resource* resource, ID3D12CommandList* list) +{ + if (!resource || !list) return; + AcquireSRWLockExclusive(&upload_ring_lock); + for (std::size_t i = 0; i < upload_ring_chunks.size(); ++i) { + if (upload_ring_chunks[i].resource == resource) { + auto& chunks = recorded_upload_chunks[list]; + if (std::find(chunks.begin(), chunks.end(), i) == chunks.end()) { + chunks.push_back(i); + ++upload_ring_chunks[i].unsubmitted_lists; + } + break; + } + } + ReleaseSRWLockExclusive(&upload_ring_lock); +} + +static bool is_upload_chunk_idle(const UploadRingChunk& chunk) +{ + return is_upload_chunk_idle(chunk, [](ID3D12Fence* fence) { + return fence->GetCompletedValue(); + }); } -UploadReservation reserve_upload_ring(std::size_t bytes) +UploadReservation reserve_upload_ring(std::size_t bytes, ID3D12CommandList* list = nullptr) { constexpr u64 initial_chunk_bytes = u64{16} << 20; constexpr u64 max_total_bytes = u64{256} << 20; @@ -2465,9 +2505,19 @@ UploadReservation reserve_upload_ring(std::size_t bytes) const u64 rounded = (static_cast(bytes) + 511) & ~u64{511}; AcquireSRWLockExclusive(&upload_ring_lock); + const auto note_list = [&](std::size_t index) { + if (!list) return; + auto& chunks = recorded_upload_chunks[list]; + if (std::find(chunks.begin(), chunks.end(), index) == chunks.end()) { + chunks.push_back(index); + ++upload_ring_chunks[index].unsubmitted_lists; + } + }; + if (!upload_ring_chunks.empty()) { reservation = reserve_upload_chunk(upload_ring_chunks[upload_ring_active], rounded); if (reservation.mapped) { + note_list(upload_ring_active); ReleaseSRWLockExclusive(&upload_ring_lock); return reservation; } @@ -2500,6 +2550,7 @@ UploadReservation reserve_upload_ring(std::size_t bytes) upload_ring_total_bytes += chunk_bytes; upload_ring_active = upload_ring_chunks.size() - 1; reservation = reserve_upload_chunk(upload_ring_chunks.back(), rounded); + note_list(upload_ring_active); ReleaseSRWLockExclusive(&upload_ring_lock); return reservation; } catch (const std::bad_alloc&) { @@ -2519,6 +2570,7 @@ UploadReservation reserve_upload_ring(std::size_t bytes) reservation = reserve_upload_chunk(upload_ring_chunks[index], rounded); if (reservation.mapped) { upload_ring_active = index; + note_list(upload_ring_active); ReleaseSRWLockExclusive(&upload_ring_lock); return reservation; } @@ -2534,6 +2586,7 @@ UploadReservation reserve_upload_ring(std::size_t bytes) reservation = reserve_upload_chunk(chunk, rounded); if (reservation.mapped) { upload_ring_active = index; + note_list(upload_ring_active); ReleaseSRWLockExclusive(&upload_ring_lock); return reservation; } @@ -2548,26 +2601,26 @@ UploadReservation reserve_upload_ring(std::size_t bytes) return reservation; } -unsigned char* reserve_upload_ring(std::size_t bytes, u64* offset, ID3D12Resource** resource) +unsigned char* reserve_upload_ring(std::size_t bytes, u64* offset, ID3D12Resource** resource, ID3D12CommandList* list = nullptr) { if (resource) *resource = nullptr; if (offset) *offset = 0; - const UploadReservation reservation = reserve_upload_ring(bytes); + const UploadReservation reservation = reserve_upload_ring(bytes, list); if (!reservation.mapped) return nullptr; if (offset) *offset = reservation.offset; if (resource) *resource = reservation.resource; return reservation.mapped; } -bool ring_copy(u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** resource = nullptr) +bool ring_copy(u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** resource = nullptr, ID3D12CommandList* list = nullptr) { - auto* dest = reserve_upload_ring(bytes, offset, resource); + auto* dest = reserve_upload_ring(bytes, offset, resource, list); if (!dest) return false; std::memcpy(dest, reinterpret_cast(title_address), bytes); return true; } -D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(u64 title_address, std::size_t bytes) +D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(u64 title_address, std::size_t bytes, ID3D12CommandList* list = nullptr) { u64 offset = 0; ID3D12Resource* resource = nullptr; @@ -3927,7 +3980,7 @@ void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) return; } const std::size_t bytes = readable_window(address, 0x10000); - const D3D12_GPU_VIRTUAL_ADDRESS desktop = bytes ? upload_from_title(address, bytes) : 0; + const D3D12_GPU_VIRTUAL_ADDRESS desktop = bytes ? upload_from_title(address, bytes, list) : 0; static LONG logged; if (first_calls(logged, 4)) { char head[3 * 32 + 1]; @@ -4109,7 +4162,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) }); retire_address_uploads(queue, native_lists); retire_draw_sampler_heaps(queue, native_lists); - note_submits(queue, wrappers); + note_submits(queue, wrappers, native_lists); retire_note_submission(queue, wrappers); for (Wrapper* w : wrappers) commit_list_gpu_writes(w); InterlockedIncrement(&render_executes); diff --git a/src/startup_stubs/upload_reservation.h b/src/startup_stubs/upload_reservation.h index 7e244fa806..ac5f0c8bf1 100644 --- a/src/startup_stubs/upload_reservation.h +++ b/src/startup_stubs/upload_reservation.h @@ -12,8 +12,8 @@ struct UploadRingChunk { unsigned char* mapped = nullptr; std::uint64_t capacity = 0; std::uint64_t used = 0; + std::size_t unsubmitted_lists = 0; std::vector> submits{}; - bool unsubmitted = false; }; struct UploadReservation { @@ -28,13 +28,23 @@ inline UploadReservation reserve_upload_chunk(UploadRingChunk& chunk, std::uint6 if (chunk.used > chunk.capacity || rounded > chunk.capacity - chunk.used) return {}; const auto start = chunk.used; chunk.used += rounded; - chunk.unsubmitted = true; return {chunk.mapped + start, start, chunk.resource}; } +template +inline bool is_upload_chunk_idle(const UploadRingChunk& chunk, FenceQuery&& query) +{ + if (chunk.unsubmitted_lists != 0) return false; + for (const auto& submit : chunk.submits) { + if (!submit.first) return false; + if (query(submit.first) < submit.second) return false; + } + return true; +} + inline void reset_upload_chunk(UploadRingChunk& chunk) { chunk.used = 0; chunk.submits.clear(); - chunk.unsubmitted = false; + chunk.unsubmitted_lists = 0; } diff --git a/tests/startup_address_console_check.py b/tests/startup_address_console_check.py index 2c0aedb77e..aef58b108a 100644 --- a/tests/startup_address_console_check.py +++ b/tests/startup_address_console_check.py @@ -222,9 +222,11 @@ def gate_colour(payload): def check_gate_ring_reuse(directory, consumer, backend): """After the gate-ring sequence has completed, one more payload must find ring capacity again. - The fixture runs the gate-ring draws, waits until every submit has completed, then draws payload 18 over - the right half from the ring. Nothing is in flight any more, so the reservation must succeed: the left half - holds payload 0 and the right half payload 18, not the null view. + The fixture runs the gate-ring draws. While the queue is still held behind the gate, a negative + control draw attempts a reservation from the exhausted ring; because submissions are still in flight, + the reservation must be refused and payload 0 on the left half preserved. Once every submit has + completed, a final draw uploads payload 18 over the right half from the recycled ring. The left half + must hold payload 0 and the right half payload 18. """ hlsl = ("Texture2D t : register(t0);\n" "float4 main(float4 p : SV_Position) : SV_Target {\n" @@ -250,6 +252,9 @@ def check_gate_ring_reuse(directory, consumer, backend): if wrong["left"] or wrong["right"]: raise AssertionError(f"gate-ring-reuse: {wrong} wrong pixels, found {sorted(seen)[:4]}; expected " f"{first.hex()} left, {last.hex()} right (payload {GATE_PAYLOADS} after completion)") + log = trap_log.read_text(errors="replace") + if "x2w-draw upload ring reservation refused: no unused capacity" not in log: + raise AssertionError("gate-ring-reuse: expected upload reservation refusal while queue was held") half = TARGET_W * TARGET_H // 2 print(f"{backend} gate-ring-reuse: after all submits completed, payload {GATE_PAYLOADS} was uploaded from the ring; " f"{half} left pixels hold payload 0 and {half} right pixels payload {GATE_PAYLOADS}") diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index dbea4a7408..b90a779079 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -491,6 +491,16 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } Sleep(250); if (invoke(fence, 8) != 0) return 46; // a submit completed although the queue was held + // Negative control: while the queue is held behind the gate, any new reservation must be + // refused because storage is in-flight. If early reuse wrongly recycled chunks before + // completion, this draw would overwrite chunk 0 while payload 0 is still in flight. + if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_UPLOAD_RING_REUSE", nullptr, 0)) { + if (!next_recording()) return 35; + if (const int result = draw_gated_console_payload(guest, list, 99, false)) return result; + invoke(list, 9); + invoke(queue, 10, 1, arg(&list)); + if (FAILED(static_cast(invoke(queue, 14, arg(fence), payloads + 1)))) return 24; + } if (FAILED(static_cast(invoke(gate, 10, 1)))) return 47; // One more recording without a draw: its submit is where the stand-in visits the completed ones. const auto reached = [&](UINT64 value) { @@ -498,11 +508,13 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* while (invoke(fence, 8) < value && GetTickCount64() < deadline) Sleep(1); return invoke(fence, 8) == value; }; - if (!reached(payloads)) return 25; + const UINT64 gate_fence = GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_UPLOAD_RING_REUSE", nullptr, 0) + ? payloads + 1 : payloads; + if (!reached(gate_fence)) return 25; if (!next_recording()) return 35; invoke(list, 9); invoke(queue, 10, 1, arg(&list)); - if (FAILED(static_cast(invoke(queue, 14, arg(fence), payloads + 1))) || !reached(payloads + 1)) return 25; + if (FAILED(static_cast(invoke(queue, 14, arg(fence), gate_fence + 1))) || !reached(gate_fence + 1)) return 25; // X2W_TEST_ADDRESS_UPLOAD_RING_REUSE: every earlier upload has now completed, so one more payload over // the right half must find ring capacity again (refs #2823). if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_UPLOAD_RING_REUSE", nullptr, 0)) { @@ -510,7 +522,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* if (const int result = draw_gated_console_payload(guest, list, payloads, false)) return result; invoke(list, 9); invoke(queue, 10, 1, arg(&list)); - if (FAILED(static_cast(invoke(queue, 14, arg(fence), payloads + 2))) || !reached(payloads + 2)) return 25; + if (FAILED(static_cast(invoke(queue, 14, arg(fence), gate_fence + 2))) || !reached(gate_fence + 2)) return 25; } return read_stream_target(desktop.Get(), frame, pixels); } else if (bc) { diff --git a/tests/upload_reservation_check.cpp b/tests/upload_reservation_check.cpp index 4be17edf56..9138589c08 100644 --- a/tests/upload_reservation_check.cpp +++ b/tests/upload_reservation_check.cpp @@ -64,11 +64,47 @@ int main() "existing reservations survive exhaustion"); reset_upload_chunk(chunks[0]); - check(chunks[0].used == 0 && !chunks[0].unsubmitted, "reset clears cursor and unsubmitted flag"); + check(chunks[0].used == 0 && chunks[0].unsubmitted_lists == 0 && chunks[0].submits.empty(), + "reset clears cursor, unsubmitted count and submits"); const auto recycled = reserve_upload_chunk(chunks[0], kAlign); - check(recycled.mapped == storage_a && recycled.offset == 0 && chunks[0].unsubmitted, + check(recycled.mapped == storage_a && recycled.offset == 0, "recycled chunk reserves from start"); + // Guard fence logic and unsubmitted tracking: + struct MockFence { + std::uint64_t completed = 0; + }; + MockFence fence_a; + MockFence fence_b; + const auto fence_query = [](const ID3D12Fence* f) { + return reinterpret_cast(f)->completed; + }; + + check(is_upload_chunk_idle(chunks[0], fence_query), "chunk without unsubmitted lists or submits is idle"); + + chunks[0].unsubmitted_lists = 1; + check(!is_upload_chunk_idle(chunks[0], fence_query), "chunk with unsubmitted lists is not idle"); + + chunks[0].unsubmitted_lists = 0; + chunks[0].submits.emplace_back(reinterpret_cast(&fence_a), 10); + fence_a.completed = 9; + check(!is_upload_chunk_idle(chunks[0], fence_query), "chunk with in-flight submit is not idle"); + + fence_a.completed = 10; + check(is_upload_chunk_idle(chunks[0], fence_query), "chunk with completed submit is idle"); + + // Multi-queue submits: + chunks[0].submits.emplace_back(reinterpret_cast(&fence_b), 5); + fence_b.completed = 4; + check(!is_upload_chunk_idle(chunks[0], fence_query), "chunk with second pending queue submit is not idle"); + + fence_b.completed = 5; + check(is_upload_chunk_idle(chunks[0], fence_query), "chunk with all queue submits completed is idle"); + + reset_upload_chunk(chunks[0]); + check(chunks[0].used == 0 && chunks[0].unsubmitted_lists == 0 && chunks[0].submits.empty(), + "final reset clears submits"); + std::puts("upload_reservation_check: all checks passed"); return 0; } From f67c03e127c94116a83c5b0371eda04af907b973 Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:04:12 +0500 Subject: [PATCH 3/5] startup: track chunk generation, closed list resubmission and device removal - Pass command list through upload_from_title to ring_copy to maintain chunk associations. - Add generation counter to UploadRingChunk and FrameCopy to invalidate stale cache hits after chunk reset. - Keep chunk recordings held across queue_execute submissions so closed lists can be safely resubmitted. - Treat UINT64_MAX fence completion query in is_upload_chunk_idle as device removal. - Extend upload_reservation_check with generation, closed list hold and device removal test coverage. --- src/startup_stubs/d3d12_draw.inl | 23 +++++++++++++---------- src/startup_stubs/d3d12_xs_device.cpp | 25 +++++++++++++++++++------ src/startup_stubs/upload_reservation.h | 14 +++++++++----- tests/upload_reservation_check.cpp | 25 ++++++++++++++----------- 4 files changed, 55 insertions(+), 32 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 26a62e9393..270ac46173 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1226,6 +1226,7 @@ struct FrameCopy { u64 address = 0; u64 offset = 0; ID3D12Resource* resource = nullptr; + u64 generation = 0; std::vector content; }; std::unordered_map& frame_copies() { static std::unordered_map m; return m; } @@ -1243,26 +1244,28 @@ bool frame_copy(u64 address, std::size_t bytes, u64* offset, ID3D12Resource** re const auto found = frame_copies().find(key); const bool known = found != frame_copies().end() && found->second.address == address && found->second.content.size() == bytes; if (known && std::memcmp(found->second.content.data(), title, bytes) == 0) { - *offset = found->second.offset; - if (resource) *resource = found->second.resource; - if (list && found->second.resource) note_upload_ring_use(found->second.resource, list); - return true; + if (is_upload_chunk_generation_valid(found->second.resource, found->second.generation)) { + *offset = found->second.offset; + if (resource) *resource = found->second.resource; + if (list && found->second.resource) note_upload_ring_use(found->second.resource, list); + return true; + } } - u64 fresh = 0; - ID3D12Resource* chunk = nullptr; - auto* ring = reserve_upload_ring(bytes, &fresh, &chunk, list); - if (!ring || !chunk) return false; + const auto reservation = reserve_upload_ring(bytes, list); + if (!reservation.mapped || !reservation.resource) return false; + const u64 fresh = reservation.offset; + auto* chunk = reservation.resource; // Cache insertion and snapshot allocation are optional. Fill the ring directly if they fail. const unsigned char* source = title; try { std::vector content(title, title + bytes); // Use the stored snapshot to fill the ring so the GPU bytes and subsequent comparisons agree. - auto entry = frame_copies().insert_or_assign(key, FrameCopy{address, fresh, chunk, std::move(content)}); + auto entry = frame_copies().insert_or_assign(key, FrameCopy{address, fresh, chunk, reservation.generation, std::move(content)}); source = entry.first->second.content.data(); } catch (const std::bad_alloc&) { // The ring slice is already reserved. The draw can proceed without another CPU allocation. } - std::memcpy(ring, source, bytes); + std::memcpy(reservation.mapped, source, bytes); if (known) { static LONG refreshed; if (first_calls(refreshed, 4)) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index fbadf2e1a2..b0129a1998 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2439,7 +2439,6 @@ void note_upload_ring_submits(ID3D12Fence* fence, UINT64 value, const std::vecto for (std::size_t chunk_idx : it->second) { if (chunk_idx < upload_ring_chunks.size()) { auto& chunk = upload_ring_chunks[chunk_idx]; - if (chunk.unsubmitted_lists > 0) --chunk.unsubmitted_lists; const auto sub = std::find_if(chunk.submits.begin(), chunk.submits.end(), [fence](const auto& s) { return s.first == fence; }); if (sub != chunk.submits.end()) { @@ -2449,7 +2448,6 @@ void note_upload_ring_submits(ID3D12Fence* fence, UINT64 value, const std::vecto } } } - recorded_upload_chunks.erase(it); } ReleaseSRWLockExclusive(&upload_ring_lock); } @@ -2463,7 +2461,7 @@ void discard_upload_ring(ID3D12CommandList* list) for (std::size_t chunk_idx : it->second) { if (chunk_idx < upload_ring_chunks.size()) { auto& chunk = upload_ring_chunks[chunk_idx]; - if (chunk.unsubmitted_lists > 0) --chunk.unsubmitted_lists; + if (chunk.recordings > 0) --chunk.recordings; } } recorded_upload_chunks.erase(it); @@ -2480,7 +2478,7 @@ void note_upload_ring_use(ID3D12Resource* resource, ID3D12CommandList* list) auto& chunks = recorded_upload_chunks[list]; if (std::find(chunks.begin(), chunks.end(), i) == chunks.end()) { chunks.push_back(i); - ++upload_ring_chunks[i].unsubmitted_lists; + ++upload_ring_chunks[i].recordings; } break; } @@ -2488,6 +2486,21 @@ void note_upload_ring_use(ID3D12Resource* resource, ID3D12CommandList* list) ReleaseSRWLockExclusive(&upload_ring_lock); } +bool is_upload_chunk_generation_valid(ID3D12Resource* resource, u64 generation) +{ + if (!resource) return false; + AcquireSRWLockShared(&upload_ring_lock); + for (const auto& chunk : upload_ring_chunks) { + if (chunk.resource == resource) { + const bool valid = chunk.generation == generation; + ReleaseSRWLockShared(&upload_ring_lock); + return valid; + } + } + ReleaseSRWLockShared(&upload_ring_lock); + return false; +} + static bool is_upload_chunk_idle(const UploadRingChunk& chunk) { return is_upload_chunk_idle(chunk, [](ID3D12Fence* fence) { @@ -2510,7 +2523,7 @@ UploadReservation reserve_upload_ring(std::size_t bytes, ID3D12CommandList* list auto& chunks = recorded_upload_chunks[list]; if (std::find(chunks.begin(), chunks.end(), index) == chunks.end()) { chunks.push_back(index); - ++upload_ring_chunks[index].unsubmitted_lists; + ++upload_ring_chunks[index].recordings; } }; @@ -2624,7 +2637,7 @@ D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(u64 title_address, std::size_t bytes { u64 offset = 0; ID3D12Resource* resource = nullptr; - return ring_copy(title_address, bytes, &offset, &resource) && resource ? resource->GetGPUVirtualAddress() + offset : 0; + return ring_copy(title_address, bytes, &offset, &resource, list) && resource ? resource->GetGPUVirtualAddress() + offset : 0; } // Number of contiguous readable bytes at address, up to wanted. diff --git a/src/startup_stubs/upload_reservation.h b/src/startup_stubs/upload_reservation.h index ac5f0c8bf1..3977e5cf72 100644 --- a/src/startup_stubs/upload_reservation.h +++ b/src/startup_stubs/upload_reservation.h @@ -12,7 +12,8 @@ struct UploadRingChunk { unsigned char* mapped = nullptr; std::uint64_t capacity = 0; std::uint64_t used = 0; - std::size_t unsubmitted_lists = 0; + std::size_t recordings = 0; + std::uint64_t generation = 0; std::vector> submits{}; }; @@ -20,6 +21,7 @@ struct UploadReservation { unsigned char* mapped = nullptr; std::uint64_t offset = 0; ID3D12Resource* resource = nullptr; + std::uint64_t generation = 0; }; // Caller holds the lock. A successful reservation owns previously unused bytes. @@ -28,16 +30,17 @@ inline UploadReservation reserve_upload_chunk(UploadRingChunk& chunk, std::uint6 if (chunk.used > chunk.capacity || rounded > chunk.capacity - chunk.used) return {}; const auto start = chunk.used; chunk.used += rounded; - return {chunk.mapped + start, start, chunk.resource}; + return {chunk.mapped + start, start, chunk.resource, chunk.generation}; } template inline bool is_upload_chunk_idle(const UploadRingChunk& chunk, FenceQuery&& query) { - if (chunk.unsubmitted_lists != 0) return false; + if (chunk.recordings != 0) return false; for (const auto& submit : chunk.submits) { if (!submit.first) return false; - if (query(submit.first) < submit.second) return false; + const auto completed = query(submit.first); + if (completed == UINT64_MAX || completed < submit.second) return false; } return true; } @@ -45,6 +48,7 @@ inline bool is_upload_chunk_idle(const UploadRingChunk& chunk, FenceQuery&& quer inline void reset_upload_chunk(UploadRingChunk& chunk) { chunk.used = 0; + ++chunk.generation; chunk.submits.clear(); - chunk.unsubmitted_lists = 0; + chunk.recordings = 0; } diff --git a/tests/upload_reservation_check.cpp b/tests/upload_reservation_check.cpp index 9138589c08..2c3ba0ad97 100644 --- a/tests/upload_reservation_check.cpp +++ b/tests/upload_reservation_check.cpp @@ -64,13 +64,13 @@ int main() "existing reservations survive exhaustion"); reset_upload_chunk(chunks[0]); - check(chunks[0].used == 0 && chunks[0].unsubmitted_lists == 0 && chunks[0].submits.empty(), - "reset clears cursor, unsubmitted count and submits"); + check(chunks[0].used == 0 && chunks[0].recordings == 0 && chunks[0].submits.empty(), + "reset clears cursor, recordings and submits"); const auto recycled = reserve_upload_chunk(chunks[0], kAlign); - check(recycled.mapped == storage_a && recycled.offset == 0, - "recycled chunk reserves from start"); + check(recycled.mapped == storage_a && recycled.offset == 0 && recycled.generation == 1, + "recycled chunk reserves from start with incremented generation"); - // Guard fence logic and unsubmitted tracking: + // Guard fence logic, recording holds and device removal: struct MockFence { std::uint64_t completed = 0; }; @@ -80,12 +80,12 @@ int main() return reinterpret_cast(f)->completed; }; - check(is_upload_chunk_idle(chunks[0], fence_query), "chunk without unsubmitted lists or submits is idle"); + check(is_upload_chunk_idle(chunks[0], fence_query), "chunk without recordings or submits is idle"); - chunks[0].unsubmitted_lists = 1; - check(!is_upload_chunk_idle(chunks[0], fence_query), "chunk with unsubmitted lists is not idle"); + chunks[0].recordings = 1; + check(!is_upload_chunk_idle(chunks[0], fence_query), "closed list still held cannot be recycled"); - chunks[0].unsubmitted_lists = 0; + chunks[0].recordings = 0; chunks[0].submits.emplace_back(reinterpret_cast(&fence_a), 10); fence_a.completed = 9; check(!is_upload_chunk_idle(chunks[0], fence_query), "chunk with in-flight submit is not idle"); @@ -98,12 +98,15 @@ int main() fence_b.completed = 4; check(!is_upload_chunk_idle(chunks[0], fence_query), "chunk with second pending queue submit is not idle"); + fence_b.completed = UINT64_MAX; + check(!is_upload_chunk_idle(chunks[0], fence_query), "device removal is not completion"); + fence_b.completed = 5; check(is_upload_chunk_idle(chunks[0], fence_query), "chunk with all queue submits completed is idle"); reset_upload_chunk(chunks[0]); - check(chunks[0].used == 0 && chunks[0].unsubmitted_lists == 0 && chunks[0].submits.empty(), - "final reset clears submits"); + check(chunks[0].used == 0 && chunks[0].recordings == 0 && chunks[0].submits.empty() && chunks[0].generation == 2, + "final reset clears submits and increments generation"); std::puts("upload_reservation_check: all checks passed"); return 0; From 3b737f027ab1fd2ab80068aeffcdea2bb6fd6d13 Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:46:46 +0500 Subject: [PATCH 4/5] startup: pin upload chunks on failed fence signals and check capacity before reset - Mark chunks untracked when queue fence signaling or creation fails so they are never recycled. - Only reset idle chunks in reserve_upload_ring when chunk.capacity >= rounded to protect cached frame copies. - Add unit tests in upload_reservation_check for generation validation and untracked chunks. --- src/startup_stubs/d3d12_xs_device.cpp | 33 +++++++++++++++++++------- src/startup_stubs/upload_reservation.h | 8 ++++++- tests/upload_reservation_check.cpp | 5 ++++ 3 files changed, 36 insertions(+), 10 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index b0129a1998..4865b879d0 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1648,6 +1648,7 @@ bool submit_fence_fails() // the queue must pass before the allocator can be reset. If that fence cannot be created or // signalled, the work is on the GPU all the same: the allocators are marked untracked instead. void note_upload_ring_submits(ID3D12Fence* fence, UINT64 value, const std::vector& lists); +void mark_upload_ring_untracked(const std::vector& lists); void discard_upload_ring(ID3D12CommandList* list); void note_submits(ID3D12CommandQueue* queue, const std::vector& lists, const std::vector& native_lists) @@ -1672,6 +1673,7 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector& lists, else same->second = value; } } else { + mark_upload_ring_untracked(native_lists); for (Wrapper* list : lists) if (const auto found = list_recordings.find(list); found != list_recordings.end()) found->second->untracked = true; static LONG failures; @@ -2469,6 +2471,21 @@ void discard_upload_ring(ID3D12CommandList* list) ReleaseSRWLockExclusive(&upload_ring_lock); } +void mark_upload_ring_untracked(const std::vector& lists) +{ + AcquireSRWLockExclusive(&upload_ring_lock); + for (ID3D12CommandList* list : lists) { + const auto it = recorded_upload_chunks.find(list); + if (it == recorded_upload_chunks.end()) continue; + for (std::size_t chunk_idx : it->second) { + if (chunk_idx < upload_ring_chunks.size()) { + upload_ring_chunks[chunk_idx].untracked = true; + } + } + } + ReleaseSRWLockExclusive(&upload_ring_lock); +} + void note_upload_ring_use(ID3D12Resource* resource, ID3D12CommandList* list) { if (!resource || !list) return; @@ -2593,16 +2610,14 @@ UploadReservation reserve_upload_ring(std::size_t bytes, ID3D12CommandList* list for (std::size_t step = 0; step < upload_ring_chunks.size(); ++step) { const std::size_t index = (upload_ring_active + 1 + step) % upload_ring_chunks.size(); auto& chunk = upload_ring_chunks[index]; - if (is_upload_chunk_idle(chunk)) { + if (chunk.capacity >= rounded && is_upload_chunk_idle(chunk)) { reset_upload_chunk(chunk); - if (chunk.capacity >= rounded) { - reservation = reserve_upload_chunk(chunk, rounded); - if (reservation.mapped) { - upload_ring_active = index; - note_list(upload_ring_active); - ReleaseSRWLockExclusive(&upload_ring_lock); - return reservation; - } + reservation = reserve_upload_chunk(chunk, rounded); + if (reservation.mapped) { + upload_ring_active = index; + note_list(upload_ring_active); + ReleaseSRWLockExclusive(&upload_ring_lock); + return reservation; } } } diff --git a/src/startup_stubs/upload_reservation.h b/src/startup_stubs/upload_reservation.h index 3977e5cf72..8a272b23b0 100644 --- a/src/startup_stubs/upload_reservation.h +++ b/src/startup_stubs/upload_reservation.h @@ -14,6 +14,7 @@ struct UploadRingChunk { std::uint64_t used = 0; std::size_t recordings = 0; std::uint64_t generation = 0; + bool untracked = false; std::vector> submits{}; }; @@ -36,7 +37,7 @@ inline UploadReservation reserve_upload_chunk(UploadRingChunk& chunk, std::uint6 template inline bool is_upload_chunk_idle(const UploadRingChunk& chunk, FenceQuery&& query) { - if (chunk.recordings != 0) return false; + if (chunk.untracked || chunk.recordings != 0) return false; for (const auto& submit : chunk.submits) { if (!submit.first) return false; const auto completed = query(submit.first); @@ -45,6 +46,11 @@ inline bool is_upload_chunk_idle(const UploadRingChunk& chunk, FenceQuery&& quer return true; } +inline bool is_upload_chunk_generation_valid(const UploadRingChunk& chunk, std::uint64_t generation) +{ + return chunk.generation == generation; +} + inline void reset_upload_chunk(UploadRingChunk& chunk) { chunk.used = 0; diff --git a/tests/upload_reservation_check.cpp b/tests/upload_reservation_check.cpp index 2c3ba0ad97..161e1652a4 100644 --- a/tests/upload_reservation_check.cpp +++ b/tests/upload_reservation_check.cpp @@ -69,6 +69,8 @@ int main() const auto recycled = reserve_upload_chunk(chunks[0], kAlign); check(recycled.mapped == storage_a && recycled.offset == 0 && recycled.generation == 1, "recycled chunk reserves from start with incremented generation"); + check(is_upload_chunk_generation_valid(chunks[0], 1), "generation validation matches incremented generation"); + check(!is_upload_chunk_generation_valid(chunks[0], 0), "generation validation rejects stale generation"); // Guard fence logic, recording holds and device removal: struct MockFence { @@ -86,6 +88,9 @@ int main() check(!is_upload_chunk_idle(chunks[0], fence_query), "closed list still held cannot be recycled"); chunks[0].recordings = 0; + chunks[0].untracked = true; + check(!is_upload_chunk_idle(chunks[0], fence_query), "untracked chunk after failed submit fence cannot be recycled"); + chunks[0].untracked = false; chunks[0].submits.emplace_back(reinterpret_cast(&fence_a), 10); fence_a.completed = 9; check(!is_upload_chunk_idle(chunks[0], fence_query), "chunk with in-flight submit is not idle"); From 0a627028ebf5311e42a698338cc594fd7bd07cd2 Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:51:06 +0500 Subject: [PATCH 5/5] startup: discard upload ring holds on command list release and unify cache validation lock - Call discard_upload_ring in release() when a list wrapper refcount hits zero to prevent transient lists from permanently pinning chunks. - Combine generation check and note_upload_ring_use into atomic validate_and_note_upload_ring_use under exclusive lock in frame_copy. --- src/startup_stubs/d3d12_draw.inl | 3 +- src/startup_stubs/d3d12_xs_device.cpp | 42 +++++++++++++++++++-------- 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 190661ff6d..2ca8e3e8e0 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1244,10 +1244,9 @@ bool frame_copy(u64 address, std::size_t bytes, u64* offset, ID3D12Resource** re const auto found = frame_copies().find(key); const bool known = found != frame_copies().end() && found->second.address == address && found->second.content.size() == bytes; if (known && std::memcmp(found->second.content.data(), title, bytes) == 0) { - if (is_upload_chunk_generation_valid(found->second.resource, found->second.generation)) { + if (validate_and_note_upload_ring_use(found->second.resource, found->second.generation, list)) { *offset = found->second.offset; if (resource) *resource = found->second.resource; - if (list && found->second.resource) note_upload_ring_use(found->second.resource, list); return true; } } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 5f2042fd56..07ac0c9bf7 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1030,6 +1030,7 @@ bool retire_reasons_enabled(); void retire_diag_note_release(Wrapper* w); void drop_mesh_lease_owner(Wrapper* w); void discard_mesh_lease_recording(ID3D12CommandList* list); +void discard_upload_ring(ID3D12CommandList* list); void clear_unplaced_buffers(Wrapper* device); ULONG __stdcall release(Wrapper* self) { @@ -1046,7 +1047,9 @@ ULONG __stdcall release(Wrapper* self) linear_buffers().retire(static_cast(self->own().real)); } if (self->own().kind == list_kind && self->own().real) { - discard_mesh_lease_recording(static_cast(self->own().real)); + auto* list = static_cast(self->own().real); + discard_mesh_lease_recording(list); + discard_upload_ring(list); retire_drop_recording(self); } if (self->own().kind == resource_kind && retire_reasons_enabled()) retire_diag_note_release(self); @@ -2487,6 +2490,31 @@ void mark_upload_ring_untracked(const std::vector& lists) ReleaseSRWLockExclusive(&upload_ring_lock); } +bool validate_and_note_upload_ring_use(ID3D12Resource* resource, u64 generation, ID3D12CommandList* list) +{ + if (!resource) return false; + AcquireSRWLockExclusive(&upload_ring_lock); + for (std::size_t i = 0; i < upload_ring_chunks.size(); ++i) { + if (upload_ring_chunks[i].resource == resource) { + if (upload_ring_chunks[i].generation != generation) { + ReleaseSRWLockExclusive(&upload_ring_lock); + return false; + } + if (list) { + auto& chunks = recorded_upload_chunks[list]; + if (std::find(chunks.begin(), chunks.end(), i) == chunks.end()) { + chunks.push_back(i); + ++upload_ring_chunks[i].recordings; + } + } + ReleaseSRWLockExclusive(&upload_ring_lock); + return true; + } + } + ReleaseSRWLockExclusive(&upload_ring_lock); + return false; +} + void note_upload_ring_use(ID3D12Resource* resource, ID3D12CommandList* list) { if (!resource || !list) return; @@ -2506,17 +2534,7 @@ void note_upload_ring_use(ID3D12Resource* resource, ID3D12CommandList* list) bool is_upload_chunk_generation_valid(ID3D12Resource* resource, u64 generation) { - if (!resource) return false; - AcquireSRWLockShared(&upload_ring_lock); - for (const auto& chunk : upload_ring_chunks) { - if (chunk.resource == resource) { - const bool valid = chunk.generation == generation; - ReleaseSRWLockShared(&upload_ring_lock); - return valid; - } - } - ReleaseSRWLockShared(&upload_ring_lock); - return false; + return validate_and_note_upload_ring_use(resource, generation, nullptr); } static bool is_upload_chunk_idle(const UploadRingChunk& chunk)