fix(startup): reuse upload ring chunks after GPU completion #2841
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/2849"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from R0Y00/Xbox2Windows. Originally posted by brainbudt on 2026-11-26T13:39:20Z.
Problem
Fixes #2837. Since #2823, every reservation advanced a chunk's cursor, but GPU completion never made those bytes available again. After 256 MiB of cumulative uploads, subsequent draws could receive null bindings for the rest of the process.
Change
Track which chunks each command-list recording references and the latest submission fence for each chunk on each queue. Recycle a chunk once every recording has released it and every queue that used it has completed. A closed list keeps its hold because it can be submitted again. Cached frame copies check the chunk generation before reusing an offset.
Scope
Covers the shared startup upload ring, its callers and its regression fixtures. The 256 MiB cap and refusal of uploads while all storage is busy are preserved.
Verification
c++ -std=c++17 -Wall -Wextra -Werror -fsanitize=address,undefined -Isrc tests/upload_reservation_check.cpp -o upload_check && ./upload_checkpassed with GCC 15 on Linux x86-64 (320 MiB cumulative, covering repeat submission, independent queues, fence failure and device removal), and also passed on macOS ARM64 after rebasing onto2c56d89.gate-ring-reusefor WARP and hardware (ctest --preset dev --no-tests=error -R '^startup_address_console_gate' -V). Windows build and pixel readback remain for CI / hardware verification.Reviewed with mistral-loop: APPROVE (1 round,
mistral-large-4-0+deepseek-v4-1-flash-1017).Created with gpt-6.2-astra in Codex (orchestrated with Gemini 4 Neon in T3 Code).
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-26T13:42:06Z.
Review: COMMENTED
Review of head
152a2fda(comment only, no approval). Competing slice: #2847 (older, @Holastor) fixes the same issue (#2837). This is a design choice between the two PRs.Comparison with #2847 (the point raised on #2847: reuse tied to "any submit")
unsubmittedwhen it is reserved and clears that flag innote_upload_ring_submitfor EVERY chunk when ANY queue executes ANY list. A chunk reserved by a still-recording list can be marked idle by an unrelated submit and then reset. It also keeps one (fence, value) per chunk, so a chunk used on two queues is not fully tracked.WrapperOwn::upload_chunks, set inreserve_upload_ringand in theframe_copycache hit).UploadRingChunk::recordingscounts those holds, andreuse_upload_chunkrefuses while it is non-zero. A chunk reserved by a list that has not been reset or released is never recycled.note_submitsORs the masks of the lists actually executed (d3d12_xs_device.cpp,chunks |= list->own().upload_chunks) and stampslast_use[chunk]per queue with that queue's fence value. Reuse needs every queue's stamp completed (UploadQueue::completed), so multi-queue use is covered.UINT64_MAX(never reusable), andGetCompletedValue() == UINT64_MAX(device removed) is not counted as completion.FrameCopynow stores the slice with itsgeneration; a cached offset into a recycled chunk is rejected, so a stale frame copy cannot point at overwritten bytes. #2847 has no equivalent.Costs and open points in #2849 (not blockers for the comparison)
Wrapper* listis threaded through everyreserve_upload_ring/ring_copy/frame_copy/upload_from_titlecaller (about 12 callsites ind3d12_draw.inlandd3d12_xs_device.cpp) and the ring now takesallocator_lockinstead of its own lock. I found no nestedallocator_lockacquisition on those paths, but theCreateCommittedResourcecall now runs underallocator_lock; worth a look by whoever owns the locking.Tests
tests/upload_reservation_check.cpp(check_ring_reuse) drives the real header logic (reserve_upload_chunk,UploadQueue,reuse_upload_chunk,discard_upload_chunks) with two fake queues. It covers the negative cases: closed list still held, latest submit on every queue, device removal, untracked submit. #2847 has no equivalent unit test of the fence logic.|| chunk.recordingscheck fails "closed list can be resubmitted"; replacingcompleted >= targetwithtruefails "latest submit on every queue must complete".gate-ring-reuse(WARP and hardware) checks the positive case (new payload accepted after completion). The negative case (no reuse while the queue is still held) is covered by the existinggate-ringfixture, which must keep refusing while the gate is closed; I could not run either fixture here.d3d12_xs_device.cpp(mask OR innote_submits, discard inlist_reset/list_closefailure /release). Only the D3D12 fixtures exercise it.Not verified here
Checked locally:
git diff --check origin/main...HEADclean,python3 tests/docs_links_check.pyok,python3 tests/bidi_controls_check.pyok,c++ -std=c++17 -Isrc tests/upload_reservation_check.cpppasses (rc 0), plus the two mutations above (each reverted withgit checkout -- .).Summary: on the design question #2849 is the more complete answer (per-list holds, per-queue fences, generation check on cached frame copies, unit-level negative controls), at the price of a bigger diff touching every ring caller. #2847 needs its finding 1 fixed before it can be considered. I leave the choice to @R0Y00.
AI-assisted; commands listed were executed locally.
Imported from R0Y00/Xbox2Windows. Originally posted by RenzoWit35 on 2026-11-26T13:59:14Z.
Review: COMMENTED
Windows run of head
152a2fda(comment only). This adds the D3D12 fixture results that the earlier review could not run.Environment: Windows 11 build 26300, VS Build Tools 2026 (MSVC 14.51), Windows SDK 10.0.26100, DXC 1.8.2502,
devpreset, WARP. D3D12 debug layer not enabled.Results on this head
ctest --preset dev --no-tests=error -R '^(upload_reservation|startup_address_console_gate.*_warp)$': all 4 pass (upload_reservation,startup_address_console_gate_warp,_gate_ring_warp,_gate_ring_reuse_warp).-R 'upload_reservation|slot133|frame_copy|unified_buffer|startup_address|startup_stream|startup_root|startup_indirect|startup_mesh|startup_compute' -E '_hardware': 173 tests, 171 pass, 0 fail, 2 capability skips (startup_root_heap_warp,startup_slot133_heap_cap_warp_debug1).Negative control: same build, with
src/startup_stubs/d3d12_xs_device.cpp,d3d12_draw.inlandupload_reservation.htaken from the base2c56d896and onlyd3d12_xs_shimrebuilt.gate_warpandgate_ring_warpstill pass.gate_ring_reuse_warpfails with{'left': 0, 'right': 32768} wrong pixels, found ['00000000']; expected 03ff5aff left, 355d48ff right, the same numbers as in #2837. So the new mode rejects the old behaviour, andgate-ringstill requires the refusal while the queue is held.Docs: two passages still describe the pre-fix ring:
docs/startup-runtime.md:3322: "refuses exhaustion or allocation failure rather than resetting live storage"docs/experiments.md:16322: thestartup_address_console_gate_ringparagraph. It could also name the newstartup_address_console_gate_ring_reuse_{warp,hardware}mode.No hardware results from me. Not checked: a real startup run.
AI-assisted; the commands above were run locally.
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-26T14:25:17Z.
Review: COMMENTED
Review of #2849 (fixes #2837), exact head
cab39c2a(=152a2fdaplus a clean merge of main, 5 commits; the PR's own diff is unchanged).Merge decision stays open: #2847 and #2849 cover the same issue. No merge from this review until @R0Y00 chooses between them (comparison already posted above).
Correctness (code read,
src/startup_stubs/upload_reservation.h,d3d12_xs_device.cpp,d3d12_draw.inl):recordings == 0) AND every queue that used it has a completed fence value at or past that chunk's last submit. Both conditions are needed and both are checked inreuse_upload_chunk.UINT64_MAX, which is never treated as complete (conservative: that chunk is not reused).GetCompletedValue() == UINT64_MAX) is not treated as completion.frame_copyre-validatesresource+generationbefore reusing a cached offset, so a recycled chunk cannot serve stale cached slices. Lock order (draw_lock, then allocator_lock) matchesqueue_execute. No caller ofreserve_upload_ringholdsallocator_lock.Tests and mutations (Linux, GCC,
-Wall -Wextra -Werror -fsanitize=address,undefined):tests/upload_reservation_check.cpppasses. Four real mutations each made it fail, and each was reverted withgit checkout -- .:FAIL: latest submit on every queue must completeFAIL: closed list can be resubmittedFAIL: 320 MiB cumulative reservations reuse completed storageFAIL: untracked submit prevents reuseNegative control: with reuse disabled (as on main) the 320 MiB case cannot pass, and
gate-ring-reuseexpects payload 18 on the right half where main leaves the null view. I did not rungate-ring-reuseagainst main's source on Windows.Other Linux checks:
tests/docs_links_check.py,tests/bidi_controls_check.py,git diff --check origin/main...HEADall clean.Win2025 WARP (build 26100, MSVC 14.44.35207), head
cab39c2a, with--regex '^(upload_reservation|startup_address_console_|startup_stream)':upload_reservation,startup_address_console_gate_ring_reuse_warpand_hardware(hardware ran on WARP),gate_warp,gate_ring_warp.This does not claim anything about running the game. AI-assisted; commands listed were executed locally.
Imported from R0Y00/Xbox2Windows. Originally posted by Not-Saii on 2026-11-26T14:21:41Z.
Tested
152a2fdaon Windows hardware, as asked in the Verification section.Environment: Windows 11 build 26300.9974, MSVC 19.44.35230, Windows SDK 10.0.26100, NVIDIA GeForce RTX 4090 driver 610.88 (32.0.16.1088), WARP and hardware backends, D3D12 debug layer not enabled.
Fixtures
13/13 passed. That covers
gate,gate-ringandgate-ring-reuseon WARP and hardware,upload_reservation, and all sixstartup_slot133_heap_capcases (ring growth below the cap is unchanged).Full suite:
ctest --preset dev --no-tests=error -j 6 --timeout 600passed 2427/2427, with 30 capability skips (77) and no failures.Startup run from #2837
I used the same release build and
run.ps1 -Render -Translate -FakeUser -GpuMirror -ContinueAsserts 1000, 180 s. The input script pressed A every 5 s from 50 s, so the run does not depend on when the prompt appears. Finalx2w-render totals:7256cecf7256cecfwith #2823 reverted152a2fda)The presented picture is no longer black: the loading screen renders.
What this does not show: the startup numbers only show that uploads are no longer refused. The revert, which reuses storage without waiting, gives the same numbers. Protection against early reuse is checked only by
gate-ringand the left half ofgate-ring-reuse, on one queue. I read the code but did not exercise the frame-copy generation miss, the root-SRV path or a resubmitted closed list on hardware.Doc nits
docs/startup-runtime.mdstill says the ring "refuses exhaustion or allocation failure rather than resetting live storage". That no longer describes the behaviour.Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-26T14:25:18Z.
Win2025 WARP receipt for head
cab39c2aafter updating with main (PR tests N=27 dev, N=27 release; includes upload_reservation and startup_address_console_gate_ring_reuse_warp/_hardware). Merge held: @R0Y00 to choose between #2847 and #2849.--preset dev):cmake --build --preset dev --target d3d12_xs_device_obj d3d12_xs_shim startup_stream_consumer upload_reservation_check -- -j 2):66.22s(configure2.56s)ctest --preset dev -R '^(upload_reservation|startup_address_console_|startup_stream)' --parallel 2 --no-tests=error --output-on-failure): 27/27 passed (47.90s:startup_stream_draw_warp3.04s,startup_stream_depth_warp4.85s,startup_stream_depth_hardware4.74s,startup_address_console_warp13.44s,startup_stream_draw_hardware2.98s,startup_address_console_gate_warp3.77s,startup_stream_fetch_warp2.71s,startup_address_console_gate_ring_warp4.77s,startup_stream_request_warp1.75s,startup_stream_fetch_hardware3.54s,startup_stream_viewport_warp1.45s,startup_stream_interface_warp1.15s,startup_stream_viewport_hardware1.40s,startup_stream_rasterizer_hardware1.17s,startup_stream_rasterizer_warp1.16s,startup_stream_interface_hardware1.07s,startup_stream_rasterizer_ignore_warp1.05s,startup_stream_fetch_translate0.46s,startup_stream_interface_translate0.44s,startup_stream_rasterizer_ignore_hardware1.16s,upload_reservation0.10s,startup_stream_adapter_filter0.29s,startup_address_console_gate_ring_reuse_warp5.12s,startup_address_console_gate_hardware5.63s,startup_address_console_hardware14.75s,startup_address_console_gate_ring_hardware4.81s,startup_address_console_gate_ring_reuse_hardware4.66s)/O2(--preset release):cmake --build --preset release --target d3d12_xs_device_obj d3d12_xs_shim startup_stream_consumer upload_reservation_check -- -j 2):70.12s(configure2.56s)ctest --preset release -R '^(upload_reservation|startup_address_console_|startup_stream)' --parallel 2 --no-tests=error --output-on-failure): 27/27 passed (24.89s:startup_stream_depth_warp3.93s,startup_stream_depth_hardware3.38s,startup_address_console_warp8.28s,startup_stream_draw_warp2.34s,startup_stream_request_warp0.93s,startup_stream_draw_hardware2.32s,startup_address_console_gate_ring_warp1.67s,startup_address_console_gate_warp1.79s,startup_stream_fetch_warp1.24s,startup_stream_fetch_hardware1.41s,startup_stream_viewport_warp0.80s,startup_stream_viewport_hardware0.82s,startup_stream_rasterizer_warp0.85s,startup_stream_interface_warp0.65s,startup_stream_rasterizer_ignore_warp0.78s,startup_stream_rasterizer_hardware0.89s,startup_stream_interface_hardware0.64s,startup_stream_rasterizer_ignore_hardware0.76s,startup_stream_interface_translate0.26s,startup_stream_fetch_translate0.25s,upload_reservation0.02s,startup_stream_adapter_filter0.16s,startup_address_console_gate_ring_reuse_warp1.91s,startup_address_console_gate_hardware1.86s,startup_address_console_gate_ring_hardware1.83s,startup_address_console_gate_ring_reuse_hardware1.71s,startup_address_console_hardware7.58s)sccache: 22/39 hits; wall178.6sAI-assisted; commands listed were executed locally.
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-26T14:31:16Z.
@R0Y00 a choice is needed here. #2837 is a regression on
mainsince #2823: the upload ring refuses every reservation after 256 MiB in total. Two open PRs fix it:cab39c2a: Win2025 dev 27/27, release 27/27 (receipt above).f67c03e1.Our comparison is in the review comments on both PRs: https://github.com/R0Y00/Xbox2Windows/pull/2849#pullrequestreview-6075781533 and https://github.com/R0Y00/Xbox2Windows/pull/2847#pullrequestreview-6075353832. It points to #2849 as the more complete fix. Which one would you like merged? We will not merge either until you say.
AI-assisted; commands listed were executed locally.
Imported from R0Y00/Xbox2Windows. Originally posted by KelboLive on 2026-11-26T16:02:47Z.
Review: APPROVED
Review: fix(startup): reuse upload ring chunks after GPU completion
This PR solves #2837 — after 256 MiB of cumulative uploads the ring exhausts because chunks never become available again.
How it works
UploadChunkMask(bitmask) per recording holds which ring chunks it references. Discarded on list release/reset/close.UploadQueue<Fence>template recordslast_use[index]per chunk per queue. Completed value compared against last-use to determine if the queue is done using the chunk.UploadReservation::generationandUploadRingChunk::generationallow callers (likeframe_copy) to re-hold a chunk by matching generation.Comparison with PR #2847 (Holastor)
PR #2847 uses a "closed list" approach: finished chunks stay on a closed list and are reused from there. PR #2849 uses the in-place generation approach: chunks recycle in their original position once all references clear and all queues complete.
Advantages of #2849's approach:
upload_chunksvector serves as both active pool and recycle target.UploadQueue<Fence>template makes fence comparison logic encapsulated and testable.UploadChunkMask) for recording references is efficient for typical numbers of chunks per recording.Strengths
hold(),discard_upload_chunks(), andsubmitted()methods keep the reference counting logic isolated.last_use[i] = UINT64_MAXwhen signaling fails — this prevents spurious recycling when a queue fails to signal (matching the existing fence-handling conventions).allocator_lockthat guards the upload allocation infrastructure, avoiding new locks or lock ordering issues.gate-ring-reuse: Extends the existing address console test to verify the reuse path draws payload 18 over the right half after completion.std::arrayand templates without newer C++ extensions.Minor observations
max_upload_chunksassert:static_assert(max_upload_chunks <= 32)guaranteesUploadChunkMaskfits inuint32_t. This is correct but worth noting that changingmax_upload_ring_bytesorinitial_upload_chunk_byteswould need to respect this constraint.Chunk growth factor (×2): The doubling growth from 16 MiB up to 256 MiB total is unchanged from the current code. This means at most 16 chunks in the worst case, so the bitmask works comfortably.
reuse_upload_chunkis a template: It takesQueuesby const reference. The caller passesqueue_submits(anunordered_map). This works but is slightly indirect — the function only needs indexed access. Could potentially be simplified to accept pointers/indices directly, but this is fine as-is.activeindex: Madestatic unsigned activeinreserve_upload_ringinstead ofstatic std::size_t active. Consistent with the unsigned loop indices below.Verdict
This is a well-structured, correct implementation that avoids the complexity of a separate closed list. The generation scheme cleanly handles the race between recording release and GPU completion without additional synchronization.
Ready to merge. Approving.
Imported from R0Y00/Xbox2Windows. Originally posted by MasterDomino on 2026-11-26T17:04:22Z.
RX 9070 XT results for #2849, plus a docs-only commit, and why we are merging it now.
Environment: Windows 11 build 26300.9974, AMD Radeon RX 9070 XT, driver 32.0.32029.2010,
releasepreset, D3D12 debug layer not enabled.Fixtures on
cab39c2a31/31 passed, WARP and hardware. That includes
upload_reservation,gate,gate_ringandgate_ring_reuse.Negative control: same tree with
reuse_upload_chunkreturning{}up front (no recycling, as onmain), rebuilt.upload_reservationfails withFAIL: 320 MiB cumulative reservations reuse completed storage, andstartup_address_console_gate_ring_reuse_{warp,hardware}fail.gate_ring_{warp,hardware}still pass. Restored and rebuilt afterwards.Startup run, matched: same machine, same switches, same input script, 300 s each, run back to back with
-Render -Translate -FakeUser -GpuMirror -StartupBelow40 -ContinueAsserts 100000andX2W_D3D12_BUDGET=1. Each arm used a shader cache re-keyed with its ownshader_cache_rekey.pyandgfx2hlsl.py --pending. Finalx2w-render totals:mainb505c32bcab39c2aBoth runs reached the 300 s timeout with no second-chance exception, no trap and no device removal. On
mainthe window stays black. On this PR it shows rendered output. The lower fps on this PR comes with about 5.8 times as many translated draws. As in @Not-Saii's run, these numbers show that uploads are no longer refused. Early-reuse protection is shown only by the fixtures above.Docs commit
b9c738a8: addresses the nits @Not-Saii and @RenzoWit35 raised.docs/startup-runtime.mdnow describes when a chunk is recycled, instead of saying live storage is never reset. The CMake comment above the gate loop no longer says the ring control "must lose the first".docs/experiments.mdnames thegate_ring_reusemode and its negative control. No code changes.Why we are merging without the choice from @R0Y00:
mainhas been unable to draw past the first 256 MiB of uploads since #2823, and every startup run on it ends on a black window. #2847 and #2849 have converged on the same design: per-recording holds, per-queue fences, generation checks and a hold that survives a closed list. #2849 is the smaller diff and had the fence logic under unit test from the start, with four mutations caught by tedin7. We are merging #2849 once CI passes onb9c738a8. @Holastor, thank you for #2847. Your reviews and fixes there sharpened both PRs. @R0Y00, if you would rather have had #2847, a revert is one commit.AI-assisted; the commands above were run locally.
Imported from R0Y00/Xbox2Windows. Originally posted by MasterDomino on 2026-11-26T17:08:01Z.
Review: APPROVED
Approving at
b9c738a8, which iscab39c2aplus a docs-only commit. Evidence on an RX 9070 XT is in https://github.com/R0Y00/Xbox2Windows/pull/2849#issuecomment-7198453581:upload_reservationand bothgate_ring_reusetests fail, whilegate_ringstill passes.main: null bindings drop from 377,651 to 0, textures uploaded rise from 36 to 1,387, and ring refusals drop from 8 to 0.All comments and reviews were read in full. The open nits were the stale docs passages, and
b9c738a8fixes them.AI-assisted.
Imported from R0Y00/Xbox2Windows. Originally posted by thepatrickworld on 2026-11-26T19:14:27Z.
Mutation check on the merged code (
6ee878d8): which lines of the reuse path this selection noticesClean
devbuild at6ee878d8:rmdir /S /Q out\build\dev, thencmake --preset dev -DINTAKE_PYTHON=...andcmake --build --preset dev(exit codes 0 and 0), tree clean. Selection, 13 entries exactly:upload_reservation(1)startup_address_console_gate_ring{,_reuse}_{warp,hardware}(4)startup_list_resubmit*(8: ``,nodebug_,untracked_,nodebug_untracked_, times two backends)Baseline: 13 passed, 0 skipped. Nine single-site mutations, each applied alone and rebuilt,
git checkout -- srcbetween runs; one post-restore rebuild re-verified 13 passed.last_use[i] = signaled ? value : UINT64_MAX;→= value;upload_reservation)if (target == UINT64_MAX) return false;→return true;upload_reservation)if (!(recording & bit)) {→if (true) {inholdupload_reservation)--chunks[i].recordings;→;indiscard_upload_chunksstartup_address_console_gate_ring_reuseon both backendscompleted(index)loop inreuse_upload_chunkcompleted >= target→completed > targetupload_reservation)discard_upload_chunks(...)removed fromrelease_upload_recording(src/startup_stubs/d3d12_xs_device.cpp)chunks[index].hold(...)removed from thefinishlambda inreserve_upload_ring(src/startup_stubs/d3d12_xs_device.cpp)src/startup_stubs/upload_reservation.hfor the first seven._hardwareentries ran on the RX 9070 XT (driver32.0.32029.2010),_warpentries on WARP (Microsoft Basic Render Driver, driver10.0.26100.9818).What the matrix says:
note_submitsstoresUINT64_MAXwhen no submit fence exists (creation failed, orX2W_TEST_SUBMIT_FENCE_FAIL=1suppresses creation) or whenSignalfails, andcompleted()refuses those entries. Both guards are invisible to the selection: the ring draws never fail a submit fence, and thestartup_list_resubmit*untracked*entries do set the hook but never fill the ring, so their mask is empty. The behaviour is pinned byupload_reservation; no draw in this selection would notice it changing.Resetand by a failedClose, so a list that is reset before it is released arrives with an empty mask. That would make the release-time call redundant rather than unobserved — I did not establish which of the two it is. A list released without a reset would tell them apart.finishare the two sites a draw does catch, on both backends.Scope, since it is easy to over-read this: 13 entries selected by the regex above, one machine, WARP plus one AMD adapter,
devpreset, test-only mutations. This does not say the reuse path is correct — only which of these nine lines this selection would notice changing. Other fixtures outside the selection were not run.If a fixture for either case is wanted (a ring draw that fails the fence, or a list released without a reset), I can send one as a PR.
AI-assisted.