From f6cb6e7a903b9280853dfd164e2b68585cc467eb Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:08:24 +0000 Subject: [PATCH 1/2] e2e: a same-list wait on title memory follows the CPU-done write console_list_methods records Write32BitValueBottomOfPipeX to an ordinary title allocation outside graphics memory, then Wait32BitValueX on the same cell, and submits it by ExecuteCommandLists and by KickoffX. The CPU does that write after the GPU segment, so the wait can only be met after the producer segment has run and its deferred store has landed. Without that ordering the wait is checked before the list is submitted and times out (2 s) before the list runs; the test fails above 1 s. Co-Authored-By: Claude Opus 5.5 --- tests/testtitle/src/gpu.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index 238ed482cf..3e593ddbe7 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -581,6 +581,41 @@ pub fn console_list_methods() -> Result<(), String> { ensure!(r32(0x300) == 0xDEAD_00AA && r64(0x308) == 0x0000_0003_0000_0000, "wait cells not written"); ensure!(r32(0x310) == 0x55AA_55AA, "post-Wait32/64 write failed ({:#x})", r32(0x310)); + // 4. Same-list write-then-wait on ordinary title memory (outside graphics memory), where the + // CPU does the write after the GPU: the wait must follow that store, not the submission + // (otherwise it times out before the write is even submitted), by Execute and by KickoffX. + use std::sync::atomic::{AtomicU32, Ordering}; + let cells = Box::new([AtomicU32::new(0), AtomicU32::new(0)]); + let cell = |i: usize| &cells[i] as *const AtomicU32 as u64; + alloc.Reset().map_err(e)?; + list.Reset(&alloc, None).map_err(e)?; + write32_bottom(l, cell(0), 0x0BAD_F00D, 0, 0); + wait32(l, cell(0), 3, 0x0BAD_F00D, u32::MAX, 0); + write32_bottom(l, at(0x318), 0x6666_7777, 0, 0); + list.Close().map_err(e)?; + let t0 = std::time::Instant::now(); + queue.ExecuteCommandLists(&[Some(list.cast::().map_err(e)?)]); + wait(&queue, &fence, 4)?; + let took = t0.elapsed(); + let c0 = cells[0].load(Ordering::Acquire); + ensure!(c0 == 0x0BAD_F00D && r32(0x318) == 0x6666_7777, "write-then-wait on title memory ({c0:#x}, {:#x})", r32(0x318)); + ensure!(took < std::time::Duration::from_secs(1), "Execute: wait after a CPU-done write in the same list took {took:?}"); + + alloc.Reset().map_err(e)?; + list.Reset(&alloc, None).map_err(e)?; + write32_bottom(l, cell(1), 0x0DEF_ACED, 0, 0); + wait32(l, cell(1), 3, 0x0DEF_ACED, u32::MAX, 0); + write32_bottom(l, at(0x31C), 0x7777_8888, 0, 0); + let t0 = std::time::Instant::now(); + kickoff(l); + list.Close().map_err(e)?; + queue.ExecuteCommandLists(&[Some(list.cast::().map_err(e)?)]); + wait(&queue, &fence, 5)?; + let took = t0.elapsed(); + let c1 = cells[1].load(Ordering::Acquire); + ensure!(c1 == 0x0DEF_ACED && r32(0x31C) == 0x7777_8888, "write-then-wait on title memory by KickoffX ({c1:#x}, {:#x})", r32(0x31C)); + ensure!(took < std::time::Duration::from_secs(1), "KickoffX: wait after a CPU-done write in the same list took {took:?}"); + crate::XMemFree(mem as *mut c_void, graphics); Ok(()) } From e638c3497598d81d6bccf32dbf015a7dad384acc Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:15:46 +0000 Subject: [PATCH 2/2] D3D12.X: a CPU-write receipt says whether the GPU got to its submission The receipt a wait after a deferred CPU write waits for (#3035) was sent whenever the worker had done the stores, also after it gave up on the fence after WAIT_MS (10 s) and wrote anyway; a job that never reached the worker (no fence, a failed Signal, no thread) had no receipt at all, the same as no deferred work; and both callers dropped the result. - The worker sends whether the fence got to the job's value. It rechecks the fence after every wake until its deadline: the one auto-reset event can also be set by an earlier job's value registered before that job gave up, which ended the next job's wait at once. - A nonempty job asked for a receipt always has one; a job dropped before the worker has it drops its sender, and the receipt reads as failed. - ExecuteCommandLists and KickoffX log an unconfirmed receipt and go on to the wait as before: the continuation is on the same queue, so the GPU still runs it after the producer, and a wait the store did not satisfy times out in wait_all_on. Holding the continuation for ever would turn a lost producer into a hang. Reported by pickles976 and Royalflamejlh on #3035. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/cpu_writes.rs | 113 +++++++++++++++++++----- crates/xcl/src/hle/d3d12x/list_x.rs | 69 +++++++++++++-- 2 files changed, 153 insertions(+), 29 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index f672e42f0a..cc29b05db4 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -34,7 +34,10 @@ struct Job { fence: ID3D12Fence, value: u64, writes: Vec, - done: Option>, + /// how long the worker waits for `value` before writing anyway (`WAIT_MS`) + wait_ms: u32, + /// told whether the queue got to `value` before the writes were done + done: Option>, } // SAFETY: the fence is a free-threaded COM object; the writes are plain data @@ -71,13 +74,27 @@ fn worker() -> &'static Mutex> { let spawned = std::thread::Builder::new().name("xcl-cpu-writes".into()).spawn(move || unsafe { let event = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()); for job in rx { - if super::real::fence_completed(&job.fence) < job.value && job.fence.SetEventOnCompletion(job.value, HANDLE(event as *mut c_void)).is_ok() { - th::WaitForSingleObject(event, WAIT_MS); - if super::real::fence_completed(&job.fence) < job.value { + let mut reached = super::real::fence_completed(&job.fence) >= job.value; + if !reached && job.fence.SetEventOnCompletion(job.value, HANDLE(event as *mut c_void)).is_ok() { + // the event can also be set by an earlier job's value, registered before + // that job gave up: the fence is checked again until the time is up + let deadline = std::time::Instant::now() + std::time::Duration::from_millis(job.wait_ms.into()); + loop { + let left = deadline.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + break; + } + th::WaitForSingleObject(event, left.as_millis().max(1) as u32); + reached = super::real::fence_completed(&job.fence) >= job.value; + if reached { + break; + } + } + if !reached { static LATE: AtomicU64 = AtomicU64::new(0); let k = LATE.fetch_add(1, Ordering::Relaxed) + 1; if k.is_power_of_two() { - crate::xlog_warn!("D3D12.X: {k} writes after the GPU so far done although their queue had not got there after {WAIT_MS} ms (fence at {}, wanted {}; {} writes)", super::real::fence_completed(&job.fence), job.value, job.writes.len()); + crate::xlog_warn!("D3D12.X: {k} writes after the GPU so far done although their queue had not got there after {} ms (fence at {}, wanted {}; {} writes)", job.wait_ms, super::real::fence_completed(&job.fence), job.value, job.writes.len()); } } } @@ -91,7 +108,7 @@ fn worker() -> &'static Mutex> { } } if let Some(done) = job.done { - let _ = done.send(()); + let _ = done.send(reached); } } }); @@ -224,33 +241,46 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { } /// Receipt published only after the worker has applied every deferred store in a submission. -pub(super) struct Completion(mpsc::Receiver<()>); +pub(super) struct Completion(mpsc::Receiver); impl Completion { + /// Whether the stores were done after the GPU had finished their submission. False when the + /// worker wrote anyway after `WAIT_MS` (a removed device, a queue that never got there) and + /// when the job never reached the worker (no fence, a failed `Signal`, no worker thread). pub(super) fn wait(self) -> bool { let _stall = crate::stall::span(crate::stall::StallKind::MemorySynchronization); - self.0.recv().is_ok() + self.0.recv().unwrap_or(false) } } #[cfg(test)] -pub(super) fn completion_pair_for_test() -> (Completion, mpsc::Sender<()>) { +pub(super) fn completion_pair_for_test() -> (Completion, mpsc::Sender) { let (tx, rx) = mpsc::channel(); (Completion(rx), tx) } -/// Schedule `writes` from lists just submitted to `queue` after the GPU has finished them. -unsafe fn schedule(queue: *mut c_void, writes: Vec, completion: bool) -> Option { - if writes.is_empty() || queue.is_null() { +/// Schedule `writes` from lists just submitted to `queue` after the GPU has finished them. With +/// `completion`, every nonempty `writes` gets a receipt; one whose job is dropped before the worker +/// has it reads as failed, its sender going with the job. +unsafe fn schedule(queue: *mut c_void, writes: Vec, completion: bool, wait_ms: u32) -> Option { + if writes.is_empty() { return None; } - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return None }; let (done, receipt) = if completion { let (tx, rx) = mpsc::channel(); (Some(tx), Some(Completion(rx))) } else { (None, None) }; + enqueue(queue, writes, wait_ms, done); + receipt +} + +unsafe fn enqueue(queue: *mut c_void, writes: Vec, wait_ms: u32, done: Option>) { + if queue.is_null() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; let job = { let mut g = FENCES.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); @@ -259,31 +289,30 @@ unsafe fn schedule(queue: *mut c_void, writes: Vec, completion: bool) -> std::collections::hash_map::Entry::Vacant(v) => { let mut dev: Option = None; if q.GetDevice(&mut dev).is_err() { - return None; + return; } - let Some(dev) = dev else { return None }; - let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return None }; + let Some(dev) = dev else { return }; + let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return }; v.insert(QueueFence { fence, value: 0 }) } }; entry.value += 1; if super::real::native_queue_signal(q, &entry.fence, entry.value).is_err() { - return None; + return; } - Job { fence: entry.fence.clone(), value: entry.value, writes, done } + Job { fence: entry.fence.clone(), value: entry.value, writes, wait_ms, done } }; static FIRST: std::sync::Once = std::sync::Once::new(); FIRST.call_once(|| crate::xlog_info!("D3D12.X: bottom-of-pipe writes outside unified memory are done by the CPU after the GPU ({} in the first submission)", job.writes.len())); - worker().lock().unwrap().send(job).ok()?; - receipt + let _ = worker().lock().unwrap().send(job); } pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { - let _ = schedule(queue, writes, false); + let _ = schedule(queue, writes, false, WAIT_MS); } pub(super) unsafe fn after_with_completion(queue: *mut c_void, writes: Vec) -> Option { - schedule(queue, writes, true) + schedule(queue, writes, true, WAIT_MS) } #[cfg(test)] @@ -401,6 +430,46 @@ mod tests { } } + /// A receipt is true only when the queue got to the writes' submission: false when the worker + /// wrote after giving up, and a later job's wait outlasts the event of the value given up on. + #[test] + fn a_receipt_says_whether_the_queue_got_there() { + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap(); + let warp: IDXGIAdapter = factory.EnumWarpAdapter().unwrap(); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.unwrap(); + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let cell = Box::new([0u32; 2]); + let va = cell.as_ptr() as usize; + + // the queue stands at the gate: the worker gives up after 50 ms and writes anyway + q.Wait(&gate, 1).unwrap(); + let late = schedule(q.as_raw(), vec![Write::Immediate(va, vec![7])], true, 50).expect("a receipt"); + assert!(!late.wait(), "a write done before its queue got there is not confirmed"); + + // the next job's value comes after a second gate; opening the first sets the worker's + // event for the value given up on, which must not end the next job's wait + q.Wait(&gate, 2).unwrap(); + let next = schedule(q.as_raw(), vec![Write::Immediate(va + 4, vec![9])], true, 5_000).expect("a receipt"); + gate.Signal(1).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + assert_eq!((*((va + 4) as *const AtomicU32)).load(Ordering::Acquire), 0, "written before its queue got there"); + gate.Signal(2).unwrap(); + assert!(next.wait(), "the queue got to the second job"); + assert_eq!(*cell, [7, 9]); + + // no queue: the job never reaches the worker, and the receipt says so + let lost = schedule(std::ptr::null_mut(), vec![Write::Immediate(va, vec![1])], true, 50).expect("a receipt"); + assert!(!lost.wait()); + assert!(schedule(q.as_raw(), Vec::new(), true, 50).is_none(), "no writes, no receipt"); + } + } + /// A ReadbackU64 write copies the 64-bit value from the mapped readback buffer after the queue finishes. #[test] fn readback_u64_lands_after_the_queue() { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 0210c522f1..7688a4a489 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3648,6 +3648,21 @@ unsafe fn submit_segment_effects(queue: *mut c_void, effects: &[SegmentEffects], } } +/// receipts of deferred CPU writes a wait went on without (`wait_cpu_completions`) +static CPU_WRITES_UNCONFIRMED: AtomicU64 = AtomicU64::new(0); + +/// Wait for the deferred CPU writes a following wait depends on. A receipt that is not confirmed +/// (the worker wrote after giving up on the GPU, or the job never reached it) is logged and the +/// wait goes on as for any other cell: the continuation is on the same queue, so the GPU still +/// runs it after the producer, and a wait the store did not satisfy times out (`wait_all_on`). +fn wait_cpu_completions(completions: &mut Vec) { + for completion in completions.drain(..) { + if !completion.wait() && once(&CPU_WRITES_UNCONFIRMED, 8) { + crate::xlog_warn!("D3D12.X: a wait after a deferred CPU write goes on without the GPU having finished the write's segment"); + } + } +} + /// Execute a plan and retain completion receipts for its deferred CPU writes. unsafe fn execute_submission_plan_with_completions( queue: *mut c_void, @@ -3698,9 +3713,7 @@ unsafe fn execute_submission_plan_with_completions( completions.extend(completion); } if after_cpu_write { - for completion in completions.drain(..) { - let _ = completion.wait(); - } + wait_cpu_completions(&mut completions); } let t = Instant::now(); let on_cpu = wait_all_on(queue, &effects.waits, &effects.write64_signals); @@ -5322,9 +5335,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } if !gate.failed() && !waits.is_empty() { if wait_after_cpu_write { - for completion in prior_cpu_completions.drain(..) { - let _ = completion.wait(); - } + wait_cpu_completions(&mut prior_cpu_completions); } if sparse_again_after_split(wait_all_on(q_raw, &waits, &write64_signals), split_sparse_after_cpu_waits_only()) { mapped_after_wait(q_raw); @@ -8426,7 +8437,7 @@ mod tests { std::thread::spawn(move || { std::thread::sleep(Duration::from_millis(20)); completed.store(true, Ordering::Release); - let _ = done.send(()); + let _ = done.send(true); }); (true, Some(receipt)) } else { @@ -8452,6 +8463,50 @@ mod tests { assert_eq!(callbacks, 1, "a failed first chunk suppresses later waits and submissions"); } + /// A receipt the worker could not confirm (here: dropped before it was sent) is counted, and + /// the continuation is still submitted once, after the producer. + #[test] + fn an_unconfirmed_cpu_receipt_is_counted_and_the_continuation_goes_on() { + let producer = 0x7ffe_2901usize as *mut c_void; + let continuation = 0x7ffe_2902usize as *mut c_void; + let cell = Box::new(AtomicU64::new(1)); + let va = &*cell as *const AtomicU64 as u64; + { + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + let mut first = ListState::default(); + first.note_write(WriteProducer::CpuAfterSegment, va, 8); + m.insert(producer as usize, first); + let wait = PendingWait { va, width: 8, comparison: D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, value: 1, mask: u64::MAX, after_write64: false }; + m.insert(continuation as usize, ListState { pending_waits: vec![wait], ..Default::default() }); + } + let plan = SubmissionPlan::capture(&[producer, continuation]); + { + let mut g = LISTS.lock().unwrap(); + let m = g.as_mut().unwrap(); + m.remove(&(producer as usize)); + m.remove(&(continuation as usize)); + } + let before = CPU_WRITES_UNCONFIRMED.load(Ordering::Relaxed); + let mut chunks = Vec::new(); + unsafe { + let leftovers = execute_submission_plan_with_completions(std::ptr::null_mut(), &plan, &[], |chunk| { + chunks.push(chunk.lists().to_vec()); + if chunk.lists() == [producer] { + let (receipt, done) = super::super::cpu_writes::completion_pair_for_test(); + drop(done); + (true, Some(receipt)) + } else { + (true, None) + } + }); + let (leftovers, submitted) = leftovers; + assert!(submitted && leftovers.is_empty()); + } + assert_eq!(chunks, vec![vec![producer], vec![continuation]]); + assert!(CPU_WRITES_UNCONFIRMED.load(Ordering::Relaxed) > before, "the unconfirmed receipt is counted"); + } + #[test] fn segment_reasons_keep_the_existing_segment_costs() { assert_eq!(SegmentReason::WaitAfterWrite64.extra_segments(), 1);