Skip to content

D3D12.X: forget a command list before the runtime frees it - #2691

Open
SergeAx wants to merge 1 commit into
xcl-dev:mainfrom
SergeAx:d3d12x-forget-lists-before-release
Open

SergeAx wants to merge 1 commit into
xcl-dev:mainfrom
SergeAx:d3d12x-forget-lists-before-release

Conversation

@SergeAx

@SergeAx SergeAx commented Nov 26, 2026 •

Copy link
Copy Markdown

Fixes #2690.

real::cl_release dropped what XCL keeps by a command list's address only after the runtime's final Release had freed the list, so a list created on another thread in between could get the address and lose its bind state, allocator, last submit and DRED marks. As res_release and #2422 do, the last reference (AddRef returns 2) now forgets the list first. When two last-but-one releases race, both miss it and the list is forgotten after its release, as before.

What is in it

  • crates/xcl/src/hle/d3d12x/real.rs: cl_release forgets the list before the runtime's final Release (forget_command_list).
  • crates/xcl/src/hle/d3d12x/real.rs (list_release_tests): a_new_list_at_a_released_lists_address_keeps_its_state, a fake list whose Release hands its address to a new list at once.

Tested

Regression run

main:

xcl-smoke v1
commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7
gpu: NVIDIA GeForce RTX 5080
title: 3c290c16
seconds: 60
exit: 0x0
frames shown: 1400 (PresentX 1401)
presents per 2 s (last 3): 60 52 47
device removals: 0
crashes: 0
peak commit: 18229 MB

this PR:

xcl-smoke v1
commit: 008fc9618549088436a454a2247bfd4d62aeb5cc
gpu: NVIDIA GeForce RTX 5080
title: 3c290c16
seconds: 60
exit: 0x0
frames shown: 1445 (PresentX 1445)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15653 MB

Not tested

AI use

  • Claude Code (Claude Opus 5.5) found the cause, wrote the change and the test, ran the tests and measurements, and wrote this description.

cl_release dropped what XCL keeps by a PC command list's address
(list_x::on_release, bind::forget, dred::forget_list) only after the
runtime's final Release had freed the list, so a list created on
another thread in between could get the address and lose its bind
state, allocator, last submit and DRED marks. As in res_release and
xcl-dev#2422, the last reference (AddRef returns 2) now forgets the list
first.

A fake list whose Release hands its address to a new list at once
loses the new list's state on main. The parallel flake
a_dispatch_with_a_pipeline_still_building_waits_at_the_submit failed
13/200 on main and 6/200 with this change alone; xcl-dev#1453 closes the
longer window in title_list::release (0/400).
@SlopTart

SlopTart commented Nov 26, 2026 •

Copy link
Copy Markdown

Tested on the Linux/Wine lane, full standard env (AMD rig: Ryzen 9 9900X, 96 GB DDR5, RX 7900 XT 20 GB, Arch kernel 7.2.15, Mesa 26.2.5 RADV, wine-11.0 Proton, rustc 1.94.0; d3d12,d3d12core,dxgi,d3d11,d3d10core=n,b overrides, official DXC kit, VKD3D_CONFIG=ignore_shared_fence, threads=2), head 008fc961, mergeable against main b49be183:
non-gpu suite (--skip gpu::): 597 passed, 3 failed, 4 ignored, 733 filtered.
The failure set is identical to bare main b49be183 measured on the same rig the same day (596 passed, 3 failed): gpu_promoted_uav_clear (our #2490), xma2_source_voice (#2481, vendored-FAudio gate). The third red, the sparse tile video-memory test, is a known batch flake (green solo).
Zero delta from this PR; every test it adds passes inside the suite.
Not tested: gpu suite, Windows native.
Correction: an earlier version of this row reported three extra reds; those runs lacked the d3d12,d3d12core=n,b DLL overrides and hit stub-DLL NOTIMPL artifacts. Re-ran with the standard env, artifacts gone.
AI use: Hermes agent (local Qwen-class) ran the tests and drafted this; I checked it before posting.

@luckyteagirl

Copy link
Copy Markdown
Contributor

RX 6800M verification at exact PR head 008fc9618549088436a454a2247bfd4d62aeb5cc against current main b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7 (Windows 11, AMD driver 30.0.13002.13003, Rust 1.99.0 MSVC):

  • cargo test --locked -p xcl --lib -j 1 hle::d3d12x::real::list_release_tests::a_new_list_at_a_released_lists_address_keeps_its_state -- --exact --test-threads=1 --nocapture: 1 passed, 0 failed, 0 ignored, 1,336 filtered. This is the synthetic pointer-reuse fixture.
  • cargo build --locked --release -p xcl -j 1: passed; head executable SHA-256 D81895D827BCDFEEAB5C971FAADC03D381C521690D74C7C40E36AFC948BD8F81.
  • Paired guarded release smoke with scripts/smoke.ps1 -Seconds 12, XCL_ADAPTER=6800M, and separate data/DXIL cache directories, on the same locally owned title build (hash 2ef5fd64):
Main b49be183 PR 008fc961
Exit 0x0 0x0
Frames shown / PresentX 147 / 147 153 / 153
Last three 2-second present windows 27, 60, 60 33, 60, 60
Device removals / crashes 0 / 0 0 / 0
Peak commit 7,512 MB 7,499 MB

I attempted a longer 60-second clean-main control. A separate low-memory monitor stopped that control after about 22 seconds when available commit fell to 1,015 MB, so there is no comparable 60-second result. These short runs show startup and presentation; they do not trigger the command-list address-reuse race or establish world-load/performance behavior. I did not run the full workspace suite on this head. AI-assisted test report with Codex.

sage-sage added a commit to sage-sage/xcl that referenced this pull request Nov 26, 2026
…ease

`heap_release`, `mem_heap_release`, `q_release` and `alloc_release`
called the driver's Release first and, when it returned 0, removed what
XCL keeps by the object's address. Once the driver has freed the object,
another thread can create a new one at the same address and record its
own entries; the cleanup then removes those. For an ID3D12Heap that is
worse than lost bookkeeping: `mem_heap_release` takes the new heap's
`HEAP_UMA` entry and frees its block of unified memory while the new
heap's buffers live in it. A descriptor heap loses its console slots, a
queue or an allocator its list_x / alloc_pool entries.

`release_taking_first` takes a reference first; when AddRef returns 2
the caller holds the last one, so the entries are removed while the
address is still this object's, and what must outlive the object (the
heap's memory block, a descriptor heap's slots and shadow) is freed
after the last Release, as before. `console_heap::unregister` is split
into `take` and `free` for that.

The command list and pipeline releases have the same order; xcl-dev#2691,
xcl-dev#1453 and xcl-dev#2422 change those (xcl-dev#2690).

Assisted-by: Claude Code (Claude Opus 5.5)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sage-sage

Copy link
Copy Markdown

Test report: passes on NVIDIA, and with #1453 the dispatch flake from #2690 did not show in 300 parallel runs. Exact head 008fc961 (its base is current main b49be18, so head = merged).

Tested

Not tested

Claude Code (Claude Opus 5.5) ran the tests and wrote this report.

sage-sage added a commit to sage-sage/xcl that referenced this pull request Nov 26, 2026
…ease

`heap_release`, `mem_heap_release`, `q_release` and `alloc_release`
called the driver's Release first and, when it returned 0, removed what
XCL keeps by the object's address. Once the driver has freed the object,
another thread can create a new one at the same address and record its
own entries; the cleanup then removes those. For an ID3D12Heap that is
worse than lost bookkeeping: `mem_heap_release` takes the new heap's
`HEAP_UMA` entry and frees its block of unified memory while the new
heap's buffers live in it. A descriptor heap loses its console slots, a
queue or an allocator its list_x / alloc_pool entries.

`release_taking_first` takes a reference first; when AddRef returns 2
the caller holds the last one, so the entries are removed while the
address is still this object's, and what must outlive the object (the
heap's memory block, a descriptor heap's slots and shadow) is freed
after the last Release, as before. Two last-but-one releases at once
both miss `AddRef == 2`; the one whose Release ends at 0 then takes the
entries after the object is gone, as before this change, so nothing is
left behind. `console_heap::unregister` is split into `take` and `free`.

The command list and pipeline releases have the same order; xcl-dev#2691,
xcl-dev#1453 and xcl-dev#2422 change those (xcl-dev#2690).

Assisted-by: Claude Code (Claude Opus 5.5)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
rootw0rm pushed a commit to rootw0rm/xcl that referenced this pull request Nov 26, 2026
…(port upstream xcl-dev#2520 + xcl-dev#2691)

(cherry picked from commit 87b65e230fd1e87fda0839146a41c2bca2420fb3)
@KDenKC

KDenKC commented Nov 26, 2026

Copy link
Copy Markdown

A data point from our AMD iGPU (RDNA2), list_x with --test-threads=4. The flaky a_dispatch_with_a_pipeline_still_building_waits_at_the_submit (stand-in lost, 0x0 skipped) failed 3 of 5 runs on main, 3 of 11 with this PR alone, 0 of 50 with #1453, and 0 of 50 with both. So on this fixture the remaining failures come from the title_list path #1453 fixes. The two merge cleanly together. Details are in #1453: #1453

AI use: Claude Code (Claude Opus 5.5) ran the arms and wrote this.

KDenKC added a commit to KDenKC/xcl that referenced this pull request Nov 26, 2026
Apply thehollowedone's patch and reference-count regression from xcl-dev#2622 comment 7187891221. A list whose Close failed cannot be reset, so release it rather than losing its owner on later spare reuse, and clear its dispatch-chain predecessor.

Adjust the suggested initial-refusal Release call to use the adopted vtable too: cl_release must clean address-keyed state instead of bypassing it through orig_fn. This is the same lifecycle class discussed in xcl-dev#1453 and xcl-dev#2691.

Assisted-by: Codex (GPT-6.1-Sol)
bmjask pushed a commit to bmjask/xcl that referenced this pull request Nov 26, 2026
A cell recorded and never submitted (xcl-dev#1452: rec 0x619, sub 0x0@qNone)
did not say which list recorded the value or what became of that list.
Each cell now keeps the PC list and time of the recording that set its
recorded_max, and each list that recorded a Write64 keeps its last
execute, Reset and Release (signal_write64_fences, the KickoffX submit,
reset_pc, clear_segment_state, on_release). The cell entry in
cells_behind_summary prints them as their time after the recording, or
"no": reset or released with no execute is a recording thrown away
(xcl-dev#2691's address reuse shows as a release), executed is a miss on the
submit side, and none of the three a list the title still holds.

Part of xcl-dev#1452.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@SergeAx
SergeAx marked this pull request as ready for review November 26, 2026 12:28
bmjask pushed a commit to bmjask/xcl that referenced this pull request Nov 26, 2026
A cell recorded and never submitted (xcl-dev#1452: rec 0x619, sub 0x0@qNone)
did not say which list recorded the value or what became of that list.
Each cell now keeps the PC list and time of the recording that set its
recorded_max, and each list that recorded a Write64 keeps its last
execute, Reset and Release (signal_write64_fences, the KickoffX submit,
reset_pc, clear_segment_state, on_release). The cell entry in
cells_behind_summary prints them as their time after the recording, or
"no": reset or released with no execute is a recording thrown away
(xcl-dev#2691's address reuse shows as a release), executed is a miss on the
submit side, and none of the three a list the title still holds.

Part of xcl-dev#1452.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@KDenKC

KDenKC commented Nov 26, 2026

Copy link
Copy Markdown

@SergeAx a small suggestion for the concurrent-release case that the description leaves open, in case it is useful.

On 008fc961, two releases that race can both miss the last-reference probe and take the late cleanup path. That path removes bind::STATES by address after the native Release, so it can remove the state of a new list that already reuses the address. The patch below:

  • takes a generation for the entry before the final native Release;
  • afterwards removes the entry only if its generation still matches, under the same lock;
  • gives creation/reset and split inheritance fresh generations, so an absent old entry never authorizes deleting a new one.

Scope is the binding state only. LISTS, allocator associations and DRED keep this PR's cleanup.

Test: a GPU-free fake final release that checks a replacement at the same address, an absent old entry, and ordinary final cleanup. On 008fc961 it fails (the replacement's state is erased); with the patch both release tests pass (2/2). About 70 changed lines on 008fc961.

Not tested: a full suite or a title run with the patch.

patch on 008fc96
diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs
index 3f31c48b..ab4b3753 100644
--- a/crates/xcl/src/hle/d3d12x/bind.rs
+++ b/crates/xcl/src/hle/d3d12x/bind.rs
@@ -20,6 +20,7 @@ use super::console_list::{self, Layout, Param};
 
 #[derive(Default)]
 struct State {
+    generation: u64,
     layout: Option<Arc<Layout>>,
     args: Vec<u8>,
     /// the graphics root signature's layout and arguments
@@ -38,6 +39,11 @@ struct State {
 
 static STATES: Mutex<Option<HashMap<usize, State>>> = Mutex::new(None);
 
+fn next_generation() -> u64 {
+    static NEXT: AtomicU64 = AtomicU64::new(1);
+    NEXT.fetch_add(1, Ordering::Relaxed)
+}
+
 /// draws / dispatches of console code: with a translated pipeline, skipped, with a PC one
 static COUNTS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
 
@@ -66,7 +72,8 @@ fn count(k: usize) {
 }
 
 fn with<R>(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R {
-    f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default())
+    f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize)
+        .or_insert_with(|| State { generation: next_generation(), ..Default::default() }))
 }
 
 /// The list was created or reset onto `allocator` with `initial_pso`: the previous
@@ -74,6 +81,7 @@ fn with<R>(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R {
 /// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics.
 pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) {
     let (old, blocks) = with(list, |s| {
+        s.generation = next_generation();
         let old = std::mem::replace(&mut s.allocator, allocator);
         s.arena = Default::default();
         s.pso = initial_pso;
@@ -108,6 +116,7 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u
         (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso)
     });
     let (old, blocks) = with(to, |s| {
+        s.generation = next_generation();
         let old = std::mem::replace(&mut s.allocator, allocator);
         s.arena = Default::default();
         s.layout = layout;
@@ -139,7 +148,28 @@ pub(super) fn pass_arena(from: *mut c_void, to: *mut c_void) {
 
 /// The list is gone.
 pub(super) fn forget(list: *mut c_void) {
-    if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) {
+    forget_if(list, |_| true);
+}
+
+pub(super) fn generation(list: *mut c_void) -> Option<u64> {
+    STATES.lock().unwrap().as_ref()?.get(&(list as usize)).map(|s| s.generation)
+}
+
+pub(super) fn forget_generation(list: *mut c_void, generation: Option<u64>) {
+    if let Some(generation) = generation {
+        forget_if(list, |s| s.generation == generation);
+    }
+}
+
+fn forget_if(list: *mut c_void, matches: impl FnOnce(&State) -> bool) {
+    let old = {
+        use std::collections::hash_map::Entry;
+        match STATES.lock().unwrap().as_mut().map(|m| m.entry(list as usize)) {
+            Some(Entry::Occupied(e)) if matches(e.get()) => Some(e.remove()),
+            _ => None,
+        }
+    };
+    if let Some(s) = old {
         console_list::hold_until_reset(s.allocator, s.uma);
     }
 }
diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs
index ae390356..a3ac3bbe 100644
--- a/crates/xcl/src/hle/d3d12x/real.rs
+++ b/crates/xcl/src/hle/d3d12x/real.rs
@@ -7006,7 +7006,7 @@ unsafe extern "system" fn cl_execute_indirect(
 
 /// The last reference: what XCL keeps by the list's address goes before the runtime frees it,
 /// as a list created on another thread can get the address at once. (Two last-but-one releases
-/// at once miss each other here; the list's state then goes after it, as before.)
+/// at once miss each other here; check the binding generation in that fallback.)
 unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 {
     let add: RefFn = std::mem::transmute(orig_fn(this, 1));
     let f: RefFn = std::mem::transmute(orig_fn(this, 2));
@@ -7015,9 +7015,12 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 {
     if last {
         forget_command_list(this);
     }
+    let generation = if last { None } else { super::bind::generation(this) };
     let n = f(this);
     if n == 0 && !last {
-        forget_command_list(this);
+        super::list_x::on_release(this as usize);
+        super::bind::forget_generation(this, generation);
+        super::dred::forget_list(this);
     }
     n
 }
@@ -8997,6 +9000,8 @@ mod list_release_tests {
     struct FakeList {
         vtable: usize,
         refs: u32,
+        concurrent_release: bool,
+        recycle: bool,
     }
 
     const ALLOC: usize = 0x7E57_A130;
@@ -9012,7 +9017,11 @@ mod list_release_tests {
     unsafe extern "system" fn release(this: *mut c_void) -> u32 {
         let l = &mut *(this as *mut FakeList);
         l.refs -= 1;
-        if l.refs == 0 {
+        if std::mem::take(&mut l.concurrent_release) {
+            // The probe observed two references. The other owner releases while it unwinds.
+            l.refs -= 1;
+        }
+        if l.refs == 0 && l.recycle {
             super::super::bind::reset(this, ALLOC, PSO);
             super::super::alloc_pool::created_on(this as usize, ALLOC, 0);
         }
@@ -9023,7 +9032,7 @@ mod list_release_tests {
     fn a_new_list_at_a_released_lists_address_keeps_its_state() {
         let pc = [0, add_ref as usize, release as usize];
         let ext = [pc.as_ptr() as usize, 0];
-        let mut list = FakeList { vtable: ext.as_ptr() as usize + 8, refs: 2 };
+        let mut list = FakeList { vtable: ext.as_ptr() as usize + 8, refs: 2, concurrent_release: false, recycle: true };
         let this = &mut list as *mut FakeList as *mut c_void;
         super::super::bind::reset(this, ALLOC + 0x10, PSO + 0x10);
         let (kept, n) = unsafe {
@@ -9039,5 +9048,24 @@ mod list_release_tests {
         assert_eq!(pso, PSO, "the new list's bind state");
         assert_eq!(backing, Some(ALLOC), "the new list's allocator");
     }
+
+    #[test]
+    fn concurrent_final_release_only_forgets_its_bind_generation() {
+        let pc = [0, add_ref as usize, release as usize];
+        let ext = [pc.as_ptr() as usize, 0];
+        for (seed, recycle) in [(true, true), (false, true), (true, false)] {
+            let mut list = FakeList { vtable: ext.as_ptr() as usize + 8, refs: 2, concurrent_release: true, recycle };
+            let this = &mut list as *mut FakeList as *mut c_void;
+            if seed {
+                super::super::bind::reset(this, ALLOC + 0x10, PSO + 0x10);
+            }
+            let n = unsafe { cl_release(this) };
+            let pso = super::super::bind::tracked_pso(this);
+            super::super::bind::forget(this);
+            super::super::alloc_pool::forget_list(this as usize);
+            assert_eq!(n, 0);
+            assert_eq!(pso, if recycle { PSO } else { 0 }, "bind state after concurrent last release (seed={seed}, recycle={recycle})");
+        }
+    }
 }

AI use: Codex (GPT-6.2-Sol) wrote the patch and test and ran them. Claude Code (Claude Opus 5.5) reviewed it and wrote this.

@SergeAx

SergeAx commented Nov 26, 2026

Copy link
Copy Markdown
Author

@KDenKC thanks, the generation check is right for what it covers. I read it against 008fc961: every place that starts a list's bind state (reset, inherit_for_split and the first insert in with) takes a fresh generation, so a list made at the address in the window keeps its state.

I'd still keep it out of this PR:

  • It closes the concurrent window for bind::STATES only. The same late path also drops the list's alloc_pool entries (through list_x::on_release) and its DRED marks by address. A fix of that window should guard all three the same way, and that is a second change, of about the same size again.
  • This PR fixes the window its test reproduces, the single last release, and the description says the concurrent case stays as before.
  • The concurrent window needs two owners releasing the same list at once, and a new list made at the freed address before the late cleanup. Nothing here has shown it yet.

If you want to take it on, a follow-up PR stacked on this one, with your test and the guard for all three, is the way I'd go; I'd test it here.

AI use: Claude Code (Claude Opus 5.5) checked the patch against the code and wrote this reply.

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.

D3D12.X: a command list is forgotten after the runtime frees it, so a new list at its address can lose its state

5 participants