Skip to content

d3d12: track live console-heap V# slots in a host-RAM bitset (RT-CONSOLE-HEAP-VSHARP-BITSET) - #1887

Merged
aslan2142 merged 1 commit into
ProjectLeonida:mainfrom
IlyassRS3:rt-console-heap-vsharp-bitset
Nov 25, 2026
Merged

aslan2142 merged 1 commit into
ProjectLeonida:mainfrom
IlyassRS3:rt-console-heap-vsharp-bitset

Conversation

@IlyassRS3

Copy link
Copy Markdown
Contributor

Item: RT-CONSOLE-HEAP-VSHARP-BITSET
Claim: #1608 (comment)

Summary

Eliminates uncached write-combined GPU memory reads from heap.copy during console resource-heap invalidation scans in refresh_console_heap() (runtime/shims/d3d12_vulkan_device.cpp).

  • Root cause: Whenever released_backings or title_va_aliases().invalidations() advanced, refresh_console_heap() scanned every 32-byte slot of heap.copy linearly (for (size_t at = 0; at + kDescriptorSize <= heap.bytes; at += kDescriptorSize)) checking !(w[3] >> 30) && (w[2] || w[6]). When heap.copy falls back to arena.mapped (uncached WC GPU memory — e.g. when import_console_heap cannot land within 4 GiB of arena.address or host-memory import is unavailable), reading 4–5.5+ MiB of WC memory triggers ~130k–180k uncached PCIe reads per buffer release (hundreds of ms/submission); even in cached scratch memory it linearly scans all empty and T# slots.
  • Fix:
    • Add portable header-only leonida::ConsoleHeapVsharpSlots (runtime/src/console_heap_vsharp_slots.h), a dense host-RAM uint64_t bitset (~22 KiB for a 5.5 MiB heap, L1-resident) with O(1) empty() fast path, clear_range() for zeroed page runs, std::countr_zero iteration safe against in-place bit clears inside the callback, and is_live_vsharp(w) matching the exact legacy predicate !(w[3] >> 30) && (w[2] || w[6]).
    • Keep heap.live_vsharps synchronized at every resource-heap write to heap.copy: add_console_heap (reset), fix_console_slot (set), fix_console_slots deferred zeroing (clear), and for_each_zeroed (clear_range).
    • Walk heap.live_vsharps.for_each(...) in refresh_console_heap instead of reading heap.copy.

No overlap with #1728 or #1867.

Verification

  • AI-assisted: yes
  • GPUs tested: none (CPU-only macOS arm64 host; d3d12_vulkan_device.cpp is Windows-only and verified by inspection + Windows CI)
  • New portable unit test runtime/test/console_heap_vsharp_slots_test.cpp (CTest console_heap_vsharp_slots), including a 4,000-step differential model against a linear 32-byte slot buffer (fix_console_slot, not_tsharp, deferred zeroing, clear_range, in-place invalidation clears) and 5.5 MiB sparse heap check:
    • clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=address,undefined: passed
    • clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=thread: passed
    • clang++ -std=c++20 -Wall -Wextra -Werror -O2 (3 runs): passed
  • Synthetic cached-RAM microbenchmark (5.5 MiB heap = 180,224 slots, 2,048 live V#s, -O2 on Apple Silicon): linear scan 60.30 us vs bitset 0.93 us (64.9x faster even in cached RAM; eliminates 100% of WC reads from heap.copy when heap.copy is in arena.mapped)
  • python3 -I scripts/check_no_game_data.py on all changed files: passed
  • python3 -I tests/test_text_write_line_endings.py: passed (3 tests)

Copilot AI balanced review requested due to automatic review settings November 25, 2026 14:30

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@DadaCap

DadaCap commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Retail evidence for the root cause here, from a local change of the same shape (a per-slot byte map of live V#s in host memory instead of the scan of heap.copy; I have not run this branch): RTX 5080, NVIDIA 621.24, Windows 11, story load up to the first world frames, longest single heaps time per 5 s log interval.

t (s) scan of the copy (main) host-memory map
24 to 25 556 ms 16 ms
29 to 30 473 ms 10 ms
39 to 40 417 ms 6 ms
54 to 55 454 ms 8 ms
64 to 66 486 ms 8 ms

The average per submission outside those spikes did not change (about 3.4 ms): that is the copy of the part of the heap under a slot-133 import (27,648 KiB, pinned pages), a different cost. One run each, the second with more captures written. I had planned to send mine and won't, yours was claimed first; note that this one is dirty against current main. AI-assisted (Claude Code).

When released_backings or title_va_aliases().invalidations() advances,
refresh_console_heap() previously scanned all 32-byte slots of heap.copy
linearly to find live buffer V#s (!(w[3] >> 30) && (w[2] || w[6])). When
heap.copy sits in arena.mapped (uncached write-combined GPU memory), each
buffer release triggered ~180k uncached PCIe reads across a 5.5 MiB heap.

Add a portable host-RAM bitset (leonida::ConsoleHeapVsharpSlots in
runtime/src/console_heap_vsharp_slots.h) updated at every resource-heap
write to heap.copy (fix_console_slot, deferred fix_over zeroing,
for_each_zeroed, and add_console_heap reset), and iterate only live V#
slots during invalidation passes (0 reads from heap.copy; 64 slots skipped
per word via std::countr_zero).

Item: RT-CONSOLE-HEAP-VSHARP-BITSET
@IlyassRS3
IlyassRS3 force-pushed the rt-console-heap-vsharp-bitset branch from 36d1e08 to 3233b98 Compare November 25, 2026 16:20
clquwu added a commit to clquwu/leonida-ultimate that referenced this pull request Nov 25, 2026
…1887) & staging pool (#781)

Wave 11D fixes four d3d12_vulkan_device.cpp hot-path regressions (GPL-3.0, zero non-trivial thread_local):

1. Page-dirty-only console descriptor heap diff + AVX2/SSE2 compare:
   - Extend leonida::title_shadow::Shadow::refresh() (runtime/src/title_shadow_sync.h) with optional std::vector<DirtyRange>* output recording exact changed 64 KiB page slices (page index, byte offset/length, zeroed flag).
   - Update DeviceState::refresh_console_copy() to scan ONLY changed 64 KiB pages (instead of all 32 MiB / 1M slots when 1 page changes), skip zeroed pages on initial refresh, fast-clear aligned zeroed pages, and compare 32-byte descriptors via AVX2/SSE2 (equal_descriptor_32 / is_zero_descriptor_32) instead of scalar memcmp.

2. Eliminate uncached WC arena.mapped reads in scan_title_table & host-RAM V# bitset:
   - Add leonida::ConsoleHeapVsharpSlots (runtime/src/console_heap_vsharp_slots.h, adapted from ubiquitarianism/leonida#1887, author IlyassRS3) tracking live console-heap buffer V# slots in L1-resident host RAM.
   - Skip console heaps in scan_title_table() (already refreshed & sanitized from cached host RAM by refresh_console_heaps() in before_execute_()).
   - Add a 128-entry per-submission epoch span cache for layer shader-visible heaps (invalidated on before_execute_(), heap create/destroy, and arena descriptor API writes) and stream-copy cache misses from WC arena.mapped via SSE4.1 MOVNTDQA (_mm_stream_load_si128) in 64-slot chunks, writing back only modified slots.

3. Bounded LIFO size-classed texture upload staging buffer pool:
   - Adapted from fxceless/victory-fork#781 (GPL-3.0, author marquezinii): 256 MiB cap, 64 KiB steps up to 1 MiB then 8 steps/power-of-two, separate upload vs cached-readback buckets, LIFO reuse, fullest-class oldest eviction outside the pool lock, and clean teardown in ~Device().

Note: ubiquitarianism/leonida#1926 (TitleImagePool / vulkan_title_image_pool.h) does not apply because leonida-ultimate uses VulkanSuballocator (vulkan_suballoc.h, outside W11D file boundary).

Verified (RTX 3080, VK_VALIDATION=1, 0 validation errors):
- 6/6 GPU CTests passed: d3d12_vulkan_device, d3d12_xmem_shadow, d3d12_unmapped_vsharp, d3d12_subresource_copy, d3d12_console_descriptor_heap, d3d12_console_table_draw
- Dirty-page scan: 1-slot write in 16-page heap scanned 1 page (2,048 / 32,768 slots); idle submit scanned 0 pages
- Staging pool: 1 created / 3 reused in d3d12_unmapped_vsharp; 2 created / 38 reused in d3d12_subresource_copy
- title_shadow_sync_test: 16/16 new dirty-range & ConsoleHeapVsharpSlots checks passed (84/85 total; 1 pre-existing line-139 coalesced-run split check from 8cd13ce)
- check_no_game_data.py: 0 violations; test_docs_env_vars.py: 4/4 OK
@kawaii-shakal

Copy link
Copy Markdown
Contributor

Independent test report for 3233b98 (VERIFY-1887-1957-BLACKWELL, claimed in #1608).

Setup: Windows 11 Pro 26300, VS 2026 MSVC, RelWithDebInfo, RTX 5070 Ti (Blackwell), NVIDIA driver 617.42, LEONIDA_VK_DEVICE=5070. Clean configure and full build of runtime/ succeed with MSVC.

Full CTest (ctest -j 6 --timeout 600):

tree result
base main 9e7720c 423/423 passed, same 11 skipped, 2 disabled
this PR 3233b98 424/424 passed, same 11 skipped, 2 disabled

The one new test, console_heap_vsharp_slots, passes. The skipped ones are the same as on base (game files or features this setup does not have: shader_library_corpus, bink, fsr_dispatch, bvh_builder, vk_sync_validation, d3d12_rgb9e5_rtv, d3d12_boot_movie, d3d12_first_light).

Repeat runs: console_heap_vsharp_slots, d3d12_title_va, d3d12_title_va_shadow, d3d12_unmapped_vsharp and the nine xs_proxy_mock* tests, --repeat until-fail:20 -j 4: all 13 passed all 20 rounds.

AI-assisted (Claude Code, Claude Opus 5.5).

@x2Tweek

x2Tweek commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Measured on Windows 11 with an NVIDIA RTX 5090 (driver 32.0.16.2124), retail boot past the opening credits, runtime of current main plus #1867 and a local debug overlay, 900 s runs with the same scripted input, from the [rt] submit phases and console descriptor heap lines:

without #1887 with #1887
console heap refresh per submission 0.6-1.3 s on average, peaks 5-7 s 7-19 ms
frames presented in 900 s 1,225 5,450

The invalidation rescans still run (982 in the run with #1887); they are simply cheap once they no longer read the write-combined heap copy. I also tried filtering those rescans to the slots that name a released range on top of this PR: no further gain, so this PR alone is the fix. AI-assisted: yes.

@qhukz13

qhukz13 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Independent run on Windows 10 19045, GTX 1050 Ti (Pascal, 4 GB, no Resizable BAR), NVIDIA 582.66, MSVC (VS 18 Build Tools), RelWithDebInfo. Base b0f3d3998 with this PR (3233b9857) and #1957 applied together (they touch different code).

  • Builds clean under MSVC.
  • Full ctest: 451 tests, 16 failed. These are the same 16 that fail on plain b0f3d3998 (449 tests), apart from xmem / xmem_no_write_watch swapping places; both pass 5/5 on rerun, so that pair is flaky and unrelated.
  • console_heap_vsharp_slots: passes 3/3, plain and with LEONIDA_VK_VALIDATION=1.
  • Existing tests near the change (d3d12_unmapped_vsharp, d3d12_title_va*, d3d12_api_descriptor_copy*, d3d12_rebound*, xs_proxy_mock*, d3d12_xmem_placed): pass 3/3 with no validation messages. The one exception is d3d12_geometry_views, which fails on main too, at root-signature serialization (d3d12_title_va_test.cpp:1067).
  • Not covered: none of these runs reaches the arena.mapped (write-combined) fallback of heap.copy, so the speedup itself was not measured here.

AI-assisted (Claude Code).

@KushGene

Copy link
Copy Markdown

Independent Wine/RADV report for 3233b9857 against its merge base b0f3d3998. All 448 shared tests had the same outcome. The new console_heap_vsharp_slots test passed in the suite and in 20 additional standalone runs of the Windows executable.

Revision Registered Passed Failed Skipped Disabled
Base b0f3d3998 448 391 15 40 2
PR 3233b9857 449 392 15 40 2

Fedora 45, AMD Radeon RX 6700 XT (NAVI22), Mesa RADV 26.2.7, Wine Staging 11.21. A Windows Vulkan probe enumerated only AMD 1002:73df. Cross-built the unmodified revisions with clang-cl/LLD 23.1.5, xwin SDK 10.0.26100 and CMake 4.3.0 (Ninja, RelWithDebInfo, D3D12 shim tests enabled, Rust XMA2 decoder built). SDL3 was unavailable, so CTest disabled its two GameInput tests. Ran the entire configured suite with four workers, then reran every failure individually on both revisions.

d3d12_set_descriptor_heaps, d3d12_geometry_views passed on both revisions. The same 15 failures reproduced individually on base and PR:

bcrypt_rng, bcrypt_rng_seeded, d3d12_clear, d3d12_clear_formats, d3d12_clear_restricted_depth, d3d12_console_descriptor_heap, d3d12_mesh, d3d12_xs_root_signature, device_proxy, device_proxy_trace, file_system, gameinput_host, pipeline_cache_seed, root_sig, xbox_gpu_label_completion.

Synthetic tests only. No retail run or frame-rate measurement. AI-assisted (Codex). Coordination claim.

@x2Tweek

x2Tweek commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Correction to the measurement above. The run with this PR recorded 2,725 successful presents in 902 seconds. The reported 5,450 counted each present twice because both the presentation and command queue trace layers reported it. The comparison run recorded 1,225 successful presents in 902 seconds.

The 2,725-present run also used different refresh and rescan settings from the comparison run, so the present totals describe the two configurations. They do not isolate this PR's effect.

AI-assisted: yes.

@aslan2142
aslan2142 merged commit c373741 into ProjectLeonida:main Nov 25, 2026
2 of 5 checks passed
@aslan2142

Copy link
Copy Markdown
Collaborator

Merged, thanks! Maintainer review of 3233b9857 merged onto main (the merge is mechanical):

  • Correctness: every CPU write to a resource heap's copy updates the bitset, and the release walk visits exactly the slots the old scan matched. This holds with LEONIDA_CONSOLE_FIX_US=0 (now the default) and with the retry budget. d3d12_vulkan: a title texture destroyed inside the registry is removed after the registry lets go (RT-TITLE-TEXTURE-GONE) #1798, which landed in between, touches only the title-texture registry and adds no writer to the heap copy.
  • Full runtime suite under Wine (llvmpipe and the RADV iGPU): no new failures. console_heap_vsharp_slots passes, and the new test fails on three mutated versions of the header.
  • Checked on main 9f9a7c5f3 + 3233b9857: it merges cleanly; the semantic suite passes (490 files, 6,292 tests, 0 files failed); the 15 docs and writer tests pass; check_no_game_data.py is clean on the 4 changed files.
  • Non-blocking follow-up: no test drives the release walk in refresh_console_heap itself, so a dropped set call there would still pass every test.

AI-assisted (Claude Code, Claude Opus 5.5).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants