Repository navigation
runtime, d3d12: memory leak fixes from one sweep (RT-LEAK-SWEEP) - #2569
adrianmjim wants to merge 384 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
The tests need deterministic GPU completion control and explicit Vulkan buffer-device-address enablement to avoid false failures, validation errors, and driver-dependent behavior.
3 open issues
What changed in this PR
This PR addresses thirteen memory-retention and resource-lifetime issues in the runtime’s D3D12-to-Vulkan layer and Xbox ABI proxies. It also adds native Windows memory diagnostics.
Changes:
- Reclaims upload memory and stale bookkeeping, shares shader copies, and ties scratch lifetime to GPU completion.
- Improves allocation retries and texture cleanup, with additional slot-70 image retirement remaining opt-in.
- Adds synthetic regression tests and documents lifetime guarantees, diagnostics, and switches.
| File | Description |
|---|---|
| runtime/test/xs_proxy_mock_test.cpp | Tests allocator-owned upload reuse and cleanup. |
| runtime/test/xmem_test.cpp | Checks release notifications identify the freed range. |
| runtime/test/xbox_list_cut_spares_test.cpp | Tests idle spare lists release recordings and references. |
| runtime/test/xbox_bvh_builder_test.cpp | Checks scratch retention through GPU completion. |
| runtime/test/pso_stream_test.cpp | Tests bytecode sharing, collisions, and concurrent captures. |
| runtime/test/mem_probe_vmmap_test.cpp | Tests Windows memory classification and reporting. |
| runtime/test/d3d12_zero_image_retry_test.cpp | Tests shared-image retries and backoff. |
| runtime/test/d3d12_title_buffer_fallback_test.cpp | Tests failed title-buffer allocation and retry throttling. |
| runtime/test/d3d12_shadow_gpu_releases_test.cpp | Checks released-range cleanup in GPU copy modes. |
| runtime/test/d3d12_code_base_share_test.cpp | Tests shared shader arena copies and release. |
| runtime/test/console_heap_slot_records_test.cpp | Checks bucket counts follow live records. |
| runtime/test/command_list_test.cpp | Tests epoch cleanup when recordings are dropped. |
| runtime/src/vulkan_backend.h | Retains shim-owned objects until submissions complete. |
| runtime/src/title_va_alias.h | Exposes pending removal counts for tests. |
| runtime/src/title_texture_refresh.h | Exposes texture range-index size for tests. |
| runtime/src/title_texture_memory.h | Adds texture-page commitment checks. |
| runtime/src/mem_probe.h | Adds native Windows process-memory reporting. |
| runtime/src/console_heap_slot_records.h | Removes buckets when their last live record leaves. |
| runtime/src/command_list.h | Allows closed lists to drop their recordings. |
| runtime/src/command_list_epochs.h | Supports recordings without an active epoch stamp. |
| runtime/shims/xmem.cpp | Reports reservation ranges for whole-allocation releases. |
| runtime/shims/d3d12_xs_pso_stream.h | Documents shared shader-bytecode ownership. |
| runtime/shims/d3d12_xs_pso_stream.cpp | Interns identical shader bytecode across records. |
| runtime/shims/d3d12_xs_device.cpp | Rewinds allocator uploads and drops idle spare recordings. |
| runtime/shims/d3d12_com.h | Declares lifetime helpers and diagnostic test hooks. |
| runtime/shims/d3d12_com.cpp | Tracks shim-owned objects and releases dropped recordings. |
| runtime/README.md | Documents memory controls and diagnostics. |
| runtime/CMakeLists.txt | Registers new regression tests and variants. |
| docs/d3d12_xs_console_abi.md | Documents spare-list recording cleanup. |
| docs/d3d12_vulkan.md | Explains sharing, reclamation, and texture-retirement limits. |
| docs/d3d12_command_objects.md | Documents allocator-owned upload lifetimes. |
Review effort: Balanced
lixonik
left a comment
There was a problem hiding this comment.
Reviewed and verified at head f4cc2b33f (Windows 11, MSVC 19.44, Ninja Release, Rust 1.98.1, LEONIDA_VK_VALIDATION=1).
Verification
- C++ runtime (
untime/): built all 13 added/modified test targets plusgta6rt:ctest(LEONIDA_VK_VALIDATION=1): 13/13 passed (xs_proxy_mock,pso_stream,command_list,xmem,xbox_bvh_builder,d3d12_shadow_gpu_releases,d3d12_existing_heap,d3d12_zero_image_retry,d3d12_title_buffer_fallback,xbox_list_cut_spares,d3d12_code_base_share,mem_probe_vmmap,console_heap_slot_records), 0 Vulkan validation errors on NVIDIA GeForce RTX 5070.python -I scripts/check_no_game_data.py: clean.
- Rust (d3d12/):
cargo test -p leonida-hle -p leonida: 188/188 passed (0 failed, 2 ignored).cargo test -p leonida-gpu --lib: 493 passed, 4 failed (46 ignored). Re-tested the 4 failures (descriptor::host::tests::views_off_their_elements_get_a_copy_of_their_bytes,indirect::tests::batch_tables,indirect::tests::host_list_budget_starts_empty_at_each_submission,indirect::tests::warp_batch_charges_every_execution) on cleanmain(33db04a70) with--test-threads=1: all 4 fail identically on cleanmain(pre-existing on this host), while all 14 newleonida-gputests introduced by this PR pass.
Review notes
- Needs rebase/merge with
main(blocking merge): two content conflicts againstmain(33db04a70) inruntime/shims/d3d12_xs_device.cppandruntime/test/xs_proxy_mock_test.cppdue to recentmaincommits10eb17825,038980a38, and53ed711b8. - Note on Copilot's BDA comments (false positive):
vktest::Deviceunconditionally setsenable12.bufferDeviceAddress = VK_TRUEatruntime/test/vk_test_device.h:459, and bothd3d12_title_buffer_fallback_testandxbox_list_cut_spares_testrun with 0 validation errors underVK_LAYER_KHRONOS_validationon RTX 5070. - Minor test robustness note (
untime/test/xbox_bvh_builder_test.cpp:603-604): the assertionsreset_sentinel.refs.load() > 1/release_sentinel.refs.load() > 1passed here, though as noted in the inline review, if the GPU completes the BLAS build beforeexecute_syncdrains completed pins on return, those assertions could become timing-sensitive on faster drivers.
Overall the 24 leak fixes (shared code-base arena copies, PSO bytecode interning, command-list drop/epoch release, slot-record bucket pruning, owned title-image retirement, thin-upload drop, idle pool trimming, etc.) are well-scoped and clean; happy to approve once rebased cleanly onto main.
GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, VK_LAYER_KHRONOS_validation 1.4.363).
AI-assisted (Antigravity, Gemini).
lixonik
left a comment
There was a problem hiding this comment.
Re-verified after the main merge in 098342d02 (Windows 11, MSVC 19.44, Ninja Release, LEONIDA_VK_VALIDATION=1).
Verification at 098342d02
- Reviewed the merge resolution in
runtime/shims/d3d12_xs_device.cpp,runtime/test/pso_stream_test.cpp, andruntime/test/xs_proxy_mock_test.cpp: cleanly preserves bothmain'srelease_child_reference/test_view_instancing_is_captured/ queue-fence ownership assertions and this PR'supload_allocator_gone/ bytecode-interning / mapped-upload additions. - Rebuilt
xs_proxy_mock_test,pso_stream_test,d3d12_existing_heap_test,xbox_list_cut_spares_test, andgta6rt. ctest(LEONIDA_VK_VALIDATION=1): 4/4 passed (0 validation errors), in addition to the full 13/13 C++ + Rustleonida-hle/leonida/newleonida-gpuverification atf4cc2b33f.
GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, VK_LAYER_KHRONOS_validation 1.4.363).
AI-assisted (Antigravity, Gemini).
GrahamboJangles
left a comment
There was a problem hiding this comment.
Reviewer pass over the sweep as a whole (nightly review; verified against current main b0c572464).
Claims check out. All 24 RT-*/RS-* item IDs link to exactly one claiming: line each in #1608 (by this branch's author), and the two geometry items (RT-GEOMETRY-VIEWS-CONTAIN, RT-DRAW-VIEWS-UNCHANGED) to #2570. No open PR duplicates any of the 26 IDs (gh pr list --search per ID).
Conflict notes check out. #1521, #2267 and #2085 are all still open, and the file overlaps are real: runtime/shims/d3d12_vulkan_device.cpp + runtime/test/d3d12_draw_test.cpp with #1521; runtime/CMakeLists.txt, runtime/README.md, runtime/test/d3d12_existing_heap_test.cpp with #2267; runtime/shims/d3d12_geometry_views.h + runtime/test/geometry_views_test.cpp with #2085. GitHub says mergeable but UNSTABLE — that matches: landing order against those three needs to be settled before merge.
Tree checks (local merge against fresh main b0c572464).
- Automatic merge is clean;
git diffgives 51 files, +5543/−294 — same as GitHub's stats. git diff --check: no whitespace findings.scripts/check_no_game_data.pyover all 51 changed files: clean.- Docs tests: current
mainalready fails four of them (test_docs_env_varsonLEONIDA_CLWB_PATCHatruntime/src/cpu_emulation.h:366;test_docs_cli_flagson 56 flags ind3d12/docs/*;test_docs_python_depsonport_ctl.pyvs AGENTS.md;test_docs_repo_pathson 14 backticked paths). On the merged tree the failure lists are byte-identical, so this PR adds zero new docs-test failures — the red ones stay red and belong to #2550/#2551/#2552 and to whoever landed the CLWB patch without documenting it. - Sampled commit structure matches the PR body's promise: each fix is its own commit with its own test and quantified before/after (e.g.
5fa9c200fRT-UPLOAD-ARENA-REWIND: 25 chunks → 1 over 200 mock frames, plus a--upload-rewind-offctest for the switch;b179a98a0RS-HOST-LIST-ALLOCATOR-PEAK:a_submitted_list_keeps_no_host_list_until_its_resetassertsheld(&lists) == 0after submit rounds). Commit messages state mechanism, fix, and test scope, including honest hedges (RT-SLOT70-OWNED-RETIRE opt-in after a second review found early-retire pixel risk; RT-MEM-PROBE-WINDOWS's test says it does not build ond44285197).
What I could not verify here: the native C++/Rust test suites — no CI has run on leaks/all (gh pr checks 2569: no checks reported, likely because the head is a fork), and these tests need the runtime build environment. Green tests are on the maintainers' side until CI runs them on Linux.
Two protocol gaps to close before merge:
- AGENTS.md:133 requires the PR to say it was AI-assisted, what was tested, and on which GPU and driver — the body has no such statement for any of the 26 fixes.
- Given no CI signal on this PR and three open conflicting PRs, per-fix branches
adrianmjim/leonida:leaks/<name>are exactly the right fallback if the bundle has to be split; a line about intended landing order (vs #1521/#2267/#2085) would settle theUNSTABLEstate.
No approval given from this pass: the native tests are unrun, so this is verification-of-claims, not a substitute for a CI-green bundle.
|
Red (
|
lixonik
left a comment
There was a problem hiding this comment.
Re-verified updated head abdb93f0e (covering the two newly added leak fixes RT-GEOMETRY-VIEWS-CONTAIN and RT-DRAW-VIEWS-UNCHANGED, plus the clean main d48a957bb merge).
Code audit (098342d02..abdb93f0e):
RT-GEOMETRY-VIEWS-CONTAIN(runtime/shims/d3d12_geometry_views.h,d3d12_vulkan_device.cpp):outer_index +contained_tracking cleanly serve inner ranges from ready outer views,kListsPendingdefers command-list epoch stamping untilon_retirecompletes, andcopy_title_rangeopts out withcontain = false.RT-DRAW-VIEWS-UNCHANGED(runtime/shims/d3d12_com.cpp,runtime/src/command_list.h):OMSetRenderTargetsandset_vertex_buffersmarkdraw_views_stale_only on actual bound view changes.
Verification at abdb93f0e (Windows 11, MSVC 19.44, Ninja Release, LEONIDA_VK_VALIDATION=1):
- Built
geometry_views_testandd3d12_draw_test. ctest -R '^(geometry_views|d3d12_draw|d3d12_draw_views_sharing)$': 3/3 passed (0 validation errors).python -I scripts/check_no_game_data.py: passed.
GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, VK_LAYER_KHRONOS_validation 1.4.363).
AI-assisted (Antigravity, Gemini).
|
Under Wine the new The region walk sees the 64 MiB ( The three Not checked by a second agent or human yet. AI-assisted (Claude Code). |
lixonik
left a comment
There was a problem hiding this comment.
Re-verified updated head eb145de6f covering the newly added fixes (RT-DEVICE-LOST-DRAIN, RS-ARENA-ONE-COPY, RS-SHADER-CONTAINER-FREE, RS-DSTORAGE-SCRATCH, and the shared leonida-hle test allocator).
Code audit (abdb93f0e..eb145de6f):
RT-DEVICE-LOST-DRAIN(runtime/src/vulkan_backend.h):kept_after_losspreservesbindless_slotandimage_viewordering until teardown,drain_lostcompacts kept items in-place safely in the ring buffer and destroys the rest outsidemutex_,defer_destroydrains pre-loss items once vialost_queue_drained_.exchange(true, acq_rel), andexecute_nowre-checksis_device_lost()after takingtracker_mutex_beforebindless_prepare_.- Rust additions (
leonida-hle/src/test_alloc.rs,dstorage.rs,apu.rs;leonida-gpu/src/memory.rs,shadow.rs,pipeline.rs,pipeline/host.rs): cleanly unify the test counting allocator, reuse per-worker DirectStorage scratch buffers within the 16 MiB bound, drop translated shader containers once metadata is captured, and avoid double-copying opened arenas.
Verification at eb145de6f (Windows 11, MSVC 19.44, Ninja Release, LEONIDA_VK_VALIDATION=1):
- C++: built
vk_deferred_destroy_lost_test;ctest -R '^vk_deferred_destroy_lost$': 1/1 passed (0.23 s, 0 validation errors). - Rust (
d3d12/):cargo test -p leonida-hle --lib -- --test-threads=1: 189 passed, 0 failed, 2 ignored (includingpackets_decode_without_memory_of_their_own,compressed_requests_reuse_the_workers_buffers, andstaging_counts_every_buffer_a_request_holds).cargo test -p leonida-gpu --lib memory:: -- --test-threads=1: 4 passed, 0 failed (includingan_arena_is_in_the_pcs_memory_onceandan_arena_sends_up_only_the_dwords_the_title_changed).cargo test -p leonida-gpu --lib shadow:: -- --test-threads=1: 58 passed, 0 failed, 1 ignored.cargo test -p leonida-gpu --lib pipeline:: -- --test-threads=1: 37 passed, 1 failed, 7 ignored --pipeline::tests::translated_shaders_let_their_containers_gopassed; the sole failure is the untouchedpipeline::host::tests::depth_bounds_pipeline_loads_and_filters_draws(root_signaturereturningE_INVALIDARGon this host's inboxd3d12.dll).
python -I scripts/check_no_game_data.py: passed.
GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, VK_LAYER_KHRONOS_validation 1.4.363).
AI-assisted (Antigravity, Gemini).
|
Thanks. Taken as you suggest: in |
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
|
Native Windows C++ runtime check of
Overall 3/3 on the head and 1/1 on the ancestor, no CTest skips. Focused C++ synthetic checks only. AI-assisted (Codex). |
lixonik
left a comment
There was a problem hiding this comment.
Focused follow-up on RS-PIPELINE-LIBRARY-FINGERPRINT at 962bc1601 merged locally with main aa918e5d9. Windows 10 22H2, Rust/MSVC, diag profile. The 15 library tests and one additional local file-lock fixture passed, including concurrent saves and fingerprint handling.
The extra fixture held the old cache file open without delete sharing and saved a synthetic blob for the new fingerprint. The implementation wrote the replacement to the waiting file. A read while the old file was locked correctly returned an empty library; after releasing the handle the new file was promoted and its bytes were read under the new fingerprint. This check only covers the Rust pipeline library lane of the sweep.
AI-assisted.
Native Windows 11 + NVIDIA GeForce RTX 3090 Verification (
|
…renas hold() was called from place_part, which by_address_opened (opened_side) also uses for the runtime's own arenas: memory the title never frees. Each arena was held for good, so WAITING never dropped back to 0 and tick() reaped every 100 ms (an AddRef/Release per arena, the HELD and PENDING locks) even with LEONIDA_INPLACE off, and every arena buffer carried one extra reference. The hold is now taken in place_for, the title-memory path, after place_part succeeds; place_part says why. Test: inplace::tests::warp_memory_placed_by_address_is_not_held (WARP). With the hold put back into place_part it fails with "an arena's memory is not held" (left 1, right 0); it passes with the fix. The device tests that stand for place_for place through place_held (place_part + hold).
…lists With LEONIDA_UPLOAD_AHEAD, a job whose staging buffer could not be had recorded no copy, but finish() still set uploaded, cleared dirty, noted what the host copy holds and set ahead to DONE: a placed host texture that was never written was taken for filled, ahead::there() kept the draws from uploading it, and a later upload skipped the first upload's aliasing barrier. finish() now gets which jobs were recorded; one that was not goes back to LISTED with its upload state untouched, so the next list that samples it uploads it (the first upload if none ran). What waits for it is still told. The worker also took the buffer with bytes_to_fill() after all the detilings: a list's submission that claimed the texture after listed() gave up waiting could let go of the buffer in between, and the worker then copied a new all-zero buffer over what the list brought. It now takes the buffer right after each job's detiling, and a job with none records nothing (a video's plane that found nothing to detile included). Test: texture::ahead::tests::a_job_that_copied_nothing_leaves_the_texture_to_the_lists (device, 128x128 BC7). The job's buffer is let go and none can be had (test-only TEST_NO_STAGED, by resource); red before: "nothing was copied: not filled ahead" (there() was true). Green after, and a list then uploads level 0 as the memory holds it.
…k in the last 250 ms send::let_go_idle used an idle time of 0 while the PC's memory was pressured, so each sweep let go of every spare, including buffers given back milliseconds before: the pipeline's working set. The next some 30 submissions then made theirs anew (above pool::small::MOST a committed resource each, 1.6 ms an upload buffer in docs/findings.md) while the ones let go still waited bury_lag submissions in retire_resource's line, so pressure raised what was held instead of lowering it, every second. Now idle_for gives PRESSED_MS (250 ms) under pressure; the trim() and let_go_idle docs say so. Test: send::pool_tests::under_pressure_what_just_came_back_stays, spares given back 1000, 100 and 16 ms before a pressured sweep. With 0 all three went ([1, 2, 3]); with the floor only the one a second old ([1]).
|
New round in this PR: Where the card's time goes. A
Our lists over the card copies of title memory are not in that table. They are now timed on the card (
So the runtime's own card work is some 5-7 ms of the 35. The rest is the title's translated shaders. Three changes, each behind a switch, measured in one
What the run settles:
What is left of our own card work is mostly the clamps, which need knowing what the title's culling programs write (the translator), and the ranges sent up, which are title CPU writes the card has to see. Details are in Tests: |
|
Independent check on Windows (not the author), at
Environment: Ryzen 9 7950X3D, Windows 11 Pro 10.0.26200.9711, NVIDIA RTX 4070 Ti SUPER (driver 621.01), Rust 1.98.1 pinned. This covers the GPU crate only; the runtime-side leak cases need a game run, which I did not do. AI-assisted: yes (opencode). |
What was wrong: the_pass_looks_only_at_slots_written_since_the_look_ahead (crates/leonida-gpu/src/draw.rs) read the process's frame (frame.rs FRAME) once and gave it to the look and the pass, but had a draw's table take slots 7 and 4 with HostHeap::slot_tabled, which stamps the frame of that moment. The tests beside it begin frames of the same process: the frame waits' test (frame::tests::waits_end_on_ticks_and_count_frames, through frame::wait) and five resource tests (frame::test_advance). A frame begun between the test's read and the stamp left slot 7 no table's at the test's frame (HostHeap::copied_tabled), so the look ahead looked at it too: 9 slots for 8. It failed once in three runs of the lib tests with diagnostics, and never alone. What changes: in tests, HostHeap::slot_tabled_in has a table take a slot in a given frame; the test takes slots 7 and 4 in its own frame. Tests only: the runtime is unchanged. Test: with one frame begun right after the test reads its frame, it failed every time (left 9, right 8); with the change it passes with 20 frames begun there and 20 more before slot 4 is taken. The draw, drops, dxgi, fence, fg and frame tests together, 8 threads, where the frame waits' test is the only one that begins frames: 24 of 40 runs failed before, each with the frame one further at the look than when the test read it; 0 of 40 after. The whole lib suite with diagnostics, 8 threads: the test failed in 1 of 12 runs before, 0 of 12 after (other tests failed there, as before). leonida-gpu lib 803 passed / 53 ignored, with diagnostics 869 / 53, 4 threads, RX 7900 XT.
…A_AB can flip it What was wrong: landsame::on() (host/landsame.rs:71-78) read the variable once into a OnceLock, so LEONIDA_AB could not weigh it in the same scene as everything else, and it was asked separately where a plan's capture passes are chosen (host.rs:5984), where the notes of sends are let go at a landing (host.rs:6313, landsame::forgotten(..., landsame::on())), where a fetch is noted as maybe newer than later captures (host.rs:6485) and for the frame line (host/present.rs:423). Made flippable as it was, a flip between a plan's making and its landing would let go the notes of sends a capture still in the air is merged against (its older bytes then go over title bytes that went up after it), or leave a fetch unnoted that is newer than a capture in the air (that capture then goes over the fetch's later shader bytes). What changes: the switch is read through crate::asked! (off by default, =1 on, LEONIDA_AB flips it per phase in diagnostics builds) once per plan, in Host::card_before right after its send is numbered, and kept in the plan (landsame::Capturing); the capture passes follow it. What a landing keeps for later captures, the notes of sends and the fetches noted as maybe newer, is kept while any plan alive was made to capture (landsame::capturing, counted under the order of the queue before the plan's send number can be seen by a fetch), not by the switch at the landing. The frame line is taken every period and also counts the plans of the relay landed that were made to capture and those made to fetch. The README's bullet says so, with the first game run's numbers. Switch: LEONIDA_LAND_IN_SUBMISSION=1 (off by default), flippable with LEONIDA_AB. Tests (on the host's card, host/landsame.rs card_tests): flights_made_on_and_off_in_turn_land_every_byte (flights made on, off, on, off; a title write after their sends; the second's fetch newer than the third's capture) and a_flip_after_a_plan_is_made_changes_nothing_it_does. Both fail with the global switch read at the landing again (the third capture merged over the later fetch, the title's bytes lost) and pass with the plan's own decision.
… title memory What was wrong: inplace.rs:35 said tile mappings into a heap opened on memory the process has remove the device, measured only on the software adapter, and nothing said whether the asks turned down as view memory not one run of a committed section (inplace.rs place_for, kept_from; 1,838 in a title run with LEONIDA_INPLACE=1 LEONIDA_SECTION_COMMIT=1) could be held by a reserved buffer whose tiles follow the title's scattered pages. What changes: inplace/tiled.rs. With LEONIDA_INPLACE_PROBE=1, after the in-place probe, a probe on a device of its own (ID3D12DeviceFactory, not kept as the process's device, so a refusal removes only that one; not run where the factory makes none): scattered tiles, two on one page, on a heap of ours and on a committed section opened as a heap; the card's reads of the CPU's writes, a shader's reads and unordered-access writes, a remap, an unmap; UpdateTileMappings of 1, 64 and 1024 tiles (CPU time and time to a fence) and the card's reads through tiles, a placed buffer and an upload buffer; after a loss, one tile on heaps that differ in one thing says which part is refused; a VERDICT line. LEONIDA_INPLACE_PROBE_TILES=0 leaves it out. On the RX 7900 XT (tier 4) and the software adapter: the mapping onto any opened heap removes the device (DXGI_ERROR_INVALID_CALL), as onto a heap of ours made shared and cross-adapter, while shared alone takes it: Direct3D takes no tiles in a cross-adapter heap, which every opened heap is. Everything holds on a heap of ours; 1/64/1024 tiles a range each cost 19/23/2,021 us of CPU and 0.2/1.1/20 ms to a fence; reads through tiles as fast as placed. In diagnostics builds, with LEONIDA_INPLACE on, a line every ten seconds beside the in-place line counts those asks by what tiles could make of them (every page in a view of a committed section; a reserved section; holes; views off the 64 KiB lines), their pages and sections, and the title's mappings and unmappings over those still alive. Only counted, no switch: a walk over the views of each such ask, a relaxed load per mapping while none is alive, the list of copies every ten seconds. Tests: card_tiles_over_a_committed_section (ignored, on the card), warp_tiles_probe_on_a_device_of_its_own, and the census's classification and counts on synthetic view layouts (red with the reserved-section check, the overlap test or the cross-adapter reading taken out).
…to stand beside it What was wrong: inplace/tiled.rs:62-65 ran the tiles probe with every LEONIDA_INPLACE_PROBE=1 (LEONIDA_INPLACE_PROBE_TILES on unless 0), though it removes devices on the title's adapter on purpose (four on the RX 7900 XT) and the only test that the title's device survives it was on the software adapter: card_tiles_over_a_committed_section (tiled.rs:1281) probed with no other device on the card. The census of tiles began with since = 0 (tiled.rs:1107, Census::default), the process's start, so its first line divided the mappings counted by the whole uptime (begun at 95 s, a line at 100 s: rates 20 times too low). And no test covered the census's hooks in inplace.rs (place_for's turn-down, title_memory_view, views_gone). What changes: LEONIDA_INPLACE_PROBE_TILES=1 asks for the tiles probe (off by default; documented in tiled.rs and under 'Speed and memory'). The card test makes a device as the host makes the title's (D3D12CreateDevice), probes beside it, and asserts that it reports no removal and that a copy and a fence on it complete; on the RX 7900 XT it does after the probe's four removals. The WARP test checks the copy too. Census::starting(now) begins the census at its first ask. Tests: card_tiles_over_a_committed_section (ignored; fails when the probe runs on the title's device), the_tiles_probe_runs_only_when_asked_for, the_first_lines_rates_are_over_the_census_own_time, and scattered_pages_of_a_committed_section_turned_down_are_counted_as_tiles (diagnostics: place_for over scattered single pages of a committed section is counted as tiles could hold, a views_gone under it as unmapped and a title_memory_view as mapped; fails with any of those hooks removed or the flags swapped).
…-block-loads D3D12-SHADER-OPT-CROSS-BLOCK-LOADS: propagate LOADS across write-free dominating blocks
…ase-no-ticket D3D12-SHADER-1D-WAVE-BASE-NO-TICKET: skip entry ticket barrier and LDS atomic for 1-D groups
d3d12: guard biased raw twins against sub-dword offsets and 32-bit wrap (D3D12-TWIN-BIAS-RDNA3)
… the title None of the in-place paths faulted and none moved the frame. Title GPU memory is scattered 64 KiB pages of the page pool, which no placed buffer can show and no tiled buffer may map on Windows. Landing in the submission stays off after LEONIDA_AB weighed it. Private memory is flat; card memory counts in it, so only removing duplicates saves commit. A finer window grid saves 1.3 GB but stays off until overlapping windows are safe for shader writes. The up-copy check shows shader writes through undeclared views in about nine title buffers.
|
New round in this PR: One run per configuration in the world, on an RX 7900 XT under Windows with ReBAR off. Each run is 270 s, with the save restored before each start.
No configuration faulted. None moved the frame beyond what two starts of the same build differ by. Why reading in place covers so little. The title's GPU memory outside buffers is its physical page pool.
So there is no tiled window over title memory on Windows. VKD3D-Proton has not been asked yet. Landing in the submission is now decided once per plan, so
The relay lands in 6.8 ms a frame instead of 10.2 and waits for no fetch, but the frame does not wait for the relay. It stays off. Where the process's 27.4 GB of private memory goes. It is flat from about two minutes in the world, so there is no growth to chase.
A finer window grid (
What that check did find, at either grid. About nine title buffers of 1.1 to 2.5 MiB have a card copy that differs from its CPU side at rest. They are the same addresses at every check, written by shaders through a view no flight declared. A later send of a title write there would put the older bytes back over the shaders' bytes. Also in this round: a fix for an intermittent test. Tests: |
# Conflicts: # d3d12/crates/leonida-gpu/src/draw.rs # d3d12/crates/leonida-gpu/src/host.rs # d3d12/crates/leonida-gpu/src/pipeline.rs # d3d12/crates/leonida-gpu/src/resource.rs # d3d12/crates/leonida-gpu/src/texture.rs # d3d12/crates/leonida-hle/src/modules/apu.rs # d3d12/crates/leonida-hle/src/modules/xmem.rs # d3d12/docs/findings.md # docs/d3d12_vulkan.md # runtime/CMakeLists.txt # runtime/README.md # runtime/shims/d3d12_com.cpp # runtime/shims/d3d12_com.h # runtime/shims/d3d12_geometry_views.h # runtime/shims/d3d12_vulkan_device.cpp # runtime/shims/xmem.cpp # runtime/src/command_list.h # runtime/src/console_heap_slot_records.h # runtime/src/pipeline_cache_store.h # runtime/src/title_texture_refresh.h # runtime/src/vulkan_backend.h # runtime/test/console_heap_slot_records_test.cpp # runtime/test/d3d12_existing_heap_test.cpp # runtime/test/geometry_views_test.cpp # runtime/test/pipeline_cache_store_test.cpp
…s where the stamp is set The doc of evict_placed still said a texture's stamp is set under the table's lock held there, so that no thread can find it between the look and its leaving the table. Since the tables in front (placed_shards) that is not true: texture_at stamps under the shared lock of the shard only. The doc now says the stamp is set under the lock of the table or under the shared lock of the table in front, and that a texture that would go is first taken out of the table in front under its write lock and its stamp looked at again, so no thread still holds it once it has left. The recheck had no test: the one that releases a texture from the tables in front calls evict_placed with no idle time, which every stamp passes, so the recheck could be deleted with every test green. A test-only hook, run on the calling thread between the removal from the table in front and the second look, now stamps one of two idle textures there; the test asserts that one stays (still in the table, the same resource handed out again) and the other is released. With the recheck replaced by `goes = true` the test fails.
…n and bind
The up-copy check (LEONIDA_UPCOPY_CHECK=1) says where a copy's card side
holds what its CPU side does not, at a send or at rest, but not what put
it there: in the world scene it names the same ranges at every check, and
the labels it gives ("no shader was declared to write the buffer",
"declared; ...") are the union of all declarations ever made for the copy,
not what the submission that wrote the bytes declared. The causes weighed
since (shader writes kept on the card and undone by sends, a title rewrite
a shader then changes in place, a copy at its place, a write nobody
declared, the CPU side moving under an unchanged card) cannot be told
apart from those lines.
With LEONIDA_UNDECLARED_TRACE=1 (diagnostics builds, read through
crate::asked!, with LEONIDA_UPCOPY_CHECK=1; off by default), a copy either
look of the check flags in two frames is watched (256 KiB from the piece
flagged, 16 copies at most). Every submission from then on gets a pass of
ours ahead of its lists (behind its sends, in a call of its own) and one
behind them (first in its compare's call), comparing the watched bytes on
the card with a snapshot the card keeps and taking it anew; so the
submission that changed them, and whether its lists or its sends did, is
known exactly, with the span and one word before and after. While lists
are recorded and something is watched, each keeps what it told of watched
copies: every Shadow::gpu_writes over them with its bind, the line that
called it and what became of it (declared, kept on the card by
LEONIDA_WC_NO_BACK, elided, less GPU read-only parts), and every bind of a
program that stores past what its bind declared, with the reason
crate::draw already gives for indirect batches. A change by the lists is
logged with those writers, views picked from the heap for the copy, CPU
copies, bottom-of-pipe writes and read-backs into the bytes, and whether
what changed lies in a declared write at all; a change by the sends says
whether it undoes words an earlier submission's lists changed; a copy
flagged again while its watched bytes never moved on the card is said
once. At most two passes over 4 MiB a submission, 24 lines a copy, then
sums. Builds without diagnostics are unchanged, and with it nothing is
recorded until a copy is watched.
The code is host/undeclared.rs, with one-line hooks in Host::submit, the
two looks of host/upcheck.rs, Shadow::gpu_writes and State::bind. Tests on
the card: a dispatch storing through a view its bind did not declare is
traced to its submission and bind (not to a declaration outside the
window; a declaration inside it is named by its line), and the next
submission's send undoing it is traced too; the look at rest and the look
at a send each have a copy watched after two frames; a declaration over
GPU read-only memory is noted with what became of it; off, nothing is
watched, noted or looked at. Each fails with the hook it covers taken
out; the call in State::bind (it needs a translated pipeline) and the
notes of declarations kept on the card or elided (switches read once a
process) have no test of their own. The README's diagnostics list has the
switch.
…end undoes The trace LEONIDA_UNDECLARED_TRACE=1 gives (with LEONIDA_UPCOPY_CHECK=1, diagnostics builds, off by default) could give a false verdict in the world scene, which is where it is meant to separate the causes findings.md weighs: - the notes of binds whose programs store past their views shared one list of 1024 notes per list with the declarations into watched copies, one note per bind: thousands of binds a frame pushed the declaration that tells "kept on the card (LEONIDA_WC_NO_BACK)" out of the eight a line names, or out of the notes altogether, and the line then said "what changed lies in no write it declared", the very sign of a write nobody declared; the text was built for all 16 watches at every submission; - "over words the lists of submission M changed" was a test of overlapping spans: a shader writing words all over the window made any send in it look like one undoing the shader; - with the switch turned off and on (LEONIDA_AB), the first look compared with a snapshot from before the gap, and laid everything the lists did meanwhile on that one submission's sends; - title copies done on the CPU, bottom-of-pipe writes and read-backs were said with changes by the lists, which none of them can make. Now a list keeps the declarations into watched copies apart (1024, and how many more were not kept, which the verdict then says) and counts the binds that store past their views per program and reason. A line names the declarations in the window first, then the programs with their counts, deduplicated by a map, and what the lists told is gathered in one walk for the copies with lines left only. Beside the snapshot the card keeps, per watched word, the submission whose lists last changed it: the look behind the lists sets it, the look ahead of them counts the changed words that carry one and clears them, so a change by the sends says "N of the W words were last changed by the lists of submission M" with one such word, or "none of them". A submission that was not looked at (its number is not the one after the last asked) has the snapshots taken anew. Title copies into the bytes are said with the change ahead of the lists (they go up with the submission's own sends), and the last submission whose lists wrote values there at the bottom of the pipe or read texels back is named there too. Step::Fill only reads title memory into the list's upload memory and is not a candidate. The module doc and the README bullet say what does and does not tell a title rewriting records in place from shader writes undone by sends: refreshes and changes in turns come with both. Tests on the card: more than 1024 binds of ten programs storing past their views ahead of a declaration in the window, and the line names the declaration first and says what changed lies in it; a send between two stores of the lists is said over none of their words; a submission run with the trace off lays its change on no other; title copies are told with the sends, not the lists. The first two fail on the trace as it was, the last two with the gap check or the copies' place reverted. The test switch is now one for every thread (the tests that set it take the card's turn), so that submissions of other tests are looked at as well.
…shader writes in write-combined copies is written down LEONIDA_UNDECLARED_WATCH names title addresses whose copies are watched from the first look at rest, flagged or not, so that a run with LEONIDA_WC_NO_BACK=0 (where the check finds nothing there) still tells what changes those bytes. findings.md: the up-copy check's sends-over-card lines come from its look at a send and are nonzero in the world; with the launcher's LEONIDA_WC_NO_BACK=1 the sends reset two buffers that a compute pass keeps from frame to frame, while the rings flagged next to them are the title's own rewrites.
Round 11: up to date with main, and what undoes shader writes in write-combined copiesThe merge with main.
A correction to round 10. It said the up-copy check found no send putting an older value over a card write. That was wrong:
What wrote them (
Details are in |
|
@adrianmjim, a question before anyone claims it: this pull request is closed, and the compares behind the submissions it worked on (its |


Claimed in the coordination issue as: RT-UPLOAD-ARENA-REWIND, RT-PSO-BYTECODE-INTERN, RT-SPARE-LIST-EPOCHS, RT-SLOT-RECORDS-BUCKETS, RT-REHYDRATE-SCRATCH-TICKET, RT-FSSM-ARENA-SHARE, RT-TITLE-BUFFER-FALLBACK, RT-SLOT70-DEVICE-CYCLE, RT-MEM-PROBE-WINDOWS, RT-ZERO-IMAGES-RETRY, RT-TITLE-TEXTURE-GONE-RANGES, RT-SHADOW-GPU-RELEASED-RANGES, RT-SLOT70-OWNED-RETIRE (#1608 (comment)); RS-HOST-LIST-ALLOCATOR-PEAK, RS-XTASKQUEUE-POOL-TRIM, RS-TEXTURE-READ-TRIM, RS-SNAPSHOT-POOL-TRIM, RS-EXACT-SPARE-CAP, RS-GRAPHICS-STATE-INTERN, RS-EARLY-START-AGE, RS-XMEM-FREE-DEFAULT, RS-THIN-UPLOAD-DROP, RS-APU-SCRATCH, RS-REPLACED-DRAIN (#1608 (comment)); RT-GEOMETRY-VIEWS-CONTAIN, RT-DRAW-VIEWS-UNCHANGED (#2570 (comment)); RS-ARENA-ONE-COPY, RS-SHADER-CONTAINER-FREE, RS-DSTORAGE-SCRATCH, RT-DEVICE-LOST-DRAIN (#2570 (comment)); RT-SESSION-CACHE-UNCHANGED (#2570 (comment)); RT-SHARED-PIPELINE-LAYOUTS (#2570 (comment)); RS-HOST-LIST-SCRATCH-TRIM, RS-PIPELINE-LIBRARY-FINGERPRINT, RT-ZERO-IMAGES-RELEASE, RT-DSTORAGE-CPP-SCRATCH (#2570 (comment))
Depends on: none. It conflicts with #1521 (both add a release at the same spot in
~Device; keep both), #2267 (runtime/CMakeLists.txt,runtime/test/d3d12_existing_heap_test.cpp) #2085 (runtime/shims/d3d12_geometry_views.h,runtime/test/geometry_views_test.cpp), #2480 (runtime/src/command_list.h) and #1756 (save_session_pipeline_cacheinruntime/shims/d3d12_vulkan_device.cppand the end ofruntime/test/pipeline_cache_store_test.cpp: whichever lands second passesstate->cache_originin the checkpoint and callsrecord_session_seedonly when the save succeeded; a bool does not convert toCacheOrigin, so a wrong merge does not compile).What and why
Thirty-six fixes for memory that the two runtimes never give back, or keep longer than they need. Twenty are in the C++ runtime (
runtime/: the D3D12 → Vulkan layer and the console D3D12 proxy), the thirteen below and seven more further down. Sixteen are in the Rust runtime (d3d12/). They were claimed one by one (links above) and were meant to be separate pull requests. GitHub only lets this account have one open pull request in this repository, so they come together here.The fixes stay apart in the history, which makes them easy to review or revert one at a time. Each one is its own commit (or a few), merged into this branch with its own merge commit, and comes with its own test that fails on
mainand passes here. Each one also still exists on its own branch,adrianmjim/leonida:leaks/<name>, so any of them can become a separate pull request on request, or be dropped from this one.RT-UPLOAD-ARENA-REWINDRT-PSO-BYTECODE-INTERNRT-SPARE-LIST-EPOCHSRT-SLOT-RECORDS-BUCKETSRT-REHYDRATE-SCRATCH-TICKETRT-FSSM-ARENA-SHARERT-TITLE-BUFFER-FALLBACKRT-SLOT70-DEVICE-CYCLERT-MEM-PROBE-WINDOWSRT-ZERO-IMAGES-RETRYRT-TITLE-TEXTURE-GONE-RANGESRT-SHADOW-GPU-RELEASED-RANGESRT-SLOT70-OWNED-RETIRERT-SLOT70-OWNED-RETIREis off by default (LEONIDA_TITLE_IMAGE_RETIRE=1turns it on): a second review found cases where retiring an image too early could show wrong pixels.LEONIDA_UPLOAD_REWIND=0turnsRT-UPLOAD-ARENA-REWINDoff. The other fixes have no switch.A short description of each fix follows, to keep this text under GitHub's size limit. The full description, and what the fix's test checks, are in the commit messages on its branch,
https://github.com/adrianmjim/leonida/commits/leaks/<name>:1. RT-UPLOAD-ARENA-REWIND: d3d12: upload memory comes back at its command allocator's Reset
Console list slot 148 (
AllocateUploadMemory) carved memory from an arena of persistently mapped UPLOAD buffers inruntime/shims/d3d12_xs_device.cppthat only ever advanced; onlydestroy_upload_stategave it back, when the device proxy went, so a title that uploads every frame grew it by one buffer each time the newest was full. Chunks now belong to an allocator: the allocator proxy's Reset (slot 8) rewinds them, a chunk idle for 8 of its allocator's Resets is given back, and the proxy's last release frees them.LEONIDA_UPLOAD_REWIND=0keeps the one shared arena that only grows, as before;LEONIDA_UPLOAD_LOG=1names each chunk given back.2. RT-PSO-BYTECODE-INTERN: d3d12_xs: PSO streams with equal shader bytecode share one copy
PsoStreamRecord::capture(runtime/shims/d3d12_xs_pso_stream.cpp,copy_pointed_data) copied every shader stage's bytecode into the record's own blobs in both compile modes (includingLEONIDA_PIPELINE_COMPILE=on-demand), so each slot 86 PSO kept a private copy of every container it was made from.copy_pointed_datanow takes the bytecode from a process-wide table keyed by size and DXBC checksum, takes a candidate only when all its bytes are equal, and holds weak references only, so a container is freed with the last PSO that uses it. No switch is added, because what each PSO's stream holds and reads does not change.3. RT-SPARE-LIST-EPOCHS: d3d12: an idle list-cut spare drops its recording and holds back no retired title window
A retired title window waits for every command list whose recording began before its retirement, and the list proxy's spare real lists (
restart_recordinginruntime/shims/d3d12_xs_device.cpp) kept their last recording's stamp until the proxy was released, holding back every window retired after it.restart_recordingnow drops each new spare's recording throughrt::d3d12::drop_recording, so a dropped list carries no stamp until its next Reset, and a window still without a ticket after 30 s is logged once. There is no switch; withoutLEONIDA_VULKAN_DEVICEthe spares are kept as before, and a closed list the title neither resets nor releases still holds back later windows.4. RT-SLOT-RECORDS-BUCKETS: d3d12: a slot-record bucket goes with the last half it holds
The two indexes in
runtime/src/console_heap_slot_records.hnever erased a bucket, so for the main resource heap, which lives as long as the session, the bucket count grew with every (span class, granule) ever written, not with the live slots, and never went down. Each bucket now counts the halves it holds (Bucket::live), andset()lets the last half to leave a bucket erase it with its stale entries, so the buckets held are at most twice the halves recorded. There is noLEONIDA_*=0switch: nothing a lookup returns changes, only memory that nothing reads anymore is freed.5. RT-REHYDRATE-SCRATCH-TICKET: d3d12: a shim's scratch stays alive until the submission that used it has completed
When the title passes
ScratchAccelerationStructureData = 0,rehydrate_scratch(shims/xbox_bvh_builder.cpp) hands its DEFAULT scratch buffer to the list withrt::d3d12::hold_until_reset; in the default synchronous submit mode (LEONIDA_SUBMIT_ASYNCunset) the list released it at itsResetwhile the build could still run, and~Resourcereturned its arena range at once. A list now records those objects (kept_) andExecuteCommandListspasses them toVulkanQueue::executeas akeepcallback, so the scratch lives until the first queue call after its submission has completed. There is no switch to bring back the old behaviour, since that behaviour was a use-after-free.6. RT-FSSM-ARENA-SHARE: d3d12: the PSOs of one program share its code-base copy in the arena
A PSO whose shader reads its code base copies that program into the fixed-size GPU address arena (
create_computeandcreate_graphicsinruntime/shims/d3d12_vulkan_device.cpp), and every PSO made its own copy, so N PSOs of one program held N copies of the same bytes until they were released. The device now keeps one copy per program (DeviceState::code_copies), keyed by the program's SHA-256; later PSOs take a reference and the last one returns the copy from~PipelineState.LEONIDA_SHARE_CODE_BASE=0gives every PSO a copy of its own, as before, and a compute index entry without auses_code_basekey is still copied. Not in this pull request: 2,426 of the 2,689 compute shaders in the main index have nouses_code_basekey yet, so they are still copied; that is a translator change.7. RT-TITLE-BUFFER-FALLBACK: d3d12: a title vertex or index view makes and keeps only a buffer that covers it
When
make_title_buffer(runtime/shims/d3d12_vulkan_device.cpp) could neither import nor shadow the title's pages,create_at_host_addressstill returned an ordinary DEFAULT buffer that resolved nothing; it was kept intitle_buffers_until the device went and counted againstLEONIDA_TITLE_BUFFERS_MB, and each rebind made another until the cap was used up. Nowmake_title_buffergetsE_OUTOFMEMORYinstead (ordinary_fallbackisfalse), keeps a buffer only when the context knows a buffer at the view's address (1 byte withLEONIDA_TITLE_BUFFER_COVERAGE=0), and after a refusal tries no range for a second, a refused range waiting twice as long each time, up to 64 s. No switch.8. RT-SLOT70-DEVICE-CYCLE: d3d12: an image made for slot-70 views holds no device reference, so a released device goes
The images
make_title_texturemakes for slot-70 views held a device reference (attach_device) while the device's registry (state_.title_textures) andretired_title_textures_held the images, and~Devicereleased neither, so a released device and its Vulkan objects were never destroyed. Each image now drops its device reference right after it is made, and~Devicereleases the registry's images and the retired ones aftervkDeviceWaitIdle(release_title_images). This is teardown only: during a session the refresh pass releases retired images, and a title never releases its device.9. RT-MEM-PROBE-WINDOWS: mem probe: on native Windows a vmmap line shows the process's memory by kind
LEONIDA_MEM_PROBE=<seconds>(runtime/src/mem_probe.h) reads/proc/<pid>/smapsfor its process-memory line, so on native Windows it only printedno /proc entry names gta6rtand could not say where 20+ GB of commit go. Whenproc_dir()finds no/procentry,sample()now prints avmmapline: private commit and working set fromGetProcessMemoryInfo, committed bytes by kind (title, pe-private, pe-image, pe-section, vk-mapped) from aVirtualQuerywalk, and the largest private allocations. It is a diagnostic only, with noLEONIDA_*=0switch: withLEONIDA_MEM_PROBEunset nothing runs, and under Wine with a/procentry the smaps line is unchanged.10. RT-ZERO-IMAGES-RETRY: d3d12: a shape whose shared zero image could not be made is tried again, after a wait that doubles at each failure
When the shared zeroed image for a sampled BC texture's shape (
DeviceState::zero_sampled_image) could not be made, for example under VRAM pressure, the shape was stored as nullptr inzero_images, so every later slot 133 placement of that shape took memory of its own for the rest of the session. The failure is now remembered inzero_image_retryand tried again after 1 s, doubling at each failure up to 64 s, and a shape that gets its image leaves the map. Only a shape whose image would pass the 256 MiB limit stays null for good; there is no switch.11. RT-TITLE-TEXTURE-GONE-RANGES: d3d12: a title texture destroyed inside the registry leaves the async refresh's indexes too
With
LEONIDA_TEXTURE_REFRESH_ASYNC=1,drain_titles_goneerased a destroyed slot-133 texture's registry entry but left its key intexture_rangesandmapped_title_textures, so the mapped list kept theTitleTexturealive and the next refresh pass'stitle_textures.at()threwstd::out_of_range, ending the process (0xC0000409).drain_titles_gonenow erases the range key with the registry entry and also erases a mapped entry that has no resource. The async pass's apply lambda usesfind()and skips keys with no entry.12. RT-SHADOW-GPU-RELEASED-RANGES: d3d12: LEONIDA_SHADOW_GPU=1 alone keeps no released ranges for the console heap pass
With
LEONIDA_SHADOW_GPU=1andLEONIDA_CONSOLE_HEAP_GPUunset, every arena release, destroyed title-window or geometry block, released slot-133 import and removed alias range added entries that only the console heap pass takes, so they piled up for as long as the process ran. Inruntime/shims/d3d12_vulkan_device.cppthe pushes inbacking()andtitle_block_gonenow askheap_pass_enabled(), the alias table records removals only when the pass runs,arena_releaseno longer callsbacking(..., false)twice, and~Devicereleasesheap_gpubefore the VkDevice goes. WithLEONIDA_CONSOLE_HEAP_GPU=1nothing changes apart from the duplicate range being gone.13. RT-SLOT70-OWNED-RETIRE: d3d12: a slot-70 image a newer texture covers, or whose pages went, is retired once no view names it
Owned slot-70 images from
make_title_texturewere released (retire_title_texture) only when the same address got a slot-133 registration or another description, so a streaming title kept the image and bindless index of every address it ever named for the device's life.retire_idle_owned_imagesnow retires an image superseded by a newer overlapping texture and not named since, or whose pages are gone, afterLEONIDA_TITLE_IMAGE_IDLE_MS(2000 ms by default), with up toLEONIDA_TITLE_IMAGE_CHECKS(128) candidates a pass. Retirement is off by default (LEONIDA_TITLE_IMAGE_RETIRE=1turns it on), because a descriptor the title wrote once would then sample the fallback. No in-game numbers back the claim that this fixes the bindless filling seen during the story load.Two more runtime fixes (
runtime/)From a third pass over the same runtime, claimed in #2570, which continues #1608 (#2570 (comment)). Same rules as above: each is its own merge with
its own test that fails on
mainand passes here, and it still exists on its own branch.RT-GEOMETRY-VIEWS-CONTAINRT-DRAW-VIEWS-UNCHANGEDRT-GEOMETRY-VIEWS-CONTAINonly acts withLEONIDA_GEOMETRY_MBset (off by default) and has its own switch,LEONIDA_GEOMETRY_CONTAINED=0. It retires nothing for disuse or on a remap (the reason #2350 was reverted by #2370).25. RT-GEOMETRY-VIEWS-CONTAIN: d3d12: a geometry range inside a live view is answered from that view, not copied again
GeometryViews::resolve(runtime/shims/d3d12_geometry_views.h) looked up only its exact (source, bytes) key, so withLEONIDA_GEOMETRY_MBset a range inside a live geometry copy got a copy of its own, all charged to the cap. An index of the outermost live views by source now answers a range inside a filled live view with that view's address plus its offset, and the range is retired with its view; this also fixes a lost update where a filled view over a tile with a file read in flight skipped its other written tiles for good. Nothing is retired for disuse, andLEONIDA_GEOMETRY_CONTAINED=0restores the old behaviour.26. RT-DRAW-VIEWS-UNCHANGED: d3d12: draws that bind the same views again share one views block
GraphicsCommandList(runtime/shims/d3d12_com.cpp) marked itsDrawViewsblock stale inset_vertex_buffersandOMSetRenderTargetswithout comparing with what is already bound, so a title that rebinds the same vertex buffer before each draw got onemake_shared<DrawViews>per draw (about 728 bytes), kept by the recorded draws until the list's Reset. Nowset_vertex_buffersmarks it stale only for a slot whose view changes, andOMSetRenderTargetsonly when the target count or a copied target view differs. What each draw records is unchanged.Tested at
9fc3ad427(all 26 fixes, withmain33db04a70merged):-j 3: 521 of 524 pass; the three that fail are the same as on plainmainhere (d3d12_texture_tiles,pipeline_cache_seed,d3d12_clear).d3d12_compile_poolfailed once in an earlier full run and about 1 time in 3 alone; this branch does not touch the compile pool or its test.LEONIDA_VK_VALIDATION=1:xs_proxy_mock,geometry_views,d3d12_geometry_views,d3d12_title_va,d3d12_title_va_shadow,d3d12_draw,d3d12_draw_views_sharingandd3d12_existing_heappass 8/8, no validation errors.The Rust runtime (
d3d12/)Eleven more fixes from the same sweep, in the Rust runtime this time, claimed in #1608 as well
(#1608 (comment)). They were meant to follow the runtime ones
one pull request at a time and come here for the same reason. A twelfth,
RS-XASYNC-CANCEL-UAF, was withdrawn: zmasi'searlier D3D12-HLE-XASYNC-CALLBACK-AND-CANCEL-LIFETIME covers it. As above, each fix is its own merge with its own test that
fails on
mainand passes here, and still exists on its own branch,adrianmjim/leonida:leaks/rs-<name>.RS-HOST-LIST-ALLOCATOR-PEAKRS-XTASKQUEUE-POOL-TRIMRS-TEXTURE-READ-TRIMRS-SNAPSHOT-POOL-TRIMRS-EXACT-SPARE-CAPRS-GRAPHICS-STATE-INTERNRS-EARLY-START-AGERS-XMEM-FREE-DEFAULTRS-THIN-UPLOAD-DROPRS-APU-SCRATCHRS-REPLACED-DRAINNone of them changes what the title sees.
RS-EARLY-START-AGEkeeps the last 2 runs (LEONIDA_EARLY_RUNS, 0 = every runas before) and
RS-TEXTURE-READ-TRIMkeeps 16 MiB a thread (LEONIDA_TEXTURE_READ_KEEP_MB).14. RS-HOST-LIST-ALLOCATOR-PEAK: leonida-gpu: submitted lists hold no host list until reset, idle ones are trimmed
leonida-gpu host command lists keep their command allocators at peak size, every submitted title list (with
LEONIDA_THIN=1, every back list) got a new host list at once that sat unused until the title's next reset, and the idle pool (IDLE,list.rs) kept up to 512 lists that nothing trimmed. A submission now takes the host list and leaves the title list none, and reset takes one from the pool. Once a second the sweep lets go of the oldest half of the idle lists nobody took since the last sweep, through retire, so they are freed on the reaper thread.15. RS-XTASKQUEUE-POOL-TRIM: leonida-hle: the XTaskQueue thread pool starts few workers in a burst and trims idle ones
the XTaskQueue thread pool (d3d12/crates/leonida-hle/src/modules/xasync.rs, Pool), which also runs every XAsync completion on the process queue, starts about one thread per callback in a burst of short callbacks and never lets a worker go. So it keeps its peak thread count, each thread with its stack and the title's per-thread state. Fix: start a worker only when none is idle or coming, chain the next start while tasks wait, hand each task to the worker that went idle last, and let workers idle for 30 s leave down to 4. Test: 256 short callbacks start at most 32 workers, and 16 workers left idle drop to the one kept while a callback still comes every 10 ms. The tests do not compile on main (no constructor or worker count); with a test-only shim that adds both, they fail there (55 to 255 workers in the burst; 16 or 17 that never leave). No game files.
Test:
pool_workers_stay_few_in_a_burst_of_short_callbacks,pool_workers_left_idle_leave_under_a_trickle_of_callbacks.16. RS-TEXTURE-READ-TRIM: leonida-gpu: a texture refresh thread keeps at most 16 MiB of read buffer between textures
In leonida-gpu, each thread's texture read buffer (
texture.rsREAD,with_read) only grows, so the submitting thread and eachshadow::wide_eachhelper keep room for the largest texture they ever read for the whole run. A thread now keeps at mostLEONIDA_TEXTURE_READ_KEEP_MB(16 unless set) of its own; larger reads take a buffer from a process-wide pool and give it back, and the once-a-second sweep (texture::let_go_idle) hands buffers idle forhost::ram_idle_msto the reaper thread. Nothing the title sees changes.17. RS-SNAPSHOT-POOL-TRIM: leonida-gpu: snapshot buffers no snapshot took for the idle time leave the pool
leonida-gpu's snapshot pool (shadow.rs POOL/give_back) keeps up to 512 MiB, or its largest buffer, of committed PC memory for the rest of the run, with no trim. Fix: stamp each pooled buffer when it is given back, take out those idle for host::ram_idle_ms in shadow::let_go_idle, and hand them to host::retire so the reaper thread frees them. Test: shadow::snapshot_pool_tests::buffers_the_pool_kept_for_the_idle_time_go (fails with d442851's behaviour, passes with the fix). No game files.
Test:
shadow::snapshot_pool_tests::buffers_the_pool_kept_for_the_idle_time_go.18. RS-EXACT-SPARE-CAP: leonida-gpu: spare buffers of view copies are capped at 64 MiB and go when idle
leonida-gpu's EXACT_SPARE (shadow.rs exact()) keeps up to 1,024 spare view-copy buffers (each 64 KiB to 64 MiB of committed PC memory) forever, reused only on an exact width match. Fix: also cap the spares at 64 MiB (counted in 64 KiB blocks, evicting the oldest), release what leaves outside the lock, and retire those parked for host::ram_idle_ms from shadow::let_go_idle. Test: shadow::exact_spare_tests::spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle (fails with d442851's rule, passes with the fix). No game files.
Test:
shadow::exact_spare_tests::spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle.19. RS-GRAPHICS-STATE-INTERN: leonida-gpu: title pipelines of one graphics state share it
every title pipeline created from a stream keeps its own heap copy of the full graphics state for the session (make.rs Pending.graphics: Box, pipeline.rs create_stream), ~84,000 copies of ~5,700 distinct states. Fix: Pending holds Arc, interned by a hash of describe() in a weak table, so equal states share one copy and are freed with their last pipeline. Test: two pipelines from the same synthetic stream must share one state and one with another topology must not; fails on main (two boxes), passes with the fix. No game files.
Test:
pipelines_of_one_graphics_state_share_it.20. RS-EARLY-START-AGE: leonida-gpu: the early pipeline list keeps the last two runs
early-pipelines.txt(d3d12/crates/leonida-gpu/src/pipeline/library.rs) holds every run ever and, sinceEARLY_MAXis above the title's pipeline count, is never trimmed, so every pipeline drawn with in any earlier run is started at creation at every load and its host PSO stays alive for the session. Each line now holdskey run, and a save keeps only the keys requested in the last 2 runs (LEONIDA_EARLY_RUNS, 0 = every run as before). A process that requests nothing writes the list back unchanged, and old lists without runs still load.21. RS-XMEM-FREE-DEFAULT: leonida-hle: XMemFreeDefault tells the GPU side of freed 32-bit memory
XMemFreeDefault's 32-bit path (d3d12/crates/leonida-hle/src/modules/xmem.rs) frees with the host VirtualFree directly. XMemAllocDefault's 32-bit path told the GPU side about that memory through XMemVirtualAlloc, but leonida_gpu::title_memory_freed never runs for the free, so the guarded, absent and foreign blocks, views and write-combined regions noted for the range survive and can be taken for true of the next memory at that address. The fix frees through title_virtual_free(address, 0, MEM_RELEASE), the title's own VirtualFree, which tells the GPU side first. A new unit test fails on main (the free never reaches the GPU side) and passes with the fix. No game files.
Test:
free_default_tells_the_gpu_side_of_32bit_memory.22. RS-THIN-UPLOAD-DROP: leonida-gpu: thin lists give back uploads a reset or release leaves behind
with LEONIDA_THIN=1, a title list reset or released while it records clears its words that were not handed over yet in Front::leave (d3d12/crates/leonida-gpu/src/list/thin.rs) without dropping the Box they name, so their 64 KiB upload arena blocks stay taken for good. The fix drops those uploads in leave(). The CPU unit test fails on main (the upload is never given back) and passes with the fix. No game files.
Test:
uploads_of_words_never_handed_over_are_given_back.23. RS-APU-SCRATCH: leonida-hle: XApu decodes each packet into memory the connection keeps
XApu's process() (d3d12/crates/leonida-hle/src/modules/apu.rs) allocates and zeroes a 46 KB Vec for every Opus packet, about 50 a second per playing stream, under the connection lock. The fix keeps one buffer in the connection's State. A unit test with a test-only counting allocator fails on main (10 large allocations for 10 packets) and passes with the fix (0). Processor time, not footprint. No game files.
Test:
packets_decode_without_memory_of_their_own.24. RS-REPLACED-DRAIN: leonida-gpu: replaced host copies go with LEONIDA_TEXTURE_SWEEP=0 too
with LEONIDA_TEXTURE_SWEEP=0, let_go_idle (d3d12/crates/leonida-gpu/src/resource.rs) returns before it drains REPLACED, so every host copy want_level replaces by one with more levels stays on the card for good although nothing can use it. The fix moves the drain above the switch; idle copies are still kept with the sweep off. The test runs a child process with the sweep off and checks that a replaced copy goes after four frames and a second: it fails on main and passes with the fix. No game files.
Test:
replaced_copies_go_with_the_sweep_off.Tested (
leaks/allwith the eleven merged; one conflict inshadow.rs, where two fixes add their call to the samesweep, both kept; each fix's test is named in its details above):
cargo test --locked --offline -p leonida-hle --lib: 186 passed, 0 failed.cargo test --locked --offline -p leonida-gpu --lib -- --test-threads=4: 493 passed, 4 failed, 46 ignored. The four(
views_off_their_elements_get_a_copy_of_their_bytes,batch_tables,host_list_budget_starts_empty_at_each_submission,warp_batch_charges_every_execution) fail the same way on plainmainon this machine (RX 7900 XT, AMD 32.0.32029.2010).maind44285197without the fix and failed there (the commit messages say how).9fc3ad427(see the section above).9fc3ad427: the same results (leonida-gpu --lib493 passed with the same 4 failures;leonida-hle186 passed). Plainmain33db04a70:leonida-gpu --lib479 passed with the same 4 failures,leonida-hle181 passed.Four more fixes
From a fourth pass, three in the Rust runtime and one in the C++ runtime, claimed in #2570
(#2570 (comment)). Same rules as above: each is its own merge with
its own test that fails on
mainand passes here, and it still exists on its own branch,adrianmjim/leonida:leaks/<name>.None of them has a switch.
RS-ARENA-ONE-COPYRS-SHADER-CONTAINER-FREERS-DSTORAGE-SCRATCHRT-DEVICE-LOST-DRAIN27. RS-ARENA-ONE-COPY: leonida-gpu: an arena of memory by address is in the PC's memory once
memory.rsheld each 64 MiB arena twice in the PC's memory, as the arena itself (upload::reserve) and as the CPU side of its copy on the card (shadow::by_address) with the same bytes; withLEONIDA_BVH_BUILDER=1that is up to 48 arenas, about 3 GiB.Memory::another()now makes the copy withshadow::by_address_opened, which opens the arena as a host heap so the arena itself is the CPU side, andbring()/take()resend exactly the changed dword runs; if the host does not open the memory, the copy is made as before. There is no switch, and a dword changed and changed back within one send window now goes up over what the builder stored there.28. RS-SHADER-CONTAINER-FREE: leonida-gpu: a translated shader lets its container go
d3d12/crates/leonida-gpu/src/pipeline.rskept every distinct shader container in the staticSHADERStable (container: bytes.to_vec()) for the whole process, although after translation only small derived facts are read from it. Those facts are now kept inTranslatedand a newFacts, and after a successful translationShader::translatedlets the container go, except for a shader that stores whileLEONIDA_PICKED_WRITESis on, untilcrate::pickedhas read its programs. Shaders that never translate or fail to translate keep their container, and nothing the title can see changes, so there is no switch.29. RS-DSTORAGE-SCRATCH: leonida-hle: DirectStorage workers reuse their request buffers
d3d12/crates/leonida-hle/src/modules/dstorage.rsallocated new zero-filled buffers (read_source, the zlib output,into_pages) for every compressed request and freed them at its end, andstaging_bytescounted only the compressed source, so the other buffers were outsideLEONIDA_DSTORAGE_STAGING_MB. Each worker now keeps aScratchit reuses, holding at most 16 MiB (SCRATCH_KEPT) between requests, andstaging_bytescounts every buffer a request holds. What workers keep between requests is outside the staging limit, and the bytes written to destinations are the same as before.30. RT-DEVICE-LOST-DRAIN: vulkan: after a device loss, released objects are destroyed at once
After a device loss, nothing drained the Vulkan layer's deferred deletion queue (
runtime/src/vulkan_backend.h) until the context was destroyed, so every image, buffer,VkDeviceMemory, framebuffer and image-memory range the title released after the loss stayed allocated for the rest of the process. On a lost deviceVulkanContext::defer_destroynow destroys the object at once, and the first such call also destroys what was queued before (DeferredDeletionQueue::drain_lost); bindless slots and image views still wait until teardown. There is no switch, andcompleted_retire_ticket()deliberately still answers 0 after the loss, so the other ticket-gated frees still stop there.Tested at
eb145de6f(all 30 fixes, withmaind48a957bbmerged):leonida-hletests no longer built:RS-APU-SCRATCHandRS-DSTORAGE-SCRATCHeach installed a counting#[global_allocator]in their tests, and a binary has one. The merge fixeb145de6fmoves it toleonida-hle/src/test_alloc.rs, which tells both counters of each block. Test code only.mainwithout its fix, where it fails (the commit messages say how):memory::tests::an_arena_is_in_the_pcs_memory_once,pipeline::tests::translated_shaders_let_their_containers_go,modules::dstorage::tests::{compressed_requests_reuse_the_workers_buffers, staging_counts_every_buffer_a_request_holds}andvk_deferred_destroy_lost(ctest). All pass here, andvk_deferred_destroy_lostalso passes underLEONIDA_VK_VALIDATION=1.cargo test --workspace --no-fail-fastind3d12/:leonida-gpu496 passed with the same 4 failures asmain,leonida-hle189 passed. The other failures are the three described under "Latestmainmerge" below, in code that is the same as onmain.-j 8: 3 of 526 fail, the same three as onmain(d3d12_texture_tiles,pipeline_cache_seed,d3d12_clear).python -I scripts/check_no_game_data.pypasses on every file these four change. The game was not run with them.One more runtime fix
From a fifth pass, claimed in #2570 (#2570 (comment)). Same rules as above: its own merge, its own test that fails on
mainandpasses here, and its own branch,
adrianmjim/leonida:leaks/session-cache-unchanged.RT-SESSION-CACHE-UNCHANGED31. RT-SESSION-CACHE-UNCHANGED: d3d12: a session file written beside the offline seed is loaded alone
With the offline seed loaded,
pipeline_cache.session.binis the driver's union of the seed and what sessions added (on theRX 7900 XT a 1.88 GB seed and a 1.88–1.89 GB session file). Every launch still created a driver cache from the seed, then a
second one from the session file, and merged them. In the in-game sessions below, the mem probe's vmmap line shows private
commit going from 8.1 to 9.95 GB and back to 8.3 GB between 10 and 20 s. Now, whenever the session file is written beside this
device's seed, a small record
pipeline_cache.session.seed(written after it, through the same temp-file +MoveFileExhelper) notes the seed's size and last-write time and the session file's size. On the next launch, when the record matches the
current seed and session file and the session file's header fits the device, the cache is created from the session file alone:
pipeline_cache.binis only stat'ed and nothing is merged. Everything else takes today's path: no record, a changed seed, asession file of another size, a driver that declines the blob,
LEONIDA_SESSION_CACHE_DIRECT_SEED=0orLEONIDA_DIRECT_SESSION_CACHE=0. A write-back smaller than what the cache was created from drops the record, so the next launchmerges the seed again. Nothing is deleted except a stale record. The ~1.9 GB write at exit is unchanged on purpose. Documented
in
docs/d3d12_vulkan.md.Tested at
652f45345(all 31 fixes; merging this fix's branch also brings inmain9c49bd533, 63 commits afterd48a957bb, with no conflict):d3d12_session_cache_seed(d3d12_compile_teardown_test --seed, a real device and a seed that holds a real pipeline; its rounds cover the relaunch, a touched seed,LEONIDA_PIPELINE_CACHE_BYTES=0, the switch at 0, no seed, and a seed with a session file but no record) and new unit checks inpipeline_cache_store(the record's format and every truncation, a changed seed or session file, the shrink rule). Withmain's device code the relaunch fails:1 merge(s), caches created from [3652, 7252] bytes. With the fix:0 merge(s), caches created from [7252] bytes, 2 of 2 compute build(s) a cache hit.pipeline_cache_store,heavy_pipeline_cache,d3d12_compute_journal,d3d12_pipeline_checkpoint,d3d12_compile_teardown*, plusmem_probe_vmmap) underLEONIDA_VK_VALIDATION=1: 8/8.-j 8: of 527, the same three as onmainfail (d3d12_texture_tiles,pipeline_cache_seed,d3d12_clear), plus the presentation tests (vk_present*,dxgi_*,d3d12_present,xbox_present), because the monitor was off during the run; they pass with it on, as in the runs above.gta6rt_no_tls_callbacksfailed once because an incremental link left an oldgta6rt.map; after a full relink it passes.cargo test --workspace --no-fail-fastind3d12/and the 555 standalonetests/test_*.py: the same results as ateb145de6f(this fix touches neither).python -I scripts/check_no_game_data.pypasses on every changed file.gta6rtfrom this fix's branch (a580819a5, onmain9c49bd533), a fresh copy of the port with the 1.88 GB seed and a 1.88 GB session file, the same harness as the sessions below. The first launch took the old path (loaded 1883920688 bytes from pipeline_cache.bin, thenmerged 1884044916 bytes from pipeline_cache.session.bin) and its checkpoint wrote the record. The second took the new one (loaded 1884044916 bytes from pipeline_cache.session.bin, which holds the 1883920688-byte pipeline_cache.bin it was written beside; the seed was not loaded and nothing merged) and booted and ran normally. MEASURED with an outside sample every ~11 s over the first 120 s: peak working set minus working set reached 2,685–3,272 MiB in all 5 launches on the old path (both sessions below and three today), with a peak working set of 9,456–9,490 MiB; on the new path, 307 MiB and 8,398 MiB. Private commit at launch was not measured on this build (it has no vmmap line), and the 11 s samples of private bytes are too coarse to show a transient of a few seconds on either path.652f45345also answers a review: under Wine the process's commit charge does not count what it commits, somem_probe_vmmapchecks it on Windows only, like the private working set next to it.And one more
From a sixth pass, claimed in #2570 (#2570 (comment)), with its own merge, its own test that fails on
mainand passes here, and itsown branch,
adrianmjim/leonida:leaks/shared-pipeline-layouts.RT-SHARED-PIPELINE-LAYOUTS32. RT-SHARED-PIPELINE-LAYOUTS: d3d12: PSOs share one pipeline layout per shape, destroyed at device teardown
Every PSO made its own
VkPipelineLayout(PipelineState::create_graphics/create_compute) and destroyed it with the PSO,although the create info only differs by push-constant stages and whether set 0 is the bindless layout, so a session's ~50k PSOs
held ~50k identical layouts. MEASURED standalone on the RX 7900 XT (driver 26.11.2) with the runtime's bindless set layout:
~2.3 KB of process memory per layout with the bindless set (the driver copies the 29-binding set layout into each), ~0.2 KB
without; ASSUMED from that, ~117 MB for 54k PSOs (not measured in the game). Now
DeviceState::pipeline_layoutkeeps one layoutper distinct create info: the key is the whole create info (flags, every set layout handle in order, every push range), and a
pNextchain is refused rather than shared. Layouts are made on first use under a mutex, with the map slot reserved first. PSOsno longer destroy them;
~Devicedoes, once, after the compiler cancel,vkDeviceWaitIdle, the drained deferred deletions andthe stopped pipeline workers, and before the bindless set layout and the
VkDevice. The mem probe's device line addsPSO pipeline layouts N.Tested at
20ca6dcf5(all 32 fixes,main8b318bd40merged; this fix's based57b78a9cis already in it):d3d12_shared_pipeline_layoutsand_eager(LEONIDA_LAZY_PIPELINES=0,LEONIDA_LAZY_COMPUTE=0): 256 PSOs of 4 shapes (graphics and compute, each with and without set 0) made on 4 threads to race the first creation, a dispatch that pushes constants and binds sets with a shared layout, and a second device; they count creates and destroys through the hookedvkGetDeviceProcAddr. Withmain's device code they fail:256 PSOs of 4 shapes made 256 pipeline layout(s). Here: 4 made and 4 destroyed per device, 0 live, 0 bad destroys.pipeline_workers,d3d12_pipeline_workers*,d3d12_compute,d3d12_draw,d3d12_set0_compute,d3d12_mesh*,d3d12_compile_teardown*,vulkan_mesh_limits): 15/15. UnderLEONIDA_VK_VALIDATION=1, the new two,d3d12_pipeline_workers*andd3d12_compute: 8/8, noVUIDline.-j 8: of 529, the same three as onmainfail, andd3d12_mesh_heavy_cachefailed once: it andd3d12_meshrun the same program, which rewrites the same%TEMP%\leonida_mesh_test\index.json, and its log readscannot open ...\leonida_mesh_test\index.json(READ IN CODE:runtime/test/d3d12_mesh_test.cpp:128, unchanged here). It passes alone and withd3d12_meshbeside it, 13 of 13 runs.And one more in
d3d12/From a seventh pass, claimed in #2570 (#2570 (comment)), with its own merge, its own test that fails on
mainand passes here, and itsown branch,
adrianmjim/leonida:leaks/rs-host-list-scratch-trim.RS-HOST-LIST-SCRATCH-TRIM33. RS-HOST-LIST-SCRATCH-TRIM: leonida-gpu: an idle host list lets go of an indirect scratch buffer past 1 MiB
HostList::indirect_scratch(d3d12/crates/leonida-gpu/src/host.rs) only grows its device-local buffer of clamped indirectarguments, doubling it.
list::recyclereset a host list and put it in the idle pool with that buffer still attached, and the poolhands its lists to any title list, so one large
ExecuteIndirectkept its buffer in the card's memory for the rest of the run, inevery idle list that had served one (up to 512).
recyclenow callsHostList::idle_trimright after the reset: a scratch largerthan 1 MiB (
IDLE_INDIRECT_MOST) is taken out and handed toretire_resource, which drops it once the submissions still runninghave finished. Smaller ones stay, so ordinary frames keep reusing theirs, and title-list resets are unchanged. The frame-rate line
counts what idle lists let go. It works with the
Pooldescribed under the latestmainmerge.Tested at
ca5aed779(all 33 fixes,main8b318bd40; this fix's base is the samemain):list::tests::an_idle_list_lets_go_of_a_large_indirect_scratch: grows a list's scratch to 2 MiB, recycles the list, takes it back from the pool and checks that the next request gets a fresh 64 KiB buffer, then that a 1 MiB buffer survives the same trip. Onmainit fails (the large buffer was let go: left 2097152, right 65536); here it passes, withlist::tests10/10.cargo test --workspace --no-fail-fastind3d12/:leonida-gpu524 passed andleonida-hle214 passed; the failures are the same 4 inleonida-gpu, 2 inleonida-shaderand 1 inxtaskas onmain.runtime/is unchanged by this fix.python -I scripts/check_no_game_data.pypasses on both changed files. Not run in the game (the Rust runtime is notgta6rt).Three more
From the same seventh pass, claimed in #2570 (#2570 (comment)): one in
d3d12/, two inruntime/. Each has its own merge, its owntest that fails on
mainand passes here, and its own branch on the fork (leaks/rs-pipeline-library-fingerprint,leaks/zero-images-release,leaks/dstorage-cpp-scratch).RS-PIPELINE-LIBRARY-FINGERPRINTRT-ZERO-IMAGES-RELEASERT-DSTORAGE-CPP-SCRATCH34. RS-PIPELINE-LIBRARY-FINGERPRINT: leonida-gpu: the host pipeline library is kept for one set of translated shaders
d3d12/crates/leonida-gpu/src/pipeline/library.rsopenedhost-pipelines.binwhatever translation its pipelines came from and saved it back whole, so entries of older translator generations, which can never load again, stayed and the file only grew (the library's own line reads 1,490 MB in memory in run 65). The fingerprintleonida warmalready uses (known::fingerprint()) is now written beside it ashost-pipelines.fingerprint; a missing or different one gives an empty library, and that run's first save writes over the old generation. A save that is cut short leaves no fingerprint, never a stale library under the current one. OneSAVINGmutex now covers a whole save: overlapping saves sharedhost-pipelines.tmponmaintoo, and with the fingerprint that could leave a half-written library under a valid one.35. RT-ZERO-IMAGES-RELEASE: d3d12: a shared zero image no placed texture shows any more is released
Placed BC textures with no memory of their own yet show a shared all-zero image of their shape (
DeviceState::zero_sampled_image), on a CUSTOM WRITE_BACK / L0 heap (host memory on a discrete GPU) under a 256 MiB cap, and those images were only released at device teardown, so a session streaming many shapes filled the cap for good. The device now counts each image's users (acquire_zero_image); when the last one is destroyed or gets memory of its own, the image leaves the map and the cap, and itsResourceis released through the deferred-deletion queue. With several queues, a return carries the execute epoch and is released only once no replay in progress at it is left. Shapes left out for not fitting get another try (the commentRT-ZERO-IMAGES-RETRYleft inzero_sampled_imageis corrected in962bc1601).36. RT-DSTORAGE-CPP-SCRATCH: dstorage: queue workers reuse their staging buffers
Each compressed, swizzled or physical-page DirectStorage request in
runtime/shims/dstorage.cppallocated a new zero-filled buffer at every stage and freed it at the end, the C++ side ofRS-DSTORAGE-SCRATCH. Each queue worker now keeps two sets of buffers (its own request's and its paired helper's), grown only when a request needs more, keeps at most 16 MiB between requests (the budgetcan_preparealready used), and no longer zero-fills bytes that are always written before they are read or the request fails and publishes nothing.Tested at
962bc1601(all 36 fixes,main8b318bd40; the three branches' base is the samemain):mainand passing here:pipeline::library::tests::{a_library_saved_for_other_shaders_is_not_opened, overlapping_saves_leave_one_whole_library_and_its_lists}(main:no fingerprint written; the second fails 3 of 3 with the lock made a no-op), ctestd3d12_zero_image_release(12 shapes placed and released, with a second queue running during the copy's replay;main: 12 images and 47,104 bytes still held; here 0 and 0) and, indstorage,test_reused_buffers(100 requests of two streams, outputs compared byte for byte: 300 blocks of 128 KiB or more onmain, 6 here),test_kept_buffers_capandtest_kept_buffers_pair_cap.dstorage,d3d12_zero_image_retryandd3d12_zero_image_release: 3/3; the two zero-image tests underLEONIDA_VK_VALIDATION=1: 2/2, noVUIDline.-j 8: 3 of 530 fail, the same three as onmain.cargo test --workspace --no-fail-fast:leonida-gpu528 passed (pipeline::library15/15) andleonida-hle214, with the same failures as onmain.python -I scripts/check_no_game_data.pypasses on every changed file. Not run in the game.Tested
On Windows 11 Pro 26300, MSVC 14.44, Ninja, RelWithDebInfo and Vulkan SDK 1.4.363.0, with an RX 7900 XT and 32 GB of RAM, while another
gta6rtwas running on the same GPU.Latest
mainmerge:leaks/allat5fe777296, all 31 fixes then in this branch withmain8b318bd40merged in (154 commits since7daa4a4a5). One conflict, ind3d12/crates/leonida-gpu/src/list.rs:main's7efbbdd39(LEONIDA_ALLOCATOR_TRIM=1, off by default: idle host lists older than the limit are let go) andRS-HOST-LIST-ALLOCATOR-PEAK(the idle pool as aPool, its untouched lists halved once a second) both changed the idle host-list pool. ThePoolstays; an idle list keeps when it was put by, and withLEONIDA_ALLOCATOR_TRIMits stale oldest are taken out of thePool(newPool::take_oldest, with a unit test) and counted inALLOCATOR_TRIMS[2]as onmain, under the same condition. MEASURED on the same machine:gta6rtand every test target, after a full relink.-j 8: 3 of 527 fail, the same three as onmain.pso_stream,xs_proxy_mock*,pipeline_cache_store,d3d12_session_cache_seedandmem_probe_vmmapunderLEONIDA_VK_VALIDATION=1: 14/14.cargo test --workspace --no-fail-fastind3d12/:leonida-gpu523 passed (withlist::tests9/9) andleonida-hle214 passed; the failures are the same 4 inleonida-gpu, 2 inleonida-shaderand 1 inxtaskdescribed further down, all onmaintoo.tests/test_*.py, the same 10 fail as at the merges before (listed below);tests/,tools/andscripts/are as onmain.Earlier
mainmerges, each MEASURED the same way with no failure that is not also onmain:d51ad23b7(main7daa4a4a5; one conflict inruntime/test/pso_stream_test.cpp, where #2476'stest_later_subobject_versionsandRT-PSO-BYTECODE-INTERN's three tests are all kept) andabdb93f0e(maind48a957bb, no conflict). The failures onmainthat show in every run:leonida-shaderemit::valu_tests::{typed_d16_table_uav_roundtrip_uint_sint_and_float, rdna_forms_give_what_the_spelled_out_ones_give}andxtaskpolicy::tests::repository_passes_policy(lower.rsover the size limit), both in code these fixes do not touch, and 10 standalone Python tests (tests/,tools/andscripts/are as onmain):test_bc_feature_validation,test_bcpack_history_calib,test_build_runtime_fallback,test_make_game_pipelines,test_make_game_preflight,test_progress_dashboard,test_sampler_source_census,test_spirv_metal_set0_cli_errors,test_spirv_metal_set0_extra,test_tool_stdout_encoding.leaks/allat098342d02: the 13 fixes, withmain33db04a70merged in. One conflict came from #958, which maderelease_child_referencethe single path that drops a child proxy's last reference (the queue and fence pins use it too). The allocator's upload memory is now given back in that function, by the proxy'skind, so every path that drops an allocator's last reference frees it. The mock inxs_proxy_mock_test.cppkeeps the fields from both sides.RT-UPLOAD-ARENA-REWINDxs_proxy_mock(check_upload_rewind), newxs_proxy_mock_upload_rewind_offRT-PSO-BYTECODE-INTERNpso_streamRT-SPARE-LIST-EPOCHSxbox_list_cut_spares,command_listRT-SLOT-RECORDS-BUCKETSconsole_heap_slot_recordsRT-REHYDRATE-SCRATCH-TICKETxbox_bvh_builder,xbox_bvh_builder_checkRT-FSSM-ARENA-SHAREd3d12_code_base_share,d3d12_code_base_per_psoRT-TITLE-BUFFER-FALLBACKd3d12_title_buffer_fallbackRT-SLOT70-DEVICE-CYCLEd3d12_existing_heapunderLEONIDA_VK_VALIDATION=1RT-MEM-PROBE-WINDOWSmem_probe_vmmapRT-ZERO-IMAGES-RETRYd3d12_zero_image_retryRT-TITLE-TEXTURE-GONE-RANGESd3d12_existing_heap(check_mapped_plane_gone_in_registry)RT-SHADOW-GPU-RELEASED-RANGESd3d12_shadow_gpu_releases,d3d12_console_heap_gpu_releasesRT-SLOT70-OWNED-RETIREd3d12_title_image_retire,d3d12_title_image_idle,xmemmaind44285197without that fix, and failed there (the commit messages say how). Betweend44285197and33db04a70,mainchanged these files for the stub pipelines (bbc750655,78159b886), which do not touch the paths these fixes change, and for d3d12_xs: retain queue and fence wrappers through forwarded calls #958, merged as described above.xs_proxy_mock*,pso_stream,command_list,xbox_list_cut_spares,console_heap_slot_records,xbox_bvh_builder*,d3d12_code_base_*,d3d12_title_buffer_fallback,d3d12_existing_heap*,mem_probe_vmmap,memory_breakdown,d3d12_zero_image_retry,d3d12_*_gpu_releases,d3d12_title_image_*,xmem*,allocator_proxy,device_proxy,title_texture_refresh,d3d12_title_va,d3d12_compute,d3d12_draw), with-j 4: 41/41 passed.LEONIDA_VK_VALIDATION=1.d3d12_existing_heap,d3d12_title_image_retire,d3d12_title_image_idle,d3d12_zero_image_retry,d3d12_title_buffer_fallback,d3d12_shadow_gpu_releases,d3d12_code_base_share,allocator_proxyandxs_proxy_mockpassed 9/9. There were no validation errors and noVUID-vkDestroyDevice-device-05137. Onmain,d3d12_existing_heapleaves 93 objects atvkDestroyDevice.-j 4, run twice (before and after merging33db04a70): 519/523 both times. Three tests failed both times, and they also fail on plainmainon this machine; none of these fixes touches them:d3d12_texture_tiles: the CopyTiles offset rounding on AMD (test: texture tiles NOTE only for the measured CopyTiles offset rounding on AMD and Intel (D3D-TILES-AMD-BYTE-OFFSET) #964).pipeline_cache_seed: the checker's device differs from the runtime's (vk_pipeline_check: choose robustBufferAccess and VK_EXT_robustness2 as the runtime does (RT-PIPELINE-CHECK-ROBUSTNESS) #1833).d3d12_clear: a NaN depth clear reads back 1.dxgi_waitable_latencyin the first run andrun_tiny_game_abort_exit_codesin the second. Each passes when run alone (the second 3/3), so they are timing-sensitive under-j.gta6rtand every test target build and link.python -I scripts/check_no_game_data.pypasses on every changed file, andpython -m compileall -q make_game.py tools testsis clean. Of the 534 standalonetests/test_*.py, 7 fail, the same 7 with the same output as onmain33db04a70(test_docs_cli_flags,test_docs_env_vars,test_docs_python_deps,test_docs_repo_paths,test_make_game_preflight,test_progress_dashboard,test_tool_stdout_encoding).test_docs_env_varsfails only onLEONIDA_CLWB_PATCH, which is not from this branch; the new switches are all documented.In the game: PROVISIONAL (n=1 per arm). Two sessions of 720 s each, both stopped by the harness at the end:
maind48a957bbalone, and this branch at32d2020f7(all 30 fixes; itsruntime/is the same as ateb145de6f, which only adds the test-onlyleonida-hlemerge fix). Same build type, the same first-run-UI input, each started from the same copy of the pipeline caches,LEONIDA_TITLE_WATCHDOG=0with its kick,LEONIDA_MEM_PROBE=10, and an outside sample of the process every ~11 s. Resizable BAR off. The character stands still in the world from about 420 s.main, 9,218 with the fixes, none failed).mainand 20,786 MiB with the fixes, and at the end (714 s) 20,965 and 21,010 MiB. Slope from 450 to 720 s: +41.5 and +47.8 MiB/min. Dedicated video memory, flat from about 420 s: 8,544 and 8,659 MiB. The runtime's Vulkan allocations (mem probe), flat from 360 to 700 s: 8,405 and 8,494 MiB. With one run per arm and no prediction written beforehand, these are observations: there is no measurable difference in 12 minutes.main, +91 with the fixes, after 420 s). MEASURED standalone (a separate Vulkan program, no code from this repository, on the same GPU and driver, 22 real vertex + pixel shader pairs from the translated library with the runtime's bindless set layout and dynamic states): each first compile leaves the driver holding a median 2.4 MiB of private memory (0.4–19 MiB) after its shader modules are destroyed;vkDestroyPipelinegives none of it back, destroying all 22 gives back about 0.3 MiB each, and compiling and destroying at once still adds 2.4–3.9 MiB a compile. A pipeline made again from the pipeline cache costs 23–47 KiB and 0.1–0.4 ms. About 19 new pipelines a minute at ~2.4 MiB each is the ~45 MiB/min seen in both sessions (an inference from the two measurements, not measured inside the game). So this growth is the driver's, per compile, and not from these fixes; only compiling less (a pipeline already in the seed or the heavy cache) reduces it, and destroying cold pipelines would give back little.d3d12/and do not run ingta6rt.AllocateUploadMemory(list slot 148) was never called in either session (the runtime logs every list slot's first call), soRT-UPLOAD-ARENA-REWINDwas not exercised, and an idle character does not churn PSOs or retire title windows.maind44285197against the first 13 fixes, without the watchdog variables) ended at the title's hang watchdog at about 400 s in both, also with no regression.GPUs tested: AMD Radeon RX 7900 XT, 20 GB, desktop (profile M), AMD Software 26.11.2 (D3D12 driver 32.0.32029.2010, Vulkan driver 2.0.416), Windows 11 Pro 26300, 32 GB RAM
Second sweep in
d3d12/(25 more items)Pushed at
26e00403c(with currentmainmerged): fewer copies of each byte the title writes between the PC's memory and the card's, more title memory read in place, and more leaks. Claimed in #2570 (round 2); what each does, its switch and how it was tested are in this comment. Branchesadrianmjim/leonida:unified/<name>:send-pool-trim,compare-ring,landed-cells-gate,small-leaks,placed-textures,texture-staging-release,descriptor-views,inplace-free,placement-bench,card-one-copy,inplace-blockers,page-pool-open,shadow-hot-paths,exact-waits,physical-reuse,title-alloc-watch(withxmem-combined).leonida-gpu630 passed / 48 ignored,leonida-hle243 passed / 2 ignored.A third round (7 branches,
19006b0e6): landing in the submission, no forced sweep settle, detiling only what changed, more memory in place, GPU upload buffers, hot-path bookkeeping and a fix of in-place holds; see this comment.leonida-gpu690 passed / 50 ignored.A fourth round (
7cc8e1879): card copies whose CPU side is title memory itself, in-place memory opened off the lookup path, a send ring, the compare measured and shared, list summaries at close, and a fix of double releases; see this comment.leonida-gpu718 passed / 51 ignored.Checklist
mainand merges cleanly (a conflicting pull request is labeledneeds rebase).runtime/and sixteen ind3d12/, and twenty-five more ind3d12/from a second, together only because of the open pull request limit. Each one is its own merge here and its own branch on the fork.)docs/design.md, with how it was confirmed. (n/a: no translator change)