diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..6a95828e45 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2729,10 +2729,74 @@ unsafe fn reset_own_alloc(list: *mut c_void) { } } +#[cfg(test)] +thread_local! { + /// Tests: making a split's next segment fails (as it can when the device is out of memory). + static NO_NEW_SEGMENT: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: the Reset that opens a split's next segment fails. + static SEGMENT_RESET_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// A closed PC list of type `ty` for a split's next segment when `wrapper` has no spare. +unsafe fn next_segment_list(dev: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { + #[cfg(test)] + if NO_NEW_SEGMENT.with(|f| f.get()) { + return None; + } + real::create_closed_pc_command_list(dev, ty) +} + +/// A PC list of type `ty` recording on `alloc`, for a split's next segment whose Reset failed. +unsafe fn fallback_segment_list(dev: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE, alloc: usize, init_pso: usize) -> Option<*mut c_void> { + #[cfg(test)] + if NO_NEW_SEGMENT.with(|f| f.get()) { + return None; + } + real::create_raw_pc_command_list(dev, ty, super::alloc_pool::current(alloc), init_pso) +} + +/// Resets `next` onto `alloc` for a split's next segment. +unsafe fn reset_segment(next: *mut c_void, alloc: usize, ty: D3D12_COMMAND_LIST_TYPE, init_pso: usize) -> i32 { + #[cfg(test)] + if SEGMENT_RESET_FAILS.with(|f| f.get()) { + return 0x8000_4005u32 as i32; + } + super::alloc_pool::reset_list(next as usize, alloc, ty.0, |pc_alloc| { + pc:: i32>(next, PC_RESET)(next, pc_alloc, init_pso) + }) +} + +/// Records `p` empty and closed on `alloc`, to take a place in a recording; false: it could not be. +unsafe fn record_empty(p: *mut c_void, alloc: usize, ty: D3D12_COMMAND_LIST_TYPE) -> bool { + let ext = *(p as *const usize); + let hr = reset_segment(p, alloc, ty, 0); + real::preserve_vtable(p, ext); + if hr < 0 { + return false; + } + reset_copy_scratch(p); + let hr = pc:: i32>(p, PC_CLOSE)(p); + real::preserve_vtable(p, ext); + hr >= 0 +} + +/// What XCL tracks of the list `from` goes to `to`, which takes its place in a recording. +fn move_list_state(from: usize, to: usize) { + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + let Some(s) = m.remove(&from) else { return }; + if let Some(mut old) = m.insert(to, s) { + old.clear_sparse_writes(); + old.clear_write64_signals(); + old.clear_waits(); + } +} + /// Ends `list`'s segment and opens the next; with `dispatch`, a closed segment for it comes between. unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_void> { let wrapper = super::title_list::wrapper_of(list)?; - if !super::title_list::can_split(wrapper, 1 + dispatch.is_some() as usize) { + // (a list whose Close failed records for nothing; its Close fails again) + if !super::title_list::can_split(wrapper, 1 + dispatch.is_some() as usize) || super::title_list::close_failed(wrapper, list) { return None; } let ty = list_type(list); @@ -2750,12 +2814,21 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } None => None, }; + // the next segment is had while `list` still records: without one `list` stays open and the + // title records on in it (a closed `list` would lose what comes after, its Write64s too) + let dev = device_of(list)?; + let dev_raw = dev.as_raw() as usize; + let Some(next) = super::title_list::pop_spare(wrapper).or_else(|| next_segment_list(dev.as_raw(), ty)) else { + static CREATE_ERR: AtomicU64 = AtomicU64::new(0); + warn(&CREATE_ERR, "mid-list split", format_args!("CreateCommandList1 failed; the list records on unsplit")); + return None; + }; let (alloc, last_queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, ended_early, written_ranges, bindings) = { let mut g = LISTS.lock().unwrap(); - let s = g.as_mut()?.get_mut(&(list as usize))?; - if s.allocator == 0 { + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(list as usize))).filter(|s| s.allocator != 0) else { + super::title_list::put_spare(wrapper, next); return None; - } + }; let active_query = s.occlusion.end_active_early(); let ended_early = std::mem::take(&mut s.occlusion.ended_early); let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); @@ -2789,9 +2862,34 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ let close_hr = pc:: i32>(list, PC_CLOSE)(list); real::preserve_vtable(list, ext); if close_hr < 0 { + // a list whose Close failed removes the device when it is submitted, and no Reset opens + // it again: a closed, empty list takes its place in the recording with what XCL keeps of + // it (its waits, Write64 signals and CPU writes; what it recorded for the GPU is lost), + // and the recording goes on in `next` (the failed list does not hold the allocator) static CLOSE_ERR: AtomicU64 = AtomicU64::new(0); - warn(&CLOSE_ERR, "mid-list split", format_args!("Close failed ({close_hr:#x})")); - return None; + let stand = super::title_list::pop_spare(wrapper).or_else(|| next_segment_list(dev.as_raw(), ty)); + let goes_on = stand.is_some(); + let stand = stand.unwrap_or(next); + // (a list made closed is no submittable recording until it is Reset) + if !record_empty(stand, alloc, ty) { + super::title_list::release_segment(stand); + if goes_on { + super::title_list::put_spare(wrapper, next); + } + // (the failed list still leaves the submission; what XCL keeps of it goes with it) + super::title_list::replace_failed(wrapper, list, None); + warn(&CLOSE_ERR, "mid-list split", format_args!("Close failed ({close_hr:#x}), and no list could take its place; the recording is lost")); + return None; + } + move_list_state(list as usize, stand as usize); + super::title_textures::list_reset(list as usize); + super::title_list::replace_failed(wrapper, list, Some(stand)); + if !goes_on { + // (with no list to go on in, the title records on in the failed one, for nothing) + warn(&CLOSE_ERR, "mid-list split", format_args!("Close failed ({close_hr:#x}); the rest of the recording is lost")); + return None; + } + warn(&CLOSE_ERR, "mid-list split", format_args!("Close failed ({close_hr:#x}); what the list recorded before the split is lost")); } let init_pso = if ty == D3D12_COMMAND_LIST_TYPE_COPY { @@ -2799,31 +2897,25 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } else { super::pso_async::resolve(bound_pso) }; - let dev = device_of(list)?; - let dev_raw = dev.as_raw() as usize; - let mut next_pc: Option<*mut c_void> = None; - if let Some(spare) = super::title_list::pop_spare(wrapper) { - let ext_spare = *(spare as *const usize); - let reset_hr = super::alloc_pool::reset_list(spare as usize, alloc, ty.0, |pc_alloc| { - pc:: i32>(spare, PC_RESET)(spare, pc_alloc, init_pso) - }); - real::preserve_vtable(spare, ext_spare); - if reset_hr >= 0 { - reset_copy_scratch(spare); - next_pc = Some(spare); - } - } - let next_pc = match next_pc { - Some(p) => p, - None => match real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(alloc), init_pso) { + // (the allocator backs one recording at a time: `next` opens on it only now `list` is closed) + let ext_next = *(next as *const usize); + let reset_hr = reset_segment(next, alloc, ty, init_pso); + real::preserve_vtable(next, ext_next); + let next_pc = if reset_hr >= 0 { + reset_copy_scratch(next); + next + } else { + // (a list whose Reset failed is not used again: it is released, and the segment made anew) + super::title_list::release_segment(next); + match fallback_segment_list(dev.as_raw(), ty, alloc, init_pso) { Some(p) => p, None => { - static CREATE_ERR: AtomicU64 = AtomicU64::new(0); - warn(&CREATE_ERR, "mid-list split", format_args!("CreateCommandList failed")); + static RESET_ERR: AtomicU64 = AtomicU64::new(0); + warn(&RESET_ERR, "mid-list split", format_args!("Reset ({reset_hr:#x}) and CreateCommandList failed")); return None; } - }, + } }; // the next segment is a recording of its own (reset or made here, not through `cl_reset`) @@ -7233,6 +7325,359 @@ mod tests { } } + /// A mid-list Wait after a Write64 whose split cannot make a next segment leaves the list + /// recording: what the title records after it reaches the GPU. Before, the split closed the + /// list first, and what came after a failed CreateCommandList went into a closed list (#1452). + #[test] + fn a_split_without_a_next_segment_leaves_the_list_recording() { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + unsafe { + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let a = alloc.as_raw() as usize; + let primary = dev.CreateCommandList::<_, _, ID3D12GraphicsCommandList>(0, ty, &alloc, None).unwrap().into_raw(); + real::adopt(primary, real::Kind::CommandList); + on_create(primary, a, 0, ty); + super::super::bind::reset(primary, a, 0); + let w = super::super::title_list::wrap(primary); + let slot = |i: usize| *(*(w as *const *const usize)).add(i); + let close: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(slot(9)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(slot(2)); + let segments = || { + let mut s = Vec::new(); + assert!(super::super::title_list::push_segments(w, &mut s)); + s + }; + + let mut rb: Option = None; + 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, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).unwrap(); + let rb = rb.unwrap(); + let mark = |list: *mut c_void, at: u64, value: u32| { + type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, *const D3D12_WRITEBUFFERIMMEDIATE_MODE); + let p = D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: rb.GetGPUVirtualAddress() + at, Value: value }; + pc::(list, PC_WRITE_BUFFER_IMMEDIATE)(list, 1, &p, &D3D12_WRITEBUFFERIMMEDIATE_MODE_DEFAULT); + }; + // the cells waited for hold their values already: the waits are met at the submit + let cells = Box::new([AtomicU64::new(0), AtomicU64::new(1), AtomicU64::new(0), AtomicU64::new(1)]); + let va = |i: usize| &cells[i] as *const AtomicU64 as u64; + let ge = D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32; + + // Write64, then a Wait64 on another cell: the split finds no next segment + note_write64_recorded(primary, va(0), 1); + NO_NEW_SEGMENT.with(|f| f.set(true)); + wait64_x(primary, va(1), ge, 1, 0, 0); + NO_NEW_SEGMENT.with(|f| f.set(false)); + assert_eq!(segments(), vec![primary], "no split without a next segment"); + mark(primary, 0, 0x1452); + + // the same with a next segment to be had: it is made closed and opened after the Close + note_write64_recorded(primary, va(2), 1); + wait64_x(primary, va(3), ge, 1, 0, 0); + let split = segments(); + assert_eq!(split.len(), 2); + assert_eq!(split[0], primary); + mark(split[1], 4, 0x2733); + + assert_eq!(close(w), 0, "the title's Close finds its list recording"); + let segs = segments(); + execute_with_waits_on(q.as_raw(), &segs, |chunk| { + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let exec: ExecFn = std::mem::transmute(*(*(q.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); + exec(q.as_raw(), chunk.len() as u32, chunk.as_ptr()); + signal_write64_fences(q.as_raw(), chunk); + }); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + q.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 5000).expect("the queue finishes"); + assert!(dev.GetDeviceRemovedReason().is_ok()); + + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let got = [*(p as *const u32), *(p as *const u32).add(1)]; + rb.Unmap(0, None); + assert_eq!(got, [0x1452, 0x2733], "what was recorded after each Wait ran on the GPU"); + let g = SYNC_GRAPH.lock().unwrap(); + for i in [0, 2] { + assert_eq!(g.as_ref().unwrap().cells.get(&va(i)).map(|c| c.submitted_max), Some(1), "Write64 {i} submitted"); + } + drop(g); + + assert_eq!(release(w), 0); + if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { + for i in 0..4 { + gr.cells.remove(&va(i)); + } + } + } + } + + /// A split whose next segment fails its Reset releases that list, once, whether the segment + /// made in its place is had or not (before, the list was dropped without a Release). + #[test] + fn a_split_whose_next_segment_fails_its_reset_releases_that_list_once() { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + unsafe { + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let a = alloc.as_raw() as usize; + let primary = dev.CreateCommandList::<_, _, ID3D12GraphicsCommandList>(0, ty, &alloc, None).unwrap().into_raw(); + real::adopt(primary, real::Kind::CommandList); + on_create(primary, a, 0, ty); + super::super::bind::reset(primary, a, 0); + let w = super::super::title_list::wrap(primary); + let release_w: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(w as *const *const usize)).add(2)); + let slot = |p: *mut c_void, i: usize| *(*(p as *const *const usize)).add(i); + // a spare the split takes as its next segment, with a reference of the test's own + let spare = || { + let p = real::create_closed_pc_command_list(dev.as_raw(), ty).expect("a closed list"); + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(slot(p, 1)); + assert_eq!(add_ref(p), 2); + super::super::title_list::put_spare(w, p); + p + }; + let refs_left = |p: *mut c_void| { + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(slot(p, 2)); + release(p) + }; + + // the segment made in its place is had + let s1 = spare(); + SEGMENT_RESET_FAILS.with(|f| f.set(true)); + let next = split(primary, None); + SEGMENT_RESET_FAILS.with(|f| f.set(false)); + let next = next.expect("a segment made in place of the one whose Reset failed"); + assert_ne!(next, s1); + assert_eq!(refs_left(s1), 0, "the split released the list whose Reset failed, once"); + + // it is not + let s2 = spare(); + SEGMENT_RESET_FAILS.with(|f| f.set(true)); + NO_NEW_SEGMENT.with(|f| f.set(true)); + let none = split(next, None); + NO_NEW_SEGMENT.with(|f| f.set(false)); + SEGMENT_RESET_FAILS.with(|f| f.set(false)); + assert!(none.is_none()); + assert_eq!(refs_left(s2), 0, "the split released the list whose Reset failed, once"); + + assert_eq!(release_w(w), 0); + } + } + + /// A direct list of a title wrapper, its queue and allocator, and a readback buffer for + /// `mark` (Err: why the test cannot run here). + unsafe fn split_close_rig() -> Result<(ID3D12Device, ID3D12CommandQueue, ID3D12CommandAllocator, *mut c_void, *mut c_void, ID3D12Resource), &'static str> { + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + let dev = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0).map_err(|_| "no GPU")?; + if !close_refuses_open_query(&dev) { + return Err("Close does not refuse an open pipeline-statistics query"); + } + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let a = alloc.as_raw() as usize; + let primary = dev.CreateCommandList::<_, _, ID3D12GraphicsCommandList>(0, ty, &alloc, None).unwrap().into_raw(); + real::adopt(primary, real::Kind::CommandList); + on_create(primary, a, 0, ty); + super::super::bind::reset(primary, a, 0); + let w = super::super::title_list::wrap(primary); + let mut rb: Option = None; + 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, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).unwrap(); + Ok((dev, q, alloc, primary, w, rb.unwrap())) + } + + /// Whether the runtime refuses to Close a list of its own with a query begun as `refuse_close` + /// does (vkd3d-proton under Wine records it and closes the list: #2622). + unsafe fn close_refuses_open_query(dev: &ID3D12Device) -> bool { + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let mut heap: Option = None; + dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, Count: 1, NodeMask: 0 }, &mut heap).unwrap(); + list.BeginQuery(heap.as_ref().unwrap(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); + list.Close().is_err() + } + + /// The PC lists `w`'s submit runs. + fn segments_of(w: *mut c_void) -> Vec<*mut c_void> { + let mut s = Vec::new(); + assert!(super::super::title_list::push_segments(w, &mut s)); + s + } + + /// Writes `value` at `at` of `rb` on the GPU, recorded on `list`. + unsafe fn mark(list: *mut c_void, rb: &ID3D12Resource, at: u64, value: u32) { + type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, *const D3D12_WRITEBUFFERIMMEDIATE_MODE); + let p = D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: rb.GetGPUVirtualAddress() + at, Value: value }; + pc::(list, PC_WRITE_BUFFER_IMMEDIATE)(list, 1, &p, &D3D12_WRITEBUFFERIMMEDIATE_MODE_DEFAULT); + } + + /// Submits `segs` on `q` as the title's ExecuteCommandLists does and waits for the GPU: false + /// when the device was removed. + unsafe fn submit_segments(dev: &ID3D12Device, q: &ID3D12CommandQueue, segs: &[*mut c_void]) -> bool { + execute_with_waits_on(q.as_raw(), segs, |chunk| { + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let exec: ExecFn = std::mem::transmute(*(*(q.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); + exec(q.as_raw(), chunk.len() as u32, chunk.as_ptr()); + signal_write64_fences(q.as_raw(), chunk); + }); + let Ok(done) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return false }; + q.Signal(&done, 1).is_ok() && crate::gpu::fence::wait(&done, 1, dev, None, 5000).is_ok() && dev.GetDeviceRemovedReason().is_ok() + } + + /// Makes the native Close of `list` fail, as a recording the runtime refuses does: a pipeline + /// statistics query begun and not ended (XCL ends only occlusion queries at a split). + unsafe fn refuse_close(dev: &ID3D12Device, list: *mut c_void) -> ID3D12QueryHeap { + let mut heap: Option = None; + dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, Count: 1, NodeMask: 0 }, &mut heap).unwrap(); + let heap = heap.unwrap(); + pc::(list, PC_BEGIN_QUERY)(list, heap.as_raw() as usize, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); + heap + } + + /// A mid-list split whose Close fails does not submit the list it could not close (that + /// removes the device): a closed list takes its place with its Write64 signal, the recording + /// goes on in the next segment, and the title's next Reset records on another list, since + /// the failed one cannot be Reset. Before, the failed list stayed in the recording. + #[test] + fn a_split_whose_close_fails_leaves_that_list_out_and_goes_on() { + unsafe { + let (dev, q, alloc, primary, w, rb) = match split_close_rig() { + Ok(r) => r, + Err(why) => return crate::gpu::recomp::runner::skip_test(why), + }; + let slot = |i: usize| *(*(w as *const *const usize)).add(i); + let close: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(slot(9)); + let reset: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(slot(10)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(slot(2)); + let cells = Box::new([AtomicU64::new(0), AtomicU64::new(1)]); + let va = |i: usize| &cells[i] as *const AtomicU64 as u64; + let ge = D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32; + + mark(primary, &rb, 0, 0x1111); + let _heap = refuse_close(&dev, primary); + note_write64_recorded(primary, va(0), 1); + wait64_x(primary, va(1), ge, 1, 0, 0); + let segs = segments_of(w); + assert_eq!(segs.len(), 2, "the split went on"); + assert!(!segs.contains(&primary), "the list whose Close failed is not submitted"); + mark(segs[1], &rb, 4, 0x2733); + assert_eq!(close(w), 0, "the title's Close finds its list recording"); + + assert!(submit_segments(&dev, &q, &segments_of(w)), "the device stays"); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let got = [*(p as *const u32), *(p as *const u32).add(1)]; + rb.Unmap(0, None); + assert_eq!(got, [0, 0x2733], "what was recorded after the split ran on the GPU"); + let submitted = SYNC_GRAPH.lock().unwrap().as_ref().unwrap().cells.get(&va(0)).map(|c| c.submitted_max); + assert_eq!(submitted, Some(1), "the failed list's Write64 was signalled in its place"); + + // the next recording: the primary cannot be Reset, another list records + assert_eq!(reset(w, alloc.as_raw() as usize, 0), 0); + let segs = segments_of(w); + assert_eq!(segs.len(), 1); + assert_ne!(segs[0], primary); + mark(segs[0], &rb, 8, 0x3344); + assert_eq!(close(w), 0); + assert!(submit_segments(&dev, &q, &segments_of(w)), "the device stays"); + + assert_eq!(release(w), 0); + if let Some(g) = SYNC_GRAPH.lock().unwrap().as_mut() { + for i in 0..2 { + g.cells.remove(&va(i)); + } + } + } + } + + /// A mid-list split whose Close fails with no list to go on in still leaves the failed list + /// out of the submission: the title records on in it, for nothing, and its Close fails. + #[test] + fn a_split_whose_close_fails_without_a_list_to_go_on_in_submits_none_of_it() { + unsafe { + let (dev, q, _alloc, primary, w, _rb) = match split_close_rig() { + Ok(r) => r, + Err(why) => return crate::gpu::recomp::runner::skip_test(why), + }; + let slot = |i: usize| *(*(w as *const *const usize)).add(i); + let close: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(slot(9)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(slot(2)); + // the next segment is a spare; none is had in place of the failed list + let spare = real::create_closed_pc_command_list(dev.as_raw(), D3D12_COMMAND_LIST_TYPE_DIRECT).expect("a closed list"); + super::super::title_list::put_spare(w, spare); + let _heap = refuse_close(&dev, primary); + NO_NEW_SEGMENT.with(|f| f.set(true)); + let next = split(primary, None); + NO_NEW_SEGMENT.with(|f| f.set(false)); + assert!(next.is_none()); + assert_eq!(segments_of(w), vec![spare], "the spare stands in the failed list's place"); + assert!(close(w) < 0, "the title's Close reports the failure"); + assert!(submit_segments(&dev, &q, &segments_of(w)), "the device stays"); + assert_eq!(release(w), 0); + } + } + + /// A mid-list split whose Close fails, where no list can even be recorded empty in its place + /// (the only spare's Reset fails), still leaves the failed list out of the submission, and the + /// title's further splits on it stop at once. Before, the failed list stayed in the recording. + #[test] + fn a_split_whose_close_fails_with_no_list_in_its_place_submits_none_of_it() { + unsafe { + let (dev, q, _alloc, primary, w, _rb) = match split_close_rig() { + Ok(r) => r, + Err(why) => return crate::gpu::recomp::runner::skip_test(why), + }; + let slot = |i: usize| *(*(w as *const *const usize)).add(i); + let close: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(slot(9)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(slot(2)); + let spare = real::create_closed_pc_command_list(dev.as_raw(), D3D12_COMMAND_LIST_TYPE_DIRECT).expect("a closed list"); + super::super::title_list::put_spare(w, spare); + let _heap = refuse_close(&dev, primary); + NO_NEW_SEGMENT.with(|f| f.set(true)); + SEGMENT_RESET_FAILS.with(|f| f.set(true)); + let next = split(primary, None); + SEGMENT_RESET_FAILS.with(|f| f.set(false)); + assert!(next.is_none()); + assert_eq!(segments_of(w), vec![], "the list whose Close failed is not submitted"); + NO_NEW_SEGMENT.with(|f| f.set(false)); + let spare2 = real::create_closed_pc_command_list(dev.as_raw(), D3D12_COMMAND_LIST_TYPE_DIRECT).expect("a closed list"); + super::super::title_list::put_spare(w, spare2); + assert!(split(primary, None).is_none(), "no split goes on from the failed list"); + assert_eq!(segments_of(w), vec![]); + assert!(close(w) < 0, "the title's Close reports the failure"); + assert!(submit_segments(&dev, &q, &segments_of(w)), "the device stays"); + assert_eq!(release(w), 0); + } + } + /// A buffer outside unified memory that has a mirror is bound at its mirror again without /// asking whether the title's memory is readable: the source made unreadable after the first /// bind still binds the same mirror (before, the bind asked `readable` first and gave the diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..4beebf1a29 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3190,6 +3190,30 @@ pub(super) unsafe fn create_raw_pc_command_list( }; (hr >= 0 && !out.is_null()).then_some(out) } + +/// Create a raw adopted PC `ID3D12GraphicsCommandList` closed and on no allocator +/// (CreateCommandList1), for a mid-list split's next segment made while the list it follows records. +pub(super) unsafe fn create_closed_pc_command_list(dev: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { + if dev.is_null() { + return None; + } + let iid = layout::parse_guid(layout::find("ID3D12GraphicsCommandList")?.iid); + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = if is_ext(vt(dev) as usize) { + dev_create_command_list1(dev, 0, ty.0 as usize, 0, &iid, &mut out) + } else { + let dev4 = ID3D12Device::from_raw_borrowed(&dev)?.cast::().ok()?; + match dev4.CreateCommandList1::(0, ty, D3D12_COMMAND_LIST_FLAG_NONE) { + Ok(l) => { + out = l.into_raw(); + adopt(out, Kind::CommandList); + 0 + } + Err(e) => e.code().0, + } + }; + (hr >= 0 && !out.is_null()).then_some(out) +} creator!(dev_create_descriptor_heap, "CreateDescriptorHeap", Kind::DescriptorHeap, [a1]); creator!(dev_create_committed_resource, "CreateCommittedResource", Kind::Resource, [a1, a2, a3, a4, a5]); creator!(dev_create_committed_resource1, "CreateCommittedResource1", Kind::Resource, [a1, a2, a3, a4, a5, a6]); diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index a41e5643fc..190e29d3f6 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -48,8 +48,16 @@ struct SegmentBook { spares: Vec, /// A PC command list recording in place of `primary`: at the title's Reset the GPU had not /// finished primary's last submit, and the PC does not let a list be submitted again before - /// that (#1452, debug layer id 553). A console does. + /// that (#1452, debug layer id 553). A console does. Also the closed list in the place of a + /// primary whose Close failed (`replace_failed`). first: Option, + /// `primary`'s Close failed: no Reset opens it again, so the title's Reset records on another list. + primary_broken: bool, + /// Other PC lists of the wrapper whose Close failed: never submitted or reused, released with it. + unresettable: Vec, + /// The recording's first list (`first`, else `primary`) failed its Close and no list stands + /// in: the submission leaves it out until the title's next Reset. + first_out: bool, } /// Wrapper address -> split segment book (populated lazily only for lists that split). @@ -149,12 +157,14 @@ unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { /// (calling directly rather than through the dual-dispatch vtable thunk so console state always /// resets even though this wrapper sits in `xcl.exe`), restores `F_BACKING = F_PRIMARY`, and moves /// any extra split segments into the per-list spare pool. While the GPU has not finished -/// primary's last submit, the new recording goes onto a spare instead (`first`). The newer console -/// layout's Reset (#139) reaches it through `list_x::reset_x` on the active PC list. +/// primary's last submit, or when primary's Close failed, the new recording goes onto a spare +/// instead (`first`). The newer console layout's Reset (#139) reaches it through +/// `list_x::reset_x` on the active PC list. pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: usize) -> HRESULT { let primary = *((this as usize + F_PRIMARY) as *const *mut c_void); let adopted = super::real::is_adopted(primary); - let stand_in = if adopted && super::alloc_pool::in_flight(primary as usize) { + let primary_broken = SEGMENTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).is_some_and(|b| b.primary_broken); + let stand_in = if adopted && (primary_broken || super::alloc_pool::in_flight(primary as usize)) { super::list_x::reset_stand_in(this, primary, alloc, pso) } else { None @@ -177,6 +187,7 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: let b = m.entry(this as usize).or_default(); let mut old = std::mem::take(&mut b.extra_active); old.extend(std::mem::replace(&mut b.first, stand_in)); + b.first_out = false; b.spares.extend(old.iter().copied()); old } else { @@ -252,7 +263,9 @@ pub fn push_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { }; let sg = SEGMENTS.lock().unwrap(); let book = sg.as_ref().and_then(|m| m.get(&(list as usize))); - out.push(book.and_then(|b| b.first).map_or(primary, |f| f as *mut c_void)); + if !book.is_some_and(|b| b.first_out) { + out.push(book.and_then(|b| b.first).map_or(primary, |f| f as *mut c_void)); + } if let Some(book) = book { for &seg in &book.extra_active { out.push(seg as *mut c_void); @@ -292,6 +305,54 @@ pub(super) fn put_spare(wrapper: *mut c_void, pc: *mut c_void) { sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().spares.push(pc as usize); } +/// Release a PC list that was to be a split segment and will not be (its Reset failed), as +/// `release` does the segments of a recording. +pub(super) unsafe fn release_segment(pc: *mut c_void) { + if let Some(m) = WRAPPER_OF.lock().unwrap().as_mut() { + m.remove(&(pc as usize)); + } + super::bind::forget(pc); + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(pc, 2)); + rel(pc); +} + +/// The closed list `stand` takes the place of `failed`, a list of `wrapper`'s recording whose Close +/// failed: submitted, `failed` would remove the device, and it cannot be Reset to be used again. +/// With no `stand`, `failed` only leaves the recording. It is kept only to be released with the +/// wrapper (the primary is that anyway). +pub(super) fn replace_failed(wrapper: *mut c_void, failed: *mut c_void, stand: Option<*mut c_void>) { + let primary = unsafe { *((wrapper as usize + F_PRIMARY) as *const usize) }; + let (failed, stand) = (failed as usize, stand.map(|s| s as usize)); + let mut sg = SEGMENTS.lock().unwrap(); + let b = sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default(); + if !b.first_out && (b.first == Some(failed) || (b.first.is_none() && failed == primary)) { + b.first = stand; + b.first_out = stand.is_none(); + } else if let Some(k) = b.extra_active.iter().position(|&p| p == failed) { + match stand { + Some(s) => b.extra_active[k] = s, + None => { + b.extra_active.remove(k); + } + } + } else { + return; + } + if failed == primary { + b.primary_broken = true; + } else { + b.unresettable.push(failed); + } +} + +/// Whether `pc`, a list of `wrapper`, is one whose Close failed (`replace_failed`). +pub(super) fn close_failed(wrapper: *mut c_void, pc: *mut c_void) -> bool { + let primary = unsafe { *((wrapper as usize + F_PRIMARY) as *const usize) }; + let pc = pc as usize; + let sg = SEGMENTS.lock().unwrap(); + sg.as_ref().and_then(|m| m.get(&(wrapper as usize))).is_some_and(|b| b.unresettable.contains(&pc) || (pc == primary && b.primary_broken)) +} + /// Add the closed segment `pc` to `wrapper`'s recording, after the ones it has. pub(super) fn push_segment(wrapper: *mut c_void, pc: *mut c_void) { SEGMENTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().extra_active.push(pc as usize); @@ -405,14 +466,14 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { if let Some(m) = wg.as_mut() { m.remove(&(pc as usize)); if let Some(ref b) = book { - for &seg in b.extra_active.iter().chain(b.spares.iter()).chain(b.first.iter()) { + for &seg in b.extra_active.iter().chain(b.spares.iter()).chain(b.first.iter()).chain(b.unresettable.iter()) { m.remove(&seg); } } } } if let Some(b) = book { - for seg in b.extra_active.into_iter().chain(b.spares.into_iter()).chain(b.first) { + for seg in b.extra_active.into_iter().chain(b.spares.into_iter()).chain(b.first).chain(b.unresettable) { let raw = seg as *mut c_void; super::bind::forget(raw); let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(raw, 2)); @@ -453,6 +514,56 @@ mod tests { this as u64 + a + 10 * b + 100 * c + 1000 * d } + /// A list whose Close failed leaves the recording for the closed list in its place, the + /// primary as the recording's first list too, or just leaves it when no list is in its place, + /// and is released once, with the wrapper. + #[test] + fn a_list_whose_close_failed_gives_its_place_and_goes_with_the_wrapper() { + let mut vt = vec![0usize; LIST_SLOTS]; + vt[0] = fake_qi as usize; + vt[1] = fake_add_ref as usize; + vt[2] = fake_release as usize; + let fake = || Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + let [primary, seg, stand, stand2, seg2, primary2] = [fake(), fake(), fake(), fake(), fake(), fake()]; + let p = |f: *mut Fake| f as *mut c_void; + unsafe { + let o = wrap(p(primary)); + let segs = |o| { + let mut s = Vec::new(); + assert!(push_segments(o, &mut s)); + s + }; + replace_failed(o, p(primary), Some(p(stand))); + assert_eq!(segs(o), vec![p(stand)]); + activate_segment(o, p(primary), p(seg)); + replace_failed(o, p(seg), Some(p(stand2))); + assert_eq!(segs(o), vec![p(stand), p(stand2)]); + // with no list to stand in, the failed one only leaves the recording + activate_segment(o, p(seg), p(seg2)); + replace_failed(o, p(seg2), None); + assert_eq!(segs(o), vec![p(stand), p(stand2)]); + { + let books = SEGMENTS.lock().unwrap(); + let b = &books.as_ref().unwrap()[&(o as usize)]; + assert!(b.primary_broken); + assert_eq!(b.unresettable, vec![seg as usize, seg2 as usize]); + } + assert!(close_failed(o, p(primary)) && close_failed(o, p(seg2))); + assert!(!close_failed(o, p(stand2))); + let o2 = wrap(p(primary2)); + replace_failed(o2, p(primary2), None); + assert_eq!(segs(o2), vec![], "a failed first list with nothing in its place is not submitted"); + assert!(close_failed(o2, p(primary2))); + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(o as *const *const usize)).add(2)); + assert_eq!(rel(o), 0); + assert_eq!(rel(o2), 0); + for f in [primary, seg, stand, stand2, seg2, primary2] { + assert_eq!((*f).refs, 0, "released once"); + drop(Box::from_raw(f)); + } + } + } + /// The SDK's inline writers check `write < end` (or `write + n <= end`): never room here. #[test] fn console_list_objects_have_no_room_and_forward_to_the_pc_list() {