Skip to content

gpu: defer CreateCommittedResource for read-only slot 133 textures - #2773

Open
triggered02 wants to merge 2 commits into
R0Y00:mainfrom
triggered02:gpu/slot133-lazy-textures
Open

triggered02 wants to merge 2 commits into
R0Y00:mainfrom
triggered02:gpu/slot133-lazy-textures

Conversation

@triggered02

@triggered02 triggered02 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Adds opt-in lazy desktop materialization (X2W_D3D12_LAZY_TEXTURES=1) for read-only slot 133 textures (!(Flags & (ALLOW_RENDER_TARGET | ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS))). Fixes #2764. Refs #2379, #1199.

What changed

  • src/startup_stubs/d3d12_xs_device.cpp:
    • Under X2W_D3D12_LAZY_TEXTURES=1, device_place_resource_x (slot 133) defers CreateCommittedResource and x2w_budget::committed for read-only 2D/3D textures by wrapping nullptr (lazy_slot133_texture = true), recording the sanitized D3D12_RESOURCE_DESC, format, and title_memory, and preserving note_resource and retire_set_class eligibility.
    • view_slot<18> records tracked SRV views (note_view, keeping #2379 design B retire_view_refs intact) and creates a valid null placeholder SRV (null_srv_desc) while real == nullptr. view_slot<19..21> and forward_slot<resource_kind, 12/13/14> materialize first if needed.
    • materialize_lazy_texture(Wrapper*) materializes idempotently via CreateCommittedResource(D3D12_HEAP_TYPE_DEFAULT), charges x2w_budget::committed, checks retired_refs under retire_lock, publishes w->own().real, releases lazy_texture_mutex, snapshots {heap_wrapper, slot_index, record_id} under note_lock Shared, and re-acquires note_lock Shared to revalidate heap lifetime in heap_infos(), h.shadow[slot_index] == record_id, and vr.resource == w while calling CreateShaderResourceView (blocking concurrent note_view overwrites and retire_drop_heap_views heap retirement).
    • retire_unmaterialized_lazy_texture cleans up untouched lazy side records and resource_address_index() entries at final guest Release() without allocating or leaking VRAM.
    • Exports x2w_d3d12_lazy_texture_count() and x2w_d3d12_set_lazy_refresh_hook() for fixture verification.
  • src/startup_stubs/d3d12_compute_dispatch.inl: adds retire_hold(self, view.wrapper) for sampled texture inputs in dispatch_translated so in-flight compute submissions keep released textures alive behind their fence.
  • src/startup_stubs/d3d12_capture.inl, src/startup_stubs/d3d12_memory_srv.inl, src/startup_stubs/list_copy.inl, src/startup_stubs/list_copy_texture.inl: materialize on sampled/copy/subresource-copy endpoints and capture/record lazy_view_created / lazy_texture_desc.
  • tests/startup_slot133_lazy_textures_check.cpp & tests/cmake/startup_slot133_lazy_textures.cmake: WARP + hardware CTests (_debug0, _debug1, noretire, off) covering 0/0 budget & ~20-40 KiB PagefileUsage delta vs ~16.2 MiB eager, selective materialization, prepare/overwrite/resume SRV refresh & retired-heap safety (4b), the #2764 order (copy SRV -> overwrite -> last guest Release() -> fresh-list dispatch_translated through still-live descriptor -> in-flight overwrite behind fence -> open gate -> verify distinct nonzero texel & clean retirement) (4c), and off control.
  • docs/startup-runtime.md, docs/experiments.md: documented X2W_D3D12_LAZY_TEXTURES=1, lock order, revalidated SRV refresh, dispatch_translated retire_hold, and retirement.

Verified (92db6d4e, rebased on 624f5927)

cmake --build --preset dev --target d3d12_xs_shim startup_slot133_lazy_textures_check startup_resource_retire startup_resource_retire_title startup_resource_retire_views startup_resource_retire_reasons startup_resource_budget
ctest --preset dev --no-tests=error -R '^(startup_slot133_lazy_textures|startup_resource_retire(_title|_views|_reasons)?_|startup_resource_budget)' --output-on-failure
  → 42 tests: 30 passed (100% of runnable), 0 failed, 12 skipped (all *_debug1: SDK Layers not installed)
python -B tests/docs_links_check.py     # 23 Markdown files, 541 links
python -B tests/bidi_controls_check.py   # 2018 files, no bidirectional controls
git diff --check                         # clean

Fail-first mutants (temporary, reverted on 92db6d4e):

  • Skip target_heap->shadow[item.slot_index] != item.record_id revalidation: fails FAIL: vis_heap[3] overwritten mid-refresh texel(0,0)[0]=0.89020 expected=0.35294.
  • Skip retire_hold(self, view.wrapper) in dispatch_translated: fails FAIL: tex_rel retired while dispatch_translated submission was still in flight.
  • Skip materialization on CopyTextureRegion: fails CopyTextureRegion refused: unknown_resource and FAIL: tex[3] CopyTextureRegion readback had 1045504 mismatched bytes.
  • Eagerly materialize at slot 133 with X2W_D3D12_LAZY_TEXTURES=1: fails FAIL: lazy creation committed textures: live=16777216/16 retained=0/0.

NOT established

  • _debug1 cases skipped (77) on this host without D3D12 SDK Layers.
  • On a full workload run, slot 133 still commits ~4.1+ GiB of textures that carry ALLOW_RENDER_TARGET / ALLOW_DEPTH_STENCIL / ALLOW_UNORDERED_ACCESS (read_only_texture == false); deferring unused RT/DS/UAV textures is outside this PR.

AI-assisted.

@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-26T07:38:04.945189Z
We couldn’t complete this review. Comment @codex review to try again.
3cdc4ab PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@tedin7

tedin7 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

Win2025 WARP receipt for head 3cdc4ab.

  • Dev (--preset dev): ctest -R 'startup_slot133_lazy_textures_(warp|noretire_warp|off_warp)' ran 4 tests: 3 passed (warp_debug0, noretire_warp, off_warp), 1 skipped (warp_debug1, exit 77, no debug layer on the VM). 0 failed.
  • Release (--preset release): same 4 tests, same result (3 passed, 1 skipped).
  • Note: the auto-planned run did not build startup_slot133_lazy_textures_check, so I reran with --targets startup_slot133_lazy_textures_check.
  • *_hardware variants were not run (WARP-only VM).

Review of this head (code + fixture tests only):

AI-assisted; commands listed were executed locally.

@R0Y00 R0Y00 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Independent Windows Release ran all 8 existing lazy texture CTests on WARP and RTX 4060 Laptop, including both debug1 variants. Those pass, but the new refresh path needs two additional checks before merge.

  1. materialize_lazy_texture snapshots PendingSrvRefresh destinations under note_lock, releases the lock, then writes the old CPU handles. A normal slot overwrite or heap retirement can occur in between, including on a different thread from the texture copy that first materializes this resource. Revalidate slot identity and heap lifetime at publication or coordinate the update with the existing descriptor lock and recording/fence lifetime. A prepare/overwrite/resume control must leave the replacement view bound and must not touch a retired heap.
  2. The current fixture copies the SRV, explicitly materializes with CopyTextureRegion while the guest still owns the resource, then samples and finally releases. Add the #2764 order of copy SRV, last guest Release, and first use through that still-live descriptor on a fresh list. Give the texture a distinct nonzero reference. Keep the explicit overwrite and in-flight retirement controls. Native first use must reach a materializer or stay on the eager path.

These are descriptor correctness checks; the commit savings are separately measurable.

@triggered02
triggered02 force-pushed the gpu/slot133-lazy-textures branch from 3cdc4ab to 92db6d4 Compare November 26, 2026 08:20
@triggered02

Copy link
Copy Markdown
Contributor Author

Addressed both points of R0Y00's review at 92db6d4e (rebased onto main 624f5927):

  1. Race-free SRV descriptor refresh & prepare/overwrite/resume control (src/startup_stubs/d3d12_xs_device.cpp materialize_lazy_texture):
    • Releases lazy_texture_mutex right after publishing w->own().real, mark_packed_stand_in, and budget.
    • Snapshots {heap_wrapper, slot_index, record_id} under note_lock Shared, then re-acquires note_lock Shared around revalidating that heap_wrapper is still live in heap_infos(), h.shadow[slot_index] == record_id, and vr.slot == 18 && vr.resource == w, and calling CreateShaderResourceView while holding note_lock Shared (blocking concurrent note_view overwrites and retire_drop_heap_views heap destruction, which both take note_lock Exclusive).
    • Exported x2w_d3d12_set_lazy_refresh_hook and added Step 4b in tests/startup_slot133_lazy_textures_check.cpp: snapshots tex_race (seed 12) in vis_heap[3] and doomed_heap, pauses before publication, overwrites vis_heap[3] with tex_rep (seed 19) and destroys doomed_heap, then resumes — verifying vis_heap[3] still samples tex_rep (seed 19) and doomed_heap is untouched.
  2. #2764 order (copy SRV -> last guest Release() -> fresh-list first use through still-live descriptor) + dispatch_translated retire_hold:
    • Added if (view.wrapper && !view.wrapper->own().tiled_address_srv) retire_hold(self, view.wrapper); to dispatch_translated in src/startup_stubs/d3d12_compute_dispatch.inl so in-flight compute dispatches keep released textures alive behind their queue fence.
    • Added Step 4c in tests/startup_slot133_lazy_textures_check.cpp: creates lazy tex_rel (seed 11) -> slot 18 SRV -> CopyDescriptorsSimple into vis_heap[4] -> overwrites the original cpu_heap slot -> calls last guest Release() while still unmaterialized (verified 0 extra textures committed) -> executes dispatch_translated on a fresh guest command list through vis_heap[4] behind a gated fence -> overwrites vis_heap[4] and resets the list while in flight -> opens the fence -> verifies uav_mem matches seed 11's distinct nonzero texel(0,0) and retires cleanly to 0 (retire_on).
    • Audited list_set_descriptor_heaps, list_table, list_compute_table, list_copy*, list_resolve_subresource, forward_slot, draw_translated, and dispatch_translated: native list_draw/list_dispatch never bind guest descriptor heaps/tables (refused/unforwarded); all copy/resolve/subresource/translated paths reach materialize_lazy_texture.

Verified on 92db6d4e (dev preset):

  • ctest --preset dev --no-tests=error -R '^(startup_slot133_lazy_textures|startup_resource_retire(_title|_views|_reasons)?_|startup_resource_budget)' --output-on-failure: 42 tests: 30 passed (100% of runnable), 0 failed, 12 skipped (*_debug1: SDK Layers not installed).
  • tests/docs_links_check.py: 23 Markdown files, 541 links; tests/bidi_controls_check.py: 2018 files clean; git diff --check: clean.
  • Fail-first mutants (temporary, reverted):
    • Skip target_heap->shadow[item.slot_index] != item.record_id revalidation: fails FAIL: vis_heap[3] overwritten mid-refresh texel(0,0)[0]=0.89020 expected=0.35294.
    • Skip retire_hold(self, view.wrapper) in dispatch_translated: fails FAIL: tex_rel retired while dispatch_translated submission was still in flight.

AI-assisted.

clquwu added a commit to clquwu/leonida-ultimate that referenced this pull request Nov 26, 2026
…om spare trim, RT DispatchX hardening & SRWLOCKs

- Lazy materialization for read-only 2D/3D slot-133 textures (clean-room MIT from R0Y00/Xbox2Windows#2773):
  defer CreateCommittedResource / VkImage + VRAM allocation until first SRV/view/copy/barrier use while
  answering metadata/residency queries and untouched Release with zero VRAM (LEONIDA_LAZY_SLOT133_TEXTURES).
- 256 MiB existing-heap / page-commit cap for slot-133 buffers (clean-room MIT from R0Y00/Xbox2Windows#2775):
  oversized title buffer reservations fall back to committed DEFAULT without whole-span page commit
  (LEONIDA_SLOT133_HEAP_CAP_MB, LEONIDA_UNBOUNDED_EXISTING_HEAP).
- VRAM-headroom-scaled spare pool retention, 64-frame idle upload-ring reclamation & non-local shared memory
  pressure tracking (GPL-3.0 from avatarmanz/VIctory-7900XTX#119 and Marvisak/VIctory#2972).
- RT structure builder DispatchX hardening (GPL-3.0 from fxceless/victory-fork#994): accept compact 20-byte
  FSPX kind0 headers (w4 at byte 16..19) and inherit compute workgroup dims through derived PSOs (slot 55).
- Reader-writer SRWLOCK conversion for hot read-mostly registries in d3d12_xs_device.cpp (GPL-3.0 from
  wolfattack199/victory-fork@d3d3760) with zero non-trivial thread_local.
- Unit tests in d3d12_xs_format_sanitize_test.cpp and d3d12_texture_mip_drop_test.cpp.

Verified: 10/10 CTests passed on NVIDIA GeForce RTX 3080 under LEONIDA_VK_VALIDATION=1 (0 validation errors);
check_no_game_data.py 0 violations.
@R0Y00

R0Y00 commented Nov 26, 2026

Copy link
Copy Markdown
Owner

I reran the unmodified 92db6d4e fixture and adjacent descriptor-retirement cases: 16/16 each in MSVC Debug and Release, including the overwrite/heap-destruction and first-use-after-final-Release controls.

One descriptor-copy ordering still produces a null SRV. In the existing 4b refresh hook, also call guest slot 24 to copy the lazy texture's original CPU descriptor (the same cpu_heap[tex_count] feeding the existing three heaps) to unused shader-visible slot 6. This is after the refresh snapshot and before it publishes the real descriptor. Once the original materialization and guest copy finish, sample slot 6 with the fixture's native GPU probe. Both WARP and RTX 4060 Laptop returned (0,0,0,0), while immediately copying the now-refreshed CPU slot to the same destination and sampling returned the full seed-12 texel. Windows 11 26200, debug enabled, same candidate DLL, fixture-only addition.

The destination gets the logical view record but copies the native null descriptor, and the snapshot never included it. Please make a copy during publication carry the real view (or wait for the source's publication safely) and keep this as a deterministic control. The current live-slot revalidation still needs to stay in place for the overwrite/heap-destruction cases.

@tedin7 tedin7 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Win2025 check of the resource retire tests on this head (92db6d4eb):

  • Dev: startup_resource_retire_title_* and startup_resource_retire_views_* pass (14/14).
  • Release: four startup_resource_retire_title tests end in SEGFAULT: title_warp_debug0, title_off_warp, title_hardware_debug0, title_off_hardware. The startup_resource_retire_views tests pass.
  • On current main (8c9f168f4) the same 14 tests pass in dev and release, so the crash is specific to this head in the release build.

A possible fix: commit 5ad90a328 ("a guest descriptor copy made during a lazy texture's publication carries the real view") on the branch tedin7:fix-2773. Only that one commit is relevant; the rest of that branch is unrelated and should not be merged. On a build that includes it, the 14 retire tests pass in dev and release. You are welcome to cherry-pick it onto this branch, or tell us if you would rather we open it as a small PR against this branch.

Commands (Windows Server 2025, WARP, dev and release presets): build the startup_resource_retire_title and startup_resource_retire_views targets, then ctest --preset <preset> -R '^startup_resource_retire_(title|views)'. CTest prints only SEGFAULT, no stack yet.

AI-assisted; commands listed were executed locally.

# Conflicts:
#	docs/experiments.md
#	docs/startup-runtime.md
@lukaslw-lab

Copy link
Copy Markdown
Contributor

Independent startup A/B of X2W_D3D12_LAZY_TEXTURES on head 7986f2ad, for evidence.

Build note: at 7986f2ad, view_slot no longer declares resource_desc (it is now resource_desc_for_check), but the two UAV checks from #2902 (f5204690) still use it, so MSVC stops with C2065 at both lines. That is probably the failing Windows CI job. Locally I changed those two uses to resource_desc_for_check:

-                    skip = volume_uav_range_error(resource_desc, view.Texture3D);
+                    skip = volume_uav_range_error(resource_desc_for_check, view.Texture3D);
...
-                    if (view.Texture1D.MipSlice >= resource_desc.MipLevels) skip = "an output 1D texture mip is outside the resource";
+                    if (view.Texture1D.MipSlice >= resource_desc_for_check.MipLevels) skip = "an output 1D texture mip is outside the resource";

Setup: release build of main e446b072 + this PR (with the fix above) + #3028. Windows 10 22H2 (19045), i7-4790K, 16 GB RAM, RTX 3080 Ti (NVIDIA 32.0.16.1047). Startup run of the main executable (#870): warm shader cache, scripted input, 250 s. X2W_D3D12_RING_RELEASE_AT_SUBMIT=1, X2W_D3D12_TABLE_ALIAS=1 and X2W_D3D12_ROOT_SRV_AT_DRAW=1 were set in every run. One build; only X2W_D3D12_LAZY_TEXTURES differs. Two pairs, the second in reverse order (off, on, on, off). Aggregates only.

150–240 s switch unset switch set
mean fps, pair 1 / pair 2 13.6 / 14.1 15.2 / 15.1
process private memory (average) 17.7 / 18.4 GiB 13.6 / 13.6 GiB
GPU dedicated memory (average) 9.1 / 9.4 GiB 5.4 / 5.4 GiB
process commit peak 19.1 / 20.0 GiB 14.7 / 14.7 GiB
system commit peak 39.6 / 40.4 GiB 35.2 / 35.3 GiB
hard page-ins per second (average) 18,600 / 16,700 15,200 / 14,800
null bindings buffer / token / wrapper 0 / 11,356 / 99; 0 / 9,928 / 104 0 / 11,271 / 111; 0 / 10,642 / 109
device removal none none
  • Commit drops by about 4.4 GiB and dedicated VRAM by about 3.8 GiB, the same in both pairs.
  • fps is +1.0 to +1.6 in each pair, against a spread of 0.1–0.5 between runs with the same setting. On this 16 GB machine the run pages heavily either way, and the switch lowers page-ins by about 15%.
  • Every logged materialization returned 0x00000000 (1920x1080 and 3840x2160 textures, format 61, one mip). Null-binding counts are about the same in both arms. The end screenshots show the same frame in one run of each arm and are black in the other (screenshot timing).
  • Not covered: the CTest fixtures (I ran only the startup runs), runs longer than 250 s, and other adapters.

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.

gpu: defer CreateCommittedResource for untouched read-only slot 133 textures

4 participants