diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index e6400ef..9aaab4a 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -546,6 +546,12 @@ struct ListState { pending_waits: Vec, /// bottom-of-pipe writes into memory the GPU does not see (`cpu_writes`) cpu_writes: Vec, + /// Dedicated 256-byte buffer holding the current predicate value (created lazily in COMMON state). + pred_buf: Option, + /// True while `pred_buf` is in `D3D12_RESOURCE_STATE_PREDICATION` on this open recording. + pred_in_state: bool, + /// Active `SetPredicationBufferX` op, restored across `KickoffX`. + predication: Option, /// state a PC Reset clears (restored after KickoffX) bindings: Bindings, } @@ -613,9 +619,11 @@ static PENDING_WAIT_LISTS: AtomicUsize = AtomicUsize::new(0); static SPARSE_WRITE_LISTS: AtomicUsize = AtomicUsize::new(0); /// Set once any list uses `RSSetDepthBiasX` (fast-path guard for Draw* hooks). static DEPTH_BIAS_USED: AtomicBool = AtomicBool::new(false); +/// Set once any list uses `SetPredicationBufferX` (fast-path guard for Close/Reset hooks). +static PREDICATION_USED: AtomicBool = AtomicBool::new(false); /// Record a newly created title command queue so `KickoffX` can find a compatible queue. -pub(super) fn on_queue_create(queue: usize, device: usize, ty: D3D12_COMMAND_LIST_TYPE) { +pub fn on_queue_create(queue: usize, device: usize, ty: D3D12_COMMAND_LIST_TYPE) { if queue == 0 { return; } @@ -665,15 +673,19 @@ unsafe fn try_native_depth_bias(list: *mut c_void, bias: DepthBias) -> bool { } /// Record a newly created command list's allocator, initial pipeline, and type. -pub(super) unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_COMMAND_LIST_TYPE) { +/// +/// # Safety +/// `list` must be null or a valid `ID3D12GraphicsCommandList` COM pointer. +pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_COMMAND_LIST_TYPE) { if list.is_null() { return; } let key = list as usize; - { + let old = { let mut g = LISTS.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); - if let Some(old) = m.remove(&key) { + let old = m.remove(&key); + if let Some(ref old) = old { if !old.pending_waits.is_empty() { PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); } @@ -682,7 +694,9 @@ pub(super) unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: } } m.insert(key, ListState { allocator: alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); - } + old + }; + drop(old); // Dynamic-depth-bias PSOs ignore baked RasterizerState depth bias; seed the list with the // initial PSO's static bias if non-zero (CreateCommandList resets RSSetDepthBias to 0). if ty != D3D12_COMMAND_LIST_TYPE_BUNDLE && pso != 0 { @@ -698,7 +712,8 @@ pub(super) unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: /// Clean up all tracked state when a command list is released for good. pub(super) fn on_release(list: usize) { - if let Some(old) = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)) { + let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); + if let Some(old) = old { if !old.pending_waits.is_empty() { PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); } @@ -791,6 +806,7 @@ pub(super) unsafe fn on_clear_state(list: *mut c_void, pso: usize) { s.using_fallback_pso = false; s.index_buffer = None; s.depth_bounds = None; + s.predication = None; s.bindings = Bindings::default(); s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) } else { @@ -1126,7 +1142,10 @@ unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { } /// command list #69 Write32BitValueBottomOfPipeX(address, value, flush, flags) -pub(super) unsafe extern "system" fn write32_bottom_x(this: *mut c_void, va: u64, value: u32, _flush: u32, _flags: u32) { +/// +/// # Safety +/// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer. +pub unsafe extern "system" fn write32_bottom_x(this: *mut c_void, va: u64, value: u32, _flush: u32, _flags: u32) { write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, "Write32BitValueBottomOfPipeX"); } @@ -1234,21 +1253,159 @@ pub(super) unsafe extern "system" fn copy_resource_flags_x(this: *mut c_void, ds } } -/// command list #85 SetPredicationBufferX({ u64 address; u32 operation }*) -pub(super) unsafe extern "system" fn set_predication_buffer_x(this: *mut c_void, desc: *const u64) { - static N: AtomicU64 = AtomicU64::new(0); +/// Return `list`'s dedicated 256-byte predication buffer, creating it lazily in `COMMON` state. +unsafe fn predication_buffer(list: *mut c_void) -> Option { + if let Some(p) = LISTS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(list as usize))) + .and_then(|s| s.pred_buf.as_ref()) + .map(|r| r.as_raw() as usize) + { + return Some(p); + } + let dev = device_of(list)?; + let props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let mut buf: Option = None; + dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).ok()?; + let buf = buf?; + let (raw, extra) = { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + if let Some(existing) = s.pred_buf.as_ref() { + (existing.as_raw() as usize, Some(buf)) + } else { + let raw = buf.as_raw() as usize; + s.pred_buf = Some(buf); + (raw, None) + } + }; + drop(extra); + Some(raw) +} + +/// Before `Close()` on a command list: return `pred_buf` to `COMMON` if it is currently in +/// `D3D12_RESOURCE_STATE_PREDICATION`. +pub(super) unsafe fn before_close(list: *mut c_void) { + if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { + return; + } + let pb = { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(list as usize))) else { + return; + }; + if s.pred_in_state { + s.pred_in_state = false; + s.pred_buf.as_ref().map(|r| r.as_raw() as usize) + } else { + None + } + }; + if let Some(pb) = pb { + transition(list, pb, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON); + } +} + +/// Clear active predication state when `ID3D12GraphicsCommandList::Reset` resets a recording. +pub(super) fn on_pc_reset(list: *mut c_void) { + if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { + return; + } + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.predication = None; + s.pred_in_state = false; + } +} + +/// Copy 8 predicate bytes from `(uma_buf, off)` into `pb` with exact barrier transitions and +/// bind `SetPredication(pb, 0, op)` on `this`. +unsafe fn apply_predication_copy(this: *mut c_void, uma_buf: usize, off: u64, pb: usize, op: D3D12_PREDICATION_OP) { type F = unsafe extern "system" fn(*mut c_void, usize, u64, D3D12_PREDICATION_OP); let f = pc::(this, PC_SET_PREDICATION); - if desc.is_null() { - return f(this, 0, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); + let (was_active, was_in_state) = LISTS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(this as usize))) + .map_or((false, false), |s| (s.predication.is_some(), s.pred_in_state)); + // Disarm any active predicate before copying the new predicate value so a failing predicate + // does not suppress `CopyBufferRegion` when switching directly between buffers. + if was_active { + f(this, 0, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); } - let (va, op) = (desc.read_unaligned(), (desc.add(1) as *const u32).read_unaligned()); - let Some((b, off)) = real::uma_window_buffer(va as usize, 8).filter(|_| va.is_multiple_of(8)) else { + transition(this, uma_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + let pb_before = if was_in_state { D3D12_RESOURCE_STATE_PREDICATION } else { D3D12_RESOURCE_STATE_COMMON }; + transition(this, pb, pb_before, D3D12_RESOURCE_STATE_COPY_DEST); + copy_buffer_region(this, pb, 0, uma_buf, off, 8); + transition(this, uma_buf, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + transition(this, pb, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PREDICATION); + f(this, pb, 0, op); + PREDICATION_USED.store(true, Ordering::Release); + if let Some(s) = LISTS.lock().unwrap().get_or_insert_with(HashMap::new).get_mut(&(this as usize)) { + s.predication = Some(op); + s.pred_in_state = true; + } +} + +/// command list #85 SetPredicationBufferX({ u64 address; u32 operation }*) +/// +/// # Safety +/// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer, and non-null `desc` +/// must point to readable memory if present. +pub unsafe extern "system" fn set_predication_buffer_x(this: *mut c_void, desc: *const u64) { + static N: AtomicU64 = AtomicU64::new(0); + let ty = list_type(this); + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return warn(&N, "SetPredicationBufferX", format_args!("unsupported command list type {}", ty.0)); + } + type F = unsafe extern "system" fn(*mut c_void, usize, u64, D3D12_PREDICATION_OP); + if desc.is_null() { + let f = pc::(this, PC_SET_PREDICATION); + f(this, 0, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); + let pb = { + let mut g = LISTS.lock().unwrap(); + g.as_mut().and_then(|m| m.get_mut(&(this as usize))).and_then(|s| { + s.predication = None; + if s.pred_in_state { + s.pred_in_state = false; + s.pred_buf.as_ref().map(|r| r.as_raw() as usize) + } else { + None + } + }) + }; + if let Some(pb) = pb { + transition(this, pb, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON); + } + return; + } + if !crate::gpu::shader::readable(desc as usize, 12) { + return warn(&N, "SetPredicationBufferX", format_args!("descriptor {desc:p} is not readable")); + } + let (va, op_raw) = (desc.read_unaligned(), (desc.add(1) as *const u32).read_unaligned()); + if op_raw > 1 { + return warn(&N, "SetPredicationBufferX", format_args!("unknown predication op {op_raw}")); + } + let Some((uma_buf, off)) = real::uma_window_buffer(va as usize, 8).filter(|&(b, _)| b != 0 && va.is_multiple_of(8)) else { return warn(&N, "SetPredicationBufferX", format_args!("{va:#x} is not 8-byte aligned in unified memory")); }; - transition(this, b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PREDICATION); - f(this, b, off, D3D12_PREDICATION_OP(op as i32)); - transition(this, b, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON); + let Some(pb) = predication_buffer(this) else { + return warn(&N, "SetPredicationBufferX", format_args!("could not allocate predication buffer")); + }; + apply_predication_copy(this, uma_buf, off, pb, D3D12_PREDICATION_OP(op_raw as i32)); } /// command list #93 KickoffX(): flush commands recorded so far by closing the list, submitting @@ -1258,7 +1415,10 @@ pub(super) unsafe extern "system" fn set_predication_buffer_x(this: *mut c_void, /// If no compatible queue or allocator is known yet (e.g. a bundle, or a list created before /// any queue of its type exists), `KickoffX` is a safe logged no-op and the recorded work runs /// at `Close` + `ExecuteCommandLists`. -pub(super) unsafe extern "system" fn kickoff_x(this: *mut c_void) { +/// +/// # Safety +/// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer. +pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { static NO_QUEUE: AtomicU64 = AtomicU64::new(0); static ERR: AtomicU64 = AtomicU64::new(0); let ty = list_type(this); @@ -1266,7 +1426,7 @@ pub(super) unsafe extern "system" fn kickoff_x(this: *mut c_void) { return; } let dev_raw = device_of(this).map_or(0, |d| d.as_raw() as usize); - let (alloc, queue, bound_pso, depth_bias, index_buffer, depth_bounds, active_query, waits, sparse_writes) = { + let (alloc, queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, waits, sparse_writes) = { let mut g = LISTS.lock().unwrap(); let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { if once(&NO_QUEUE, 4) { @@ -1296,7 +1456,9 @@ pub(super) unsafe extern "system" fn kickoff_x(this: *mut c_void) { let sparse_writes = s.clear_sparse_writes(); s.written_ranges.clear(); let cpu_writes = std::mem::take(&mut s.cpu_writes); - (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, active_query, waits, (sparse_writes, cpu_writes)) + let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); + let pred_buf = s.pred_buf.as_ref().map(|r| r.as_raw() as usize); + (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, waits, (sparse_writes, cpu_writes)) }; let (sparse_writes, cpu_writes) = sparse_writes; @@ -1304,6 +1466,11 @@ pub(super) unsafe extern "system" fn kickoff_x(this: *mut c_void) { if let Some(((h, i), qty)) = active_query { pc::(this, PC_END_QUERY)(this, h, qty, i); } + if pred_in_state { + if let Some(pb) = pred_buf { + transition(this, pb, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON); + } + } let ext = *(this as *const usize); let close_hr = pc:: i32>(this, PC_CLOSE)(this); @@ -1381,6 +1548,13 @@ pub(super) unsafe extern "system" fn kickoff_x(this: *mut c_void) { if let Some((min, max)) = depth_bounds { pc::(this, PC_OM_SET_DEPTH_BOUNDS)(this, min, max); } + if let (Some(op), Some(pb)) = (predication, pred_buf) { + transition(this, pb, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PREDICATION); + pc::(this, PC_SET_PREDICATION)(this, pb, 0, op); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + s.pred_in_state = true; + } + } } /// command list #94 RSSetDepthBiasX(depthBias, depthBiasClamp, slopeScaledDepthBias): @@ -1844,7 +2018,10 @@ type QueryFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u /// command list #10 Reset(allocator, initial pipeline): updates allocator/pipeline and clears /// per-recording state (queries, index buffer, depth bias, pending waits, written ranges) -pub(super) unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usize) -> i32 { +/// +/// # Safety +/// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer. +pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usize) -> i32 { // A failed native Reset leaves the old recording alive. Do not discard its tracked state or // transfer its allocations until the driver accepts the new recording. let ext = *(this as *const usize); @@ -1871,6 +2048,8 @@ pub(super) unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, ps s.clear_sparse_writes(); s.clear_waits(); s.cpu_writes.clear(); + s.predication = None; + s.pred_in_state = false; s.bindings = Bindings::default(); s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) }; @@ -3107,4 +3286,249 @@ mod tests { on_release(list_ptr as usize); } + + #[test] + fn set_predication_buffer_state_transitions_and_lifecycle() { + #[derive(Debug, PartialEq, Eq)] + enum PredEvent { + Barrier(usize, D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES), + Copy(usize, u64, usize, u64, u64), + SetPred(usize, u64, D3D12_PREDICATION_OP), + } + + #[repr(C)] + struct PredDesc { + va: u64, + op: u32, + } + + #[repr(C)] + struct FakePredList { + vt: *const usize, + ty: Mutex, + events: Mutex>, + } + + #[repr(C)] + struct FakeComRes { + vt: *const usize, + refs: AtomicUsize, + } + + unsafe extern "system" fn fake_get_type(this: *mut c_void) -> D3D12_COMMAND_LIST_TYPE { + *(*(this as *const FakePredList)).ty.lock().unwrap() + } + + unsafe extern "system" fn fake_resource_barrier(this: *mut c_void, count: u32, barriers: *const D3D12_RESOURCE_BARRIER) { + let mut events = (*(this as *const FakePredList)).events.lock().unwrap(); + for i in 0..count as usize { + let b = &*barriers.add(i); + assert_eq!(b.Type, D3D12_RESOURCE_BARRIER_TYPE_TRANSITION); + let tr = &*b.Anonymous.Transition; + let res = (std::ptr::addr_of!(tr.pResource) as *const usize).read_unaligned(); + events.push(PredEvent::Barrier(res, tr.StateBefore, tr.StateAfter)); + } + } + + unsafe extern "system" fn fake_copy_buffer_region( + this: *mut c_void, + dst: usize, + dst_off: u64, + src: usize, + src_off: u64, + n: u64, + ) { + (*(this as *const FakePredList)) + .events + .lock() + .unwrap() + .push(PredEvent::Copy(dst, dst_off, src, src_off, n)); + } + + unsafe extern "system" fn fake_set_predication( + this: *mut c_void, + res: usize, + off: u64, + op: D3D12_PREDICATION_OP, + ) { + (*(this as *const FakePredList)) + .events + .lock() + .unwrap() + .push(PredEvent::SetPred(res, off, op)); + } + + unsafe extern "system" fn res_add_ref(this: *mut c_void) -> u32 { + (*(this as *const FakeComRes)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + + unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { + (*(this as *const FakeComRes)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + + let mut orig_vt = [0usize; 64]; + orig_vt[PC_GET_TYPE] = fake_get_type as usize; + orig_vt[PC_COPY_BUFFER_REGION] = fake_copy_buffer_region as usize; + orig_vt[PC_RESOURCE_BARRIER] = fake_resource_barrier as usize; + orig_vt[PC_SET_PREDICATION] = fake_set_predication as usize; + + let mut ext_vt = [0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + + let fake = Box::new(FakePredList { + // SAFETY: `ext_vt` has 65 entries so `.add(1)` points at slot 0 with `orig_vt` at `-1`. + vt: unsafe { ext_vt.as_ptr().add(1) }, + ty: Mutex::new(D3D12_COMMAND_LIST_TYPE_DIRECT), + events: Mutex::new(Vec::new()), + }); + let list_ptr = &*fake as *const FakePredList as *mut c_void; + let list_key = list_ptr as usize; + + let mut res_vt = [0usize; 16]; + res_vt[1] = res_add_ref as usize; + res_vt[2] = res_release as usize; + let fake_res = Box::new(FakeComRes { + vt: res_vt.as_ptr(), + refs: AtomicUsize::new(1), + }); + let pb_raw = &*fake_res as *const FakeComRes as usize; + let uma_buf = 0xDEAD_BEEFusize; + + let take_events = || std::mem::take(&mut *fake.events.lock().unwrap()); + + unsafe { + // Seed ListState with fake dedicated predication resource and verify initial rejections. + on_create(list_ptr, 0x100, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + { + let mut g = LISTS.lock().unwrap(); + let s = g.as_mut().unwrap().get_mut(&list_key).unwrap(); + s.pred_buf = Some(ID3D12Resource::from_raw(pb_raw as *mut c_void)); + } + + // (a) BUNDLE and COPY lists are rejected without emitting any commands. + *fake.ty.lock().unwrap() = D3D12_COMMAND_LIST_TYPE_BUNDLE; + set_predication_buffer_x(list_ptr, std::ptr::null()); + assert!(take_events().is_empty(), "BUNDLE list must reject SetPredicationBufferX"); + + *fake.ty.lock().unwrap() = D3D12_COMMAND_LIST_TYPE_COPY; + set_predication_buffer_x(list_ptr, std::ptr::null()); + assert!(take_events().is_empty(), "COPY list must reject SetPredicationBufferX"); + + // (b) DIRECT and COMPUTE lists reject invalid descriptors / ops / alignments / non-UMA VAs. + let non_uma_slot = 0u64; + let non_uma_va = &non_uma_slot as *const u64 as u64; + let bad_op = PredDesc { va: 0x1000, op: 2 }; + let unaligned = PredDesc { va: 0x1004, op: 0 }; + let non_uma = PredDesc { va: non_uma_va, op: 0 }; + let bad_desc = std::ptr::without_provenance::(1); + for ty in [D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_TYPE_COMPUTE] { + *fake.ty.lock().unwrap() = ty; + set_predication_buffer_x(list_ptr, bad_desc); + set_predication_buffer_x(list_ptr, &bad_op as *const PredDesc as *const u64); + set_predication_buffer_x(list_ptr, &unaligned as *const PredDesc as *const u64); + set_predication_buffer_x(list_ptr, &non_uma as *const PredDesc as *const u64); + assert!(take_events().is_empty(), "invalid inputs on {ty:?} must emit no events"); + } + + // (c) Initial apply_predication_copy emits exact barriers + copy + SetPredication without disarm. + *fake.ty.lock().unwrap() = D3D12_COMMAND_LIST_TYPE_DIRECT; + apply_predication_copy(list_ptr, uma_buf, 0x100, pb_raw, D3D12_PREDICATION_OP_EQUAL_ZERO); + assert_eq!( + take_events(), + vec![ + PredEvent::Barrier(uma_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE), + PredEvent::Barrier(pb_raw, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST), + PredEvent::Copy(pb_raw, 0, uma_buf, 0x100, 8), + PredEvent::Barrier(uma_buf, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON), + PredEvent::Barrier(pb_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PREDICATION), + PredEvent::SetPred(pb_raw, 0, D3D12_PREDICATION_OP_EQUAL_ZERO), + ] + ); + + // Rejections while a predicate is active must neither emit events nor disturb tracked state. + for ty in [D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_TYPE_COMPUTE] { + *fake.ty.lock().unwrap() = ty; + set_predication_buffer_x(list_ptr, bad_desc); + set_predication_buffer_x(list_ptr, &bad_op as *const PredDesc as *const u64); + set_predication_buffer_x(list_ptr, &unaligned as *const PredDesc as *const u64); + set_predication_buffer_x(list_ptr, &non_uma as *const PredDesc as *const u64); + assert!(take_events().is_empty()); + } + *fake.ty.lock().unwrap() = D3D12_COMMAND_LIST_TYPE_DIRECT; + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&list_key).unwrap(); + assert_eq!(s.predication, Some(D3D12_PREDICATION_OP_EQUAL_ZERO)); + assert!(s.pred_in_state); + } + + // (d) Direct switch without NULL disarms active predicate BEFORE copy and transitions PREDICATION -> COPY_DEST. + apply_predication_copy(list_ptr, uma_buf, 0x200, pb_raw, D3D12_PREDICATION_OP_NOT_EQUAL_ZERO); + assert_eq!( + take_events(), + vec![ + PredEvent::SetPred(0, 0, D3D12_PREDICATION_OP_EQUAL_ZERO), + PredEvent::Barrier(uma_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE), + PredEvent::Barrier(pb_raw, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COPY_DEST), + PredEvent::Copy(pb_raw, 0, uma_buf, 0x200, 8), + PredEvent::Barrier(uma_buf, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON), + PredEvent::Barrier(pb_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PREDICATION), + PredEvent::SetPred(pb_raw, 0, D3D12_PREDICATION_OP_NOT_EQUAL_ZERO), + ] + ); + + // (e) ClearState clears predication while keeping pred_in_state == true: + // re-arming omits redundant SetPred(0, ...) yet transitions pb_raw from PREDICATION -> COPY_DEST, + // and ClearState + before_close still transitions pb_raw from PREDICATION -> COMMON (once). + on_clear_state(list_ptr, 0); + apply_predication_copy(list_ptr, uma_buf, 0x300, pb_raw, D3D12_PREDICATION_OP_EQUAL_ZERO); + assert_eq!( + take_events(), + vec![ + PredEvent::Barrier(uma_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE), + PredEvent::Barrier(pb_raw, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COPY_DEST), + PredEvent::Copy(pb_raw, 0, uma_buf, 0x300, 8), + PredEvent::Barrier(uma_buf, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON), + PredEvent::Barrier(pb_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PREDICATION), + PredEvent::SetPred(pb_raw, 0, D3D12_PREDICATION_OP_EQUAL_ZERO), + ] + ); + + on_clear_state(list_ptr, 0); + before_close(list_ptr); + assert_eq!( + take_events(), + vec![PredEvent::Barrier(pb_raw, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON)] + ); + before_close(list_ptr); + assert!(take_events().is_empty(), "second before_close must be idempotent"); + + // (f) NULL transitions PREDICATION -> COMMON when active; second NULL emits 0 barriers. + apply_predication_copy(list_ptr, uma_buf, 0x100, pb_raw, D3D12_PREDICATION_OP_EQUAL_ZERO); + take_events(); + set_predication_buffer_x(list_ptr, std::ptr::null()); + assert_eq!( + take_events(), + vec![ + PredEvent::SetPred(0, 0, D3D12_PREDICATION_OP_EQUAL_ZERO), + PredEvent::Barrier(pb_raw, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON), + ] + ); + set_predication_buffer_x(list_ptr, std::ptr::null()); + assert_eq!(take_events(), vec![PredEvent::SetPred(0, 0, D3D12_PREDICATION_OP_EQUAL_ZERO)]); + + // (g) on_pc_reset clears predication & pred_in_state so subsequent before_close emits 0 barriers. + apply_predication_copy(list_ptr, uma_buf, 0x100, pb_raw, D3D12_PREDICATION_OP_EQUAL_ZERO); + take_events(); + on_pc_reset(list_ptr); + before_close(list_ptr); + assert!(take_events().is_empty(), "on_pc_reset must clear pred_in_state before before_close"); + } + + // (h) on_release removes ListState and releases the dedicated COM resource. + on_release(list_key); + assert!(!has_list_state(list_key)); + assert_eq!(fake_res.refs.load(Ordering::Relaxed), 0); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index d8c7bfd..19e3c55 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2293,6 +2293,7 @@ macro_rules! as_usize { /// command list's vtable pointer on Close; adopt the runtime's new state vtable so /// subsequent Reset and console calls dispatch through the current native table. unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { + super::list_x::before_close(this); let ext = *(this as *const usize); let f: RefFn = std::mem::transmute(orig_fn(this, slot_of(this, "Close"))); let hr = f(this) as HRESULT; @@ -2312,6 +2313,9 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in let resolved = super::pso_async::resolve_for_bind(initial_state as usize) as *mut c_void; let hr = f(this, allocator, resolved); preserve_vtable(this, ext); + if hr >= 0 { + super::list_x::on_pc_reset(this); + } hr } diff --git a/crates/xcl/tests/predication_e2e.rs b/crates/xcl/tests/predication_e2e.rs new file mode 100644 index 0000000..95b8443 --- /dev/null +++ b/crates/xcl/tests/predication_e2e.rs @@ -0,0 +1,468 @@ +//! End-to-end GPU + D3D12 debug-layer test for `SetPredicationBufferX`. +//! +//! Exercises: +//! 1. Predicated copies (`EQUAL_ZERO` skipping/executing, `NOT_EQUAL_ZERO`, `NULL`), interleaved +//! UMA window writes (`Write32BitValueBottomOfPipeX`) on the same UMA window without state +//! conflicts, GPU-written predicate updates in the same recording, and direct switching from +//! one predicate buffer to another without `NULL`. +//! 2. `KickoffX` closing, submitting, and resetting mid-recording while predication is active, +//! preserving predication afterward, followed by closing the list while still active. +//! 3. `ClearState` unbinding predication while preserving the dedicated predication buffer's +//! resource state, then re-arming `SetPredicationBufferX` on the same recording. + +use std::ffi::c_void; +use std::sync::Mutex; + +use windows::core::Interface; +use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + +use xcl::gpu::recomp::runner; +use xcl::hle::d3d12x::{list_x, real}; + +#[repr(C)] +struct PredDesc { + va: u64, + op: u32, +} + +static DEBUG_ERRORS: Mutex> = Mutex::new(Vec::new()); + +unsafe extern "system" fn collect_debug_message( + _category: D3D12_MESSAGE_CATEGORY, + severity: D3D12_MESSAGE_SEVERITY, + id: D3D12_MESSAGE_ID, + text: windows::core::PCSTR, + _context: *mut c_void, +) { + if severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 { + let msg = if text.is_null() { + String::new() + } else { + String::from_utf8_lossy(text.as_bytes()).into_owned() + }; + DEBUG_ERRORS + .lock() + .unwrap() + .push(format!("severity={} id={} {msg}", severity.0, id.0)); + } +} + +fn buffer( + dev: &ID3D12Device, + bytes: u64, + heap: D3D12_HEAP_TYPE, + state: D3D12_RESOURCE_STATES, +) -> ID3D12Resource { + let props = D3D12_HEAP_PROPERTIES { + Type: heap, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let mut res: Option = None; + unsafe { + dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut res) + .expect("CreateCommittedResource"); + } + res.unwrap() +} + +unsafe fn wait_fence(queue: &ID3D12CommandQueue, fence: &ID3D12Fence, value: &mut u64) { + *value += 1; + let target = *value; + queue.Signal(fence, target).expect("Signal"); + if fence.GetCompletedValue() < target { + let ev = CreateEventW(None, false, false, None).expect("CreateEventW"); + let res = fence.SetEventOnCompletion(target, ev).map(|()| { + let s = WaitForSingleObject(ev, 10_000); + if s != WAIT_OBJECT_0 { + panic!("WaitForSingleObject returned {s:?}"); + } + }); + let _ = CloseHandle(ev); + res.expect("SetEventOnCompletion"); + } +} + +struct ReadbackCtx<'a> { + queue: &'a ID3D12CommandQueue, + alloc: &'a ID3D12CommandAllocator, + list: &'a ID3D12GraphicsCommandList, + fence: &'a ID3D12Fence, +} + +unsafe fn read_u32s( + ctx: &ReadbackCtx<'_>, + fence_val: &mut u64, + dst_default: &ID3D12Resource, + readback: &ID3D12Resource, + count: usize, +) -> Vec { + let bytes = (count * 4) as u64; + ctx.list.Reset(ctx.alloc, None).expect("readback Reset"); + ctx.list.CopyBufferRegion(readback, 0, dst_default, 0, bytes); + ctx.list.Close().expect("readback Close"); + let cl: ID3D12CommandList = ctx.list.cast().unwrap(); + ctx.queue.ExecuteCommandLists(&[Some(cl)]); + wait_fence(ctx.queue, ctx.fence, fence_val); + + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).expect("Map readback"); + let out = std::slice::from_raw_parts(p as *const u32, count).to_vec(); + readback.Unmap(0, None); + out +} + +fn take_debug_errors(iq: Option<&ID3D12InfoQueue>) -> Vec { + let mut errs = std::mem::take(&mut *DEBUG_ERRORS.lock().unwrap()); + if let Some(iq) = iq { + unsafe { + let n = iq.GetNumStoredMessages(); + for i in 0..n { + let mut len = 0usize; + if iq.GetMessage(i, None, &mut len).is_ok() && len > 0 { + let mut buf = vec![0u8; len]; + let msg_ptr = buf.as_mut_ptr() as *mut D3D12_MESSAGE; + if iq.GetMessage(i, Some(msg_ptr), &mut len).is_ok() { + let msg = &*msg_ptr; + if msg.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 { + let desc = if msg.pDescription.is_null() { + String::new() + } else { + std::ffi::CStr::from_ptr(msg.pDescription as *const i8) + .to_string_lossy() + .into_owned() + }; + errs.push(format!("stored id={} {desc}", msg.ID.0)); + } + } + } + } + iq.ClearStoredMessages(); + } + } + errs +} + +#[test] +fn set_predication_buffer_state_and_kickoff() { + std::env::set_var("XCL_UMA_MB", "64"); + std::env::set_var("XCL_D3D12_DEBUG", "1"); + + if xcl::hle::d3d12x::backend() != xcl::hle::d3d12x::Backend::Real { + println!("no real D3D12 device – skipping"); + runner::skip_test("no GPU"); + return; + } + let Some(uma) = xcl::gpu::uma::get() else { + println!("no UMA – skipping"); + runner::skip_test("no UMA"); + return; + }; + if real::uma_gpu_va() == 0 { + println!("UMA not opened on GPU – skipping"); + runner::skip_test("no GPU UMA"); + return; + } + + let raw_dev = real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw_dev) } + .expect("backend device") + .clone(); + + let iq = dev.cast::().ok(); + let iq1 = dev.cast::().ok(); + let mut cookie = 0u32; + if let Some(ref q1) = iq1 { + unsafe { + let _ = q1.RegisterMessageCallback( + Some(collect_debug_message), + D3D12_MESSAGE_CALLBACK_FLAG_NONE, + std::ptr::null_mut(), + &mut cookie, + ); + } + } + let _ = take_debug_errors(iq.as_ref()); + + unsafe { + // Allocate UMA slots in committed coherent UMA (zero-initialized, 8-byte aligned). + let uma_ptr = uma.alloc(0x1_0000, 0x1_0000).expect("UMA block"); + let slot_zero_va = uma_ptr as u64; + let slot_one_va = uma_ptr.add(0x100) as u64; + let slot_write_va = uma_ptr.add(0x200) as u64; + let slot_gpu_va = uma_ptr.add(0x300) as u64; + (slot_zero_va as *mut u64).write_volatile(0); + (slot_one_va as *mut u64).write_volatile(1); + (slot_write_va as *mut u64).write_volatile(0); + (slot_gpu_va as *mut u64).write_volatile(0); + + let desc_zero_eq = PredDesc { + va: slot_zero_va, + op: D3D12_PREDICATION_OP_EQUAL_ZERO.0 as u32, + }; + let desc_one_eq = PredDesc { + va: slot_one_va, + op: D3D12_PREDICATION_OP_EQUAL_ZERO.0 as u32, + }; + let desc_one_ne = PredDesc { + va: slot_one_va, + op: D3D12_PREDICATION_OP_NOT_EQUAL_ZERO.0 as u32, + }; + let desc_gpu_eq = PredDesc { + va: slot_gpu_va, + op: D3D12_PREDICATION_OP_EQUAL_ZERO.0 as u32, + }; + + const COUNT: usize = 9; + let bytes = (COUNT * 4) as u64; + let init_vals: [u32; COUNT] = [ + 0x1111_1111, + 0x2222_2222, + 0x3333_3333, + 0x4444_4444, + 0x5555_5555, + 0x6666_6666, + 0x7777_7777, + 0x8888_8888, + 0x9999_9999, + ]; + let src_vals: [u32; COUNT] = [ + 0xAAAA_0000, + 0xBBBB_0001, + 0xCCCC_0002, + 0xDDDD_0003, + 0xEEEE_0004, + 0xFFFF_0005, + 0x9999_0006, + 0x1234_0007, + 0x5678_0008, + ]; + + let init_buf = buffer( + &dev, + bytes, + D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + let src_buf = buffer( + &dev, + bytes, + D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + let dst_buf = buffer( + &dev, + bytes, + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_STATE_COMMON, + ); + let readback = buffer( + &dev, + bytes, + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + + let mut p = std::ptr::null_mut(); + init_buf.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::copy_nonoverlapping(init_vals.as_ptr(), p as *mut u32, COUNT); + init_buf.Unmap(0, None); + + src_buf.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::copy_nonoverlapping(src_vals.as_ptr(), p as *mut u32, COUNT); + src_buf.Unmap(0, None); + + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .expect("CreateCommandQueue"); + list_x::on_queue_create( + queue.as_raw() as usize, + dev.as_raw() as usize, + D3D12_COMMAND_LIST_TYPE_DIRECT, + ); + + let alloc: ID3D12CommandAllocator = dev + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .expect("CreateCommandAllocator"); + let list: ID3D12GraphicsCommandList = dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None) + .expect("CreateCommandList"); + let list_ptr = list.as_raw(); + list_x::on_create( + list_ptr, + alloc.as_raw() as usize, + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + ); + + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut fence_val = 0u64; + let ctx = ReadbackCtx { + queue: &queue, + alloc: &alloc, + list: &list, + fence: &fence, + }; + + // Seed dst_buf with init_vals. + list.CopyBufferRegion(&dst_buf, 0, &init_buf, 0, bytes); + list.Close().unwrap(); + let cl: ID3D12CommandList = list.cast().unwrap(); + queue.ExecuteCommandLists(&[Some(cl)]); + wait_fence(&queue, &fence, &mut fence_val); + let _ = take_debug_errors(iq.as_ref()); + + // Case 1: + // - dst[0]: EQUAL_ZERO on value 0 -> must SKIP copy + // - interleaved Write32BitValueBottomOfPipeX on the same UMA window while predication is active + // - switch directly to EQUAL_ZERO on value 1 WITHOUT calling NULL first -> dst[1] must EXECUTE + // - NOT_EQUAL_ZERO on value 1 -> dst[2] must SKIP + // - SetPredicationBufferX(NULL) -> dst[3] must EXECUTE + list.Reset(&alloc, None).unwrap(); + list_x::set_predication_buffer_x(list_ptr, &desc_zero_eq as *const PredDesc as *const u64); + list.CopyBufferRegion(&dst_buf, 0, &src_buf, 0, 4); + list_x::write32_bottom_x(list_ptr, slot_write_va, 0xABCD_1234, 0, 0); + list_x::set_predication_buffer_x(list_ptr, &desc_one_eq as *const PredDesc as *const u64); + list.CopyBufferRegion(&dst_buf, 4, &src_buf, 4, 4); + list_x::set_predication_buffer_x(list_ptr, &desc_one_ne as *const PredDesc as *const u64); + list.CopyBufferRegion(&dst_buf, 8, &src_buf, 8, 4); + list_x::set_predication_buffer_x(list_ptr, std::ptr::null()); + list.CopyBufferRegion(&dst_buf, 12, &src_buf, 12, 4); + list.Close().unwrap(); + + let cl: ID3D12CommandList = list.cast().unwrap(); + queue.ExecuteCommandLists(&[Some(cl)]); + wait_fence(&queue, &fence, &mut fence_val); + + let case1_errs = take_debug_errors(iq.as_ref()); + let got1 = read_u32s(&ctx, &mut fence_val, &dst_buf, &readback, COUNT); + let written_uma = (slot_write_va as *const u32).read_volatile(); + assert!(case1_errs.is_empty(), "Case 1 D3D12 debug errors: {case1_errs:#?}"); + assert_eq!(got1[0], init_vals[0], "EQUAL_ZERO(0) must skip dst[0]"); + assert_eq!(got1[1], src_vals[1], "direct switch to EQUAL_ZERO(1) must execute dst[1]"); + assert_eq!(got1[2], init_vals[2], "NOT_EQUAL_ZERO(1) must skip dst[2]"); + assert_eq!(got1[3], src_vals[3], "SetPredicationBufferX(NULL) must execute dst[3]"); + assert_eq!( + written_uma, 0xABCD_1234, + "Write32BitValueBottomOfPipeX on UMA must still write 0xABCD_1234" + ); + + // Case 1b: GPU-written predicate values (`Write32BitValueBottomOfPipeX` -> `SetPredicationBufferX`) + // within a single command list recording, verifying barrier ordering on the UMA window. + alloc.Reset().unwrap(); + list.Reset(&alloc, None).unwrap(); + list_x::write32_bottom_x(list_ptr, slot_gpu_va, 0, 0, 0); + list_x::set_predication_buffer_x(list_ptr, &desc_gpu_eq as *const PredDesc as *const u64); + list.CopyBufferRegion(&dst_buf, 28, &src_buf, 28, 4); + list_x::write32_bottom_x(list_ptr, slot_gpu_va, 1, 0, 0); + list_x::set_predication_buffer_x(list_ptr, &desc_gpu_eq as *const PredDesc as *const u64); + list.CopyBufferRegion(&dst_buf, 32, &src_buf, 32, 4); + list_x::set_predication_buffer_x(list_ptr, std::ptr::null()); + list.Close().unwrap(); + + let cl: ID3D12CommandList = list.cast().unwrap(); + queue.ExecuteCommandLists(&[Some(cl)]); + wait_fence(&queue, &fence, &mut fence_val); + + let case1b_errs = take_debug_errors(iq.as_ref()); + let got1b = read_u32s(&ctx, &mut fence_val, &dst_buf, &readback, COUNT); + assert!(case1b_errs.is_empty(), "Case 1b D3D12 debug errors: {case1b_errs:#?}"); + assert_eq!( + got1b[7], init_vals[7], + "GPU-written EQUAL_ZERO(0) must skip dst[7]" + ); + assert_eq!( + got1b[8], src_vals[8], + "GPU-written EQUAL_ZERO(1) in the same recording must execute dst[8]" + ); + + // Case 2: KickoffX mid-recording while EQUAL_ZERO(0) predication is active, + // then predicated CopyBufferRegion on dst[4], then Close while STILL active! + list.Reset(&alloc, None).unwrap(); + list_x::set_predication_buffer_x(list_ptr, &desc_zero_eq as *const PredDesc as *const u64); + list_x::kickoff_x(list_ptr); + list.CopyBufferRegion(&dst_buf, 16, &src_buf, 16, 4); + list.Close().unwrap(); + + let cl: ID3D12CommandList = list.cast().unwrap(); + queue.ExecuteCommandLists(&[Some(cl)]); + wait_fence(&queue, &fence, &mut fence_val); + + let case2_errs = take_debug_errors(iq.as_ref()); + let got2 = read_u32s(&ctx, &mut fence_val, &dst_buf, &readback, COUNT); + assert!(case2_errs.is_empty(), "Case 2 D3D12 debug errors: {case2_errs:#?}"); + assert_eq!( + got2[4], init_vals[4], + "KickoffX must preserve active EQUAL_ZERO(0) predication so dst[4] stays skipped" + ); + + // Case 3: ClearState unbinds predication on PC list without changing pred_buf state: + // - EQUAL_ZERO(0) -> ClearState(None) -> dst[5] executes unpredicated + // - Re-arm SetPredicationBufferX(EQUAL_ZERO(0)) in the SAME recording -> dst[6] skipped + // - Close while active + alloc.Reset().unwrap(); + list.Reset(&alloc, None).unwrap(); + list_x::set_predication_buffer_x(list_ptr, &desc_zero_eq as *const PredDesc as *const u64); + list.ClearState(None); + list.CopyBufferRegion(&dst_buf, 20, &src_buf, 20, 4); + list_x::set_predication_buffer_x(list_ptr, &desc_zero_eq as *const PredDesc as *const u64); + list.CopyBufferRegion(&dst_buf, 24, &src_buf, 24, 4); + list.Close().unwrap(); + + let cl: ID3D12CommandList = list.cast().unwrap(); + queue.ExecuteCommandLists(&[Some(cl)]); + wait_fence(&queue, &fence, &mut fence_val); + + let case3_errs = take_debug_errors(iq.as_ref()); + let got3 = read_u32s(&ctx, &mut fence_val, &dst_buf, &readback, COUNT); + assert!(case3_errs.is_empty(), "Case 3 D3D12 debug errors: {case3_errs:#?}"); + assert_eq!(got3[5], src_vals[5], "ClearState must unbind predication so dst[5] executes"); + assert_eq!( + got3[6], init_vals[6], + "re-arming SetPredicationBufferX after ClearState must skip dst[6]" + ); + + // Also test console Reset (`list_x::reset_x`) clears predication while reusing `pred_buf`. + alloc.Reset().unwrap(); + let hr = list_x::reset_x(list_ptr, alloc.as_raw() as usize, 0); + assert!(hr >= 0, "reset_x failed: {hr:#x}"); + list.CopyBufferRegion(&dst_buf, 24, &src_buf, 24, 4); + list.Close().unwrap(); + let cl: ID3D12CommandList = list.cast().unwrap(); + queue.ExecuteCommandLists(&[Some(cl)]); + wait_fence(&queue, &fence, &mut fence_val); + let got4 = read_u32s(&ctx, &mut fence_val, &dst_buf, &readback, COUNT); + let reset_errs = take_debug_errors(iq.as_ref()); + assert!(reset_errs.is_empty(), "Reset reuse D3D12 debug errors: {reset_errs:#?}"); + assert_eq!(got4[6], src_vals[6], "reset_x must clear prior predication so dst[6] executes"); + + drop(list); + drop(queue); + let _ = uma.free(uma_ptr as usize); + } + + if let Some(q1) = iq1 { + unsafe { + let _ = q1.UnregisterMessageCallback(cookie); + } + } +}