Repository navigation
D3D12.X: scope resource_at by device and clean up on release (#248) - #292
heretic1321 wants to merge 1 commit into
Conversation
86a9207 to
bf8e16c
Compare
|
Retail run of
The access violation at No device removal, and no new warning kinds compared with xcl-smoke, 60 sClaude Code (Claude Opus 5.5) ran the tests and wrote this report. No game files attached. |
|
A data point for the retirement part of this PR, on current RX 9060 XT 16 GB, 32 GB RAM, release,
Pages are shared per address on AI use: Claude Code with Claude Opus 5.5 read the run's log and wrote this comment from my run. |
|
From a static review (no builds or runs) of
Hold a COM reference through descriptor creation and defer GPU retirement until the relevant queue fences complete. xcl/crates/xcl/src/hle/d3d12x/real.rs Lines 2136 to 2149 in bf8e16c xcl/crates/xcl/src/hle/d3d12x/real.rs Lines 2077 to 2095 in bf8e16c Review by Claude Code (Claude Opus 5.5) with a gpt-6.2-sol audit subagent; I checked each point against the code. |
qinrxx
left a comment
There was a problem hiding this comment.
Review of bf8e16c (with 8111cf9 from #269 under it), on correctness and tests only. The diff was read against main 2997c9a.
What I ran: cargo test -p xcl --lib d3d12x:: -- --test-threads=4 on the PR head (base 63b9930): 84 passed, 0 failed, 1 ignored.
- The two new tests pass (
overlapping_placements_retire_old_release_and_teardown,resource_at_cache_retires_cools_caps_and_tears_down). - #269's four pass, including the GPU test
title_textures_at_one_address_share_video_memory(RTX 5080, not skipped). - Not run: on
main, because the PR doesn't merge (below); the workspace suite; the retail title.
0. State against main: this needs more than a rebase.
- #269 was closed, and #288 landed instead with a different design:
vram::Pages, one reserved resource per target, with tiles mapped onto shared 64 KiB pages. mainhas novram::Book,Spaceorplace_title_texture. A merge of this branch intomainconflicts indevice_x.rs,title_textures.rsandvram.rs.main'stitle_texturesalready retires overlapped entries when a newer placement covers their range (retire_range,title_textures.rs:141onmain). TheRegistry/by_endretirement andvram::detach_title_texturehere cover the same ground, built on #269's types.- Not affected:
real.rs(theresource_atcache,dev_release,q_release) andhost.rs, which merge intomainwithout conflicts. - That part could be a small PR of its own against
main, with its unit test. Points 1–3 are about it.
1. Releasing a resource_at resource can leave descriptors pointing at freed memory.
resource_at makes a resource and writes an SRV/UAV for it into the title's descriptor (dev_create_srv_x(this, resource_at(..), &v, cpu)). D3D12 descriptors hold no reference, so MADE is the only thing keeping that resource alive, which is presumably why main never lets go of it. Here it is released 2 s after one of two things:
- retired: a newer placement overlaps the old texture, and
title_texturescallsretire_resource_at(old_res); - evicted:
MADE_MAX(65,536) entries are reached.
The title may still have descriptors over that resource in a heap it reuses, and does not need to make the view again: on the console the view reads the memory, which still exists. The GPU then reads through a descriptor of a destroyed resource. Is there something that shows the title's descriptors over a retired resource are rewritten within the 2 s?
2. The cap evicts the oldest entry made, not the least used.
insert evicts in creation order (order.pop_front()). A view made early and used every frame (a UI atlas, a lookup texture) is the first to go once 65,536 later ones exist. Its next resource_at makes a new resource, but the descriptors written before still point at the old one, the case in point 1. Least-recently-used order would make this rarer, but not safe.
3. Tests. resource_at_cache_retires_cools_caps_and_tears_down checks the bookkeeping with numbers in place of resources, which is fine for the data structure. Nothing covers what points 1 and 2 are about: a view by address still in use after its resource was retired or evicted. A GPU test that makes a view through device #70 / #71, makes 65,537 more (or overlaps the texture), waits past MADE_COOL and samples through the first descriptor would show it. On the debug layer it should report the destroyed resource.
Overlap with our work:
- Our compute change for #232 touches
pso_async.rsonly: no overlap. - #267 adds a field to
D3d12Statsandstats()inreal.rs. This PR'sreal.rschanges are elsewhere in the file. I didn't merge the two together.
AI use: Claude Code (Claude Opus 5.5) built the PR head, ran the tests above, read the diff and wrote this review. I checked each point myself before posting.
|
An 8 GB data point on how much the retirement here could free on the newer retail title (TitleID 7952987A). It's from a page census, not from a run of this branch, since it conflicts with main. Machine: RTX 4060 Laptop 8 GB (7956 MiB), 15.2 GB RAM, Windows 11 26300, driver 621.24. Build: main
Pages are shared per address on main, so retiring an overwritten placement frees only the pages no other placement still holds. If the overwritten textures are among those whose T# is in no view heap, which I'd expect but didn't check, the last row is the most this can free here: about 1.1 GB, and less in practice, since most of it was under 2 s old. On this machine that wouldn't move the end much. The out-of-memory stop comes when local plus non-local video memory fills the card plus Windows' shared GPU memory (#333 (comment)): 14.8 of about 15.7 GB at the refusal. On cards where the pages keep growing well past that, like emirduran707's table above, it may matter much more. When this is rebased onto main, I can measure it here with the budgets logged at the refusal. AI use: Claude Code (Claude Opus 5.5) wrote the census patch and this comment and read the logs; I ran the title. |
Part of xcl-dev#248. Re-scoped onto upstream/main after xcl-dev#288 and xcl-dev#866: drops xcl-dev#269 overlap retirement (covered by xcl-dev#288) and unsafe mid-device MADE eviction (D3D12 descriptors hold no COM reference). Scopes real::MADE by device, returns an owned COM ID3D12Resource from resource_at held across descriptor creation, releases device-owned MADE entries and title_textures state on dev_release (routed through xcl-dev#866 late_release), clears released queues from vram::Pages::waited, and adds title-texture counts to XCL_ACTIVITY. Assisted-by: T3 Code / Antigravity (gemini-pro-orchestrator-neon)
bf8e16c to
e0e3910
Compare
|
Re-scoped cleanly onto Thank you everyone for the thorough reviews and measurements:
What is still needed before marking ready for review: Windows |
Conflicts resolved with upstream's versions where our side held older copies of PRs it has since merged or superseded: - title_textures.rs, vram.rs, device_x.rs: upstream's xcl-dev#248 (ad79932) and xcl-dev#283 replace our earlier merges of xcl-dev#248 / xcl-dev#269 (closed) / xcl-dev#292 (open, conflicts with main now). xcl-dev#242 (R9G9B9E5 targets) is to be merged again on top. - kernelx.rs unmap_away: upstream's condition (also keeps a home the caller committed). - real.rs / host.rs: calls into xcl-dev#292's title_textures::teardown, vram::on_queue_release and title_textures::stats dropped (not in upstream's files); its MADE cache in real.rs stays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Native Windows validation of Tested
Cleanup finding Reproduced independently on the RTX 3090 and AMD integrated Graphics (driver32.0.21030.2001): each targeted test0 passed /1 failed /0 ignored, no skips/timeouts. The failed assertion checks the retained cache entry; fixture cleanup occurs before asserting. A second real-COM-child probe reproduces the same dependency. Patch below adds only diagnostics and intentionally fails. The old cache already retained resources; this finding limits the new cleanup claim. Device scoping and owned lookup results remain useful. An explicit owner/session teardown boundary would need to release cache-owned resources before the final device reference, while preserving descriptor lifetimes. Not tested AI use: Codex (GPT-6) wrote the diagnostics, ran the native tests and prepared this report. No competing runtime fix. Reproducer patch against e0e3910diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs
index ee3e961..d63a538 100644
--- a/crates/xcl/src/hle/d3d12x/real.rs
+++ b/crates/xcl/src/hle/d3d12x/real.rs
@@ -5848,3 +5848,7 @@ mod resource_at_tests {
assert!(c.made.is_empty());
}
}
+
+#[cfg(test)]
+#[path = "resource_lifetime_probe.rs"]
+mod resource_lifetime_probe;
diff --git a/crates/xcl/src/hle/d3d12x/resource_lifetime_probe.rs b/crates/xcl/src/hle/d3d12x/resource_lifetime_probe.rs
new file mode 100644
index 0000000..bbe9052
--- /dev/null
+++ b/crates/xcl/src/hle/d3d12x/resource_lifetime_probe.rs
@@ -0,0 +1,103 @@
+//! Local PR292 diagnostic: real COM children, isolated from the process-wide title device.
+use super::*;
+
+#[test]
+fn native_cached_resource_device_teardown() {
+ unsafe {
+ let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
+ let sel = crate::gpu::adapter::Selector::from_env_or("auto");
+ let Some((adapter, desc)) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() else {
+ return crate::gpu::recomp::runner::skip_test("no GPU");
+ };
+ println!("adapter={}", crate::gpu::adapter::name(&desc));
+ for cached in [false, true] {
+ let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).unwrap();
+ let raw = dev.as_raw();
+ let add: RefFn = std::mem::transmute(*vt(raw).add(1));
+ let release: RefFn = std::mem::transmute(*vt(raw).add(2));
+ add(raw);
+ let before = release(raw);
+ let rd = D3D12_RESOURCE_DESC {
+ Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+ Width: 65536, Height: 1, DepthOrArraySize: 1, MipLevels: 1,
+ SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default()
+ };
+ let mut resource: Option<ID3D12Resource> = None;
+ dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, None, &mut resource).unwrap();
+ let resource = resource.unwrap();
+ add(raw);
+ let with_child = release(raw);
+ // The same adoption/release hooks used for resources held by resource_at.
+ adopt(resource.as_raw(), Kind::Resource);
+ adopt(raw, Kind::Device);
+ assert_eq!(*vt(raw).add(2), dev_release as usize);
+ let key = (raw as usize, 0x10000, [0u8; 0x38]);
+ if cached {
+ MADE.lock().unwrap().get_or_insert_with(ResourceAtCache::default).insert(key, resource.into_raw() as usize);
+ } else {
+ drop(resource);
+ super::super::late_release::drain_known(true);
+ }
+ let raw = dev.into_raw(); // consume the only application-owned device reference
+ let remaining_refs = dev_release(raw);
+ let cache_retained = MADE.lock().unwrap().as_ref().is_some_and(|c| c.get(&key).is_some());
+ println!("cached={cached} device_refs_before_child={before} with_child={with_child} after_application_release={remaining_refs} cache_retained={cache_retained}");
+ // Clean up even when the intended teardown assertion fails; no queued GPU work exists.
+ if cache_retained {
+ teardown_resource_at(raw as usize);
+ super::super::late_release::drain_known(true);
+ }
+ assert!(!cache_retained, "cached resource prevents the device Release==0 cleanup from running");
+ if !cached { assert_eq!(remaining_refs, 0, "uncached control must reach the release hook"); }
+ }
+ }
+}
+
+/// The production cache entry point, using its committed-buffer fallback outside the UMA.
+/// This does not invoke a retail texture descriptor or submit GPU work.
+#[test]
+fn resource_at_device_teardown_path() {
+ unsafe {
+ let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
+ let sel = crate::gpu::adapter::Selector::from_env_or("auto");
+ let Some((adapter, desc)) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() else {
+ return crate::gpu::recomp::runner::skip_test("no GPU");
+ };
+ println!("adapter={}", crate::gpu::adapter::name(&desc));
+ let mut rd = [0u8; 0x38];
+ rd[0..4].copy_from_slice(&1u32.to_le_bytes()); // BUFFER
+ rd[16..24].copy_from_slice(&65536u64.to_le_bytes());
+ rd[24..28].copy_from_slice(&1u32.to_le_bytes());
+ rd[28..30].copy_from_slice(&1u16.to_le_bytes());
+ rd[30..32].copy_from_slice(&1u16.to_le_bytes());
+ rd[36..40].copy_from_slice(&1u32.to_le_bytes()); // sample count
+ rd[44..48].copy_from_slice(&1u32.to_le_bytes()); // ROW_MAJOR
+ for explicit_teardown in [true, false] {
+ let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).unwrap();
+ let raw = dev.as_raw();
+ adopt(raw, Kind::Device);
+ let first = resource_at(raw, rd.as_ptr(), 0x10000).expect("production cache miss creates a native resource");
+ let hit = resource_at(raw, rd.as_ptr(), 0x10000).expect("production cache hit returns an owned reference");
+ assert_eq!(first.as_raw(), hit.as_raw());
+ let key = (raw as usize, 0x10000, rd);
+ assert!(MADE.lock().unwrap().as_ref().is_some_and(|c| c.get(&key) == Some(first.as_raw() as usize)));
+ drop(first);
+ drop(hit);
+ if explicit_teardown {
+ teardown_resource_at(raw as usize);
+ super::super::late_release::drain_known(true);
+ }
+ let raw = dev.into_raw();
+ let remaining_refs = dev_release(raw);
+ let cache_retained = MADE.lock().unwrap().as_ref().is_some_and(|c| c.get(&key).is_some());
+ println!("resource_at explicit_teardown={explicit_teardown} after_application_release={remaining_refs} cache_retained={cache_retained}");
+ if cache_retained {
+ teardown_resource_at(raw as usize);
+ super::super::late_release::drain_known(true);
+ }
+ assert!(!cache_retained, "production resource_at cache still owns its resource after application device release");
+ if explicit_teardown { assert_eq!(remaining_refs, 0, "explicit teardown control releases the device"); }
+ }
+ }
+}Run each probe in its own process with Follow-up on the requested @heretic1321 I fetched the named commit directly from your fork: The fetched8eb tree differs from the described fix:
Please push/link the revision containing the intended release-hook change, its helpers and module declaration. I can then run the focused native checks and, if appropriate, the suite. Before accepting a count threshold, it also needs cases with more than one cached child and retained descriptor/device owners; the one-child probe alone does not establish descriptor lifetime safety. One scope correction: these are two adapters in one Windows machine. We have no retail files here, so neither these filters nor a full workspace run can supply the required AI use: Codex (GPT-6) inspected the exact Git objects and ran the Windows discovery/compile diagnostics. No runtime fix was fabricated from the prose description. |
|
@WebIdentity1 thank you — the full-suite counts, the four skips and the same pre-existing integer-CLAMP failure on both revisions make this the most useful run on the PR, and the teardown finding is correct: I reproduced the mechanism from the code ( Fixed on
Since you have the hardware and I don't: could you run the same two filters on |
|
Regression run of Against the limits in CONTRIBUTING.md: 100 % of AMD Radeon RX 9070 (RDNA4, driver 32.0.32029.2010), Ryzen 7 7800X3D, 32 GB, Windows 11 build 26300, Rust 1.100.0, AI use: Claude Code (Claude Opus 5.5) built both trees and ran |
Re-scoped onto
upstream/main(47efa2e, head8eb79c2), kept as draft. Part of #248.Re-scope after #288, #866, and review feedback
#269base andtitle_texturesoverlap-retirement:#288landed onmainusingvram::Pagesand already includesshadowed/retire_overlapping/unmap_superseded. Addressing live non-overlapping texture growth (@emirduran707's 9.8 GB RX 9060 XT table /@albertoglvn's 8 GB census) belongs to opt-in page budgets such as#640, not overlap retirement.MADE_MAX/ 2 sMADE_COOLeviction: per@qinrxx(points 1–2) and@Cattn, D3D12 descriptors hold no COM reference, so dropping aMADEresource while descriptors may still exist in reused heaps is unsafe.What is in it
crates/xcl/src/hle/d3d12x/real.rs:ResourceAtCachekeysMADEby(device, va, desc)(previously(va, desc)).resource_atreturns an ownedOption<ID3D12Resource>cloned while holding theMADElock sodev_create_srv_at_x/dev_create_uav_at_xhold a live COM reference through descriptor creation (@Cattn's lifetime fix).ID3D12Device::Release(dev_release). A cached resource is a COM child and holds the device, so theReleaseof the last outside reference returns 1 and a teardown placed after that call never runs (@WebIdentity1reproduced this on two machines). The hook therefore tears the device'sMADEentries down first when at most this caller's andreal::init's process-lifetime reference remain (routing finalID3D12Resource::Releasethrough#866'slate_releasewhile upload queues remain registered), thentitle_texturesstate for that device, and the device really reaches zero.vram::on_queue_releasefromq_release.resource_at_tests::resource_at_cache_scopes_by_device_and_tears_down(holdsgating, per-device isolation, idempotent teardown).crates/xcl/src/hle/d3d12x/resource_lifetime_probe.rs: two on-device regression tests adapted from@WebIdentity1's reproducer — a raw COM-child teardown control and the productionresource_atmiss/hit/teardown path — both assert the cache is empty and the device reached 0. They skip without a GPU.crates/xcl/src/hle/d3d12x/vram.rs:on_queue_release(queue)clearing released queues from every device'spages.waitedmap so reused queue pointers cannot skip mapping-fence waits.crates/xcl/src/hle/d3d12x/title_textures.rs:Table::teardown/teardown(device)removing entries for a released device fromby_res/by_va/shadowed/shadowed_by_va/LAST_CONTENT/QUEUES/WATCH_CACHE.Statsandstats()(active,shadowed,covered_bytes), plus unit testtable_teardown_and_stats_are_scoped_by_device.crates/xcl/src/host.rs:; title textures {} ({} MB covered, {} shadowed)on theXCL_ACTIVITYmemory:line.Tested
1.98.1, head8eb79c2onupstream/main47efa2e:AR_x86_64_pc_windows_msvc=llvm-ar cargo check --release --workspace --target x86_64-pc-windows-msvc— exit 0 (15.12s, 0 errors, 0 warnings).AR_x86_64_pc_windows_msvc=llvm-ar cargo check --tests --workspace --target x86_64-pc-windows-msvc— exit 0 (8.95s, 0 errors, 0 warnings).python3 scripts/pr_check.py --localverified all required sections and asset/model checks (failing only on the missing Windowsxcl-smokeblocks for8eb79c2).@WebIdentity1one0e3910— RTX 3090 driver 591.74, Windows 10 19045, Ryzen 7 7800X3D, Rust 1.98.1 MSVC, DXC 1.8.2502.11:cargo build --locked --workspacesucceeds onmainand the head; full suite720 passed / 1 failed / 41 ignoredon the head against718 passed / 1 failed / 41 ignoredonmain(same pre-existing integer-CLAMP failure on both, four explicit skips each, the two added PR tests pass). Their cache-teardown finding reproduced on the RTX 3090 and on AMD integrated graphics; it is addressed by the release-hook change below.bf8e16c(@grahamster2RTX 3080,@qinrxxd3d12x::tests) were on the#269-stacked version and do not cover this re-scoped commit8eb79c2.Regression run
8eb79c2(draft; no Windows GPU host here).Not tested
cargo test --workspaceexecution, GPU tests,scripts/smoke.ps1/ retail title runs on8eb79c2, and multi-device teardown in a real title. Both new probe tests and@WebIdentity1's numbers are one0e3910; the release-hook fix and the probes have not been run on a GPU yet.AI use
T3 Code / Antigravity, Orchestrator (Neon) / gemini-pro-orchestrator-neon: re-scoped ontoupstream/main(47efa2e), fixedresource_atowned COM reference return and removed unsafe mid-device eviction per reviews, updatedvram::on_queue_releasefor#288's per-devicePAGESmap, added unit tests, and ran Linuxcargo checkandscripts/pr_check.py --local.Rebase note (
47efa2e)main(wait_budget,resolve_within(&Pending, …),Pending::late) from theXCL_PSO_WAIT_MSwork. Instead of keeping a second copy,resolve_for_drawnow builds onmain'sresolve_within/wait_budget: this branch keeps the draw-specific 4 s default, the compute bypass, thestandin_drawscounter and the long-wait log, and drops the duplicated wait loop.main'sreal.rs/title_textures.rs/vram.rs/host.rsand dropped this branch's half of the PR; it is restored in8eb79c2, which is why the device-scoping and teardown work is back in the diff.cargo check --release --workspaceand--testsforx86_64-pc-windows-msvcon head8eb79c2: 0 errors, 0 warnings.