From d8ddd5b5636efd543dc9e575ba4f68f30081751c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Mon, 23 Nov 2026 19:19:03 -0500 Subject: [PATCH 001/265] D3D12.X: title texture uploads run on the submitting queue, without a CPU wait title_textures::refresh runs on the title's thread before each of its submits and uploaded the CPU's writes to its textures on XCL's own queue, then waited on the CPU until the GPU had run them (texture::upload_batch). While a retail title streams its world with video memory past the card, those waits are long: thread dumps show its submit thread blocked in fence::wait under refresh, presents drop to a few per 20 s, and the title's watchdog ends it on the loading screen. When the submitting queue is a DIRECT queue on the texture's device, the upload list now runs on that queue, ahead of the title's lists, so the GPU orders the copies before the work that samples them, with no cross-queue wait. A fence on that queue retires each batch's allocator, list and staging buffers at later submits; over 512 MB in flight the oldest batches are waited for, and a batch whose wait fails or times out stays in flight. Compute and copy queues, and a queue of another device, keep the upload queue and its wait. texture::submit_batch is upload_batch without the wait. --- crates/xcl/src/gpu/texture.rs | 58 ++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 259 ++++++++++++++++---- 2 files changed, 263 insertions(+), 54 deletions(-) diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index cde3561492..e3fa9fa1a4 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -278,19 +278,7 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items None => Uploader::new(dev)?, }; // where each texture's texels go in the upload buffer - let mut failed = Vec::new(); - let mut planned = Vec::with_capacity(items.len()); - let mut total = 0u64; - for (k, (res, subs, states)) in items.iter().enumerate() { - match layout(dev, res, subs, states, states) { - Ok(l) => { - let base = total.div_ceil(PLACEMENT) * PLACEMENT; - total = base + l.total; - planned.push((k, l, base)); - } - Err(e) => failed.push((k, e)), - } - } + let (failed, planned, total) = plan_batch(dev, items); if planned.is_empty() { put_back(key, up); return Ok(failed); @@ -317,6 +305,50 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items Ok(failed) } +unsafe fn plan_batch(dev: &ID3D12Device, items: &[(ID3D12Resource, Vec, Vec)]) -> (Vec<(usize, String)>, Vec<(usize, Layout, u64)>, u64) { + let mut failed = Vec::new(); + let mut planned = Vec::with_capacity(items.len()); + let mut total = 0u64; + for (k, (res, subs, states)) in items.iter().enumerate() { + match layout(dev, res, subs, states, states) { + Ok(l) => { + let base = total.div_ceil(PLACEMENT) * PLACEMENT; + total = base + l.total; + planned.push((k, l, base)); + } + Err(e) => failed.push((k, e)), + } + } + (failed, planned, total) +} + +pub struct InFlight { + _alloc: ID3D12CommandAllocator, + _list: ID3D12GraphicsCommandList, + _staging: ID3D12Resource, + pub bytes: u64, +} + +pub unsafe fn submit_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result<(Vec<(usize, String)>, Option), String> { + let (failed, planned, bytes) = plan_batch(dev, items); + if planned.is_empty() { + return Ok((failed, None)); + } + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(err)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; + let staging = buffer(dev, bytes)?; + let mut mapped = std::ptr::null_mut(); + staging.Map(0, None, Some(&mut mapped)).map_err(err)?; + for (k, layout, base) in &planned { + let (res, subs, states) = &items[*k]; + record_into(&list, res, subs, layout, states, states, &staging, mapped as *mut u8, *base); + } + staging.Unmap(0, None); + list.Close().map_err(err)?; + queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]); + Ok((failed, Some(InFlight { _alloc: alloc, _list: list, _staging: staging, bytes }))) +} + fn put_back(key: usize, up: Uploader) { UPLOADERS.lock().unwrap().get_or_insert_with(Default::default).insert(key, up); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6d97bc6e4e..3aa863a15d 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -827,7 +827,7 @@ unsafe fn refresh_once(queue: *mut c_void) { .collect() }); seed_stream_recheck(&todo, &ranges, recheck_frame); - upload_all(todo); + upload_all(todo, ID3D12CommandQueue::from_raw_borrowed(&queue)); } /// texture → `content_hash` of its memory at its last upload @@ -1087,8 +1087,79 @@ fn batch_fits(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_d && picked_bytes.saturating_add(next_bytes) <= BATCH_BYTES) } +struct QueueUploads { + fence: ID3D12Fence, + value: u64, + in_flight: std::collections::VecDeque<(u64, texture::InFlight)>, + bytes: u64, +} + +unsafe impl Send for QueueUploads {} + +static ON_QUEUE: Mutex> = Mutex::new(BTreeMap::new()); + +const IN_FLIGHT_BYTES: u64 = 512 << 20; + +unsafe fn title_queue_for(dev: &ID3D12Device, title: Option<&ID3D12CommandQueue>) -> Option { + let q = title?; + if q.GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT { + return None; + } + let mut qd: Option = None; + q.GetDevice(&mut qd).ok()?; + (qd?.as_raw() == dev.as_raw()).then(|| q.clone()) +} + +unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u32) { + let done = q.fence.GetCompletedValue(); + while q.in_flight.front().is_some_and(|&(v, _)| v <= done) { + let (_, f) = q.in_flight.pop_front().unwrap(); + q.bytes -= f.bytes; + } + while q.bytes > cap { + let Some(&(v, _)) = q.in_flight.front() else { break }; + if crate::gpu::fence::wait(&q.fence, v, dev, None, wait_ms).is_err() { + break; + } + let (_, f) = q.in_flight.pop_front().unwrap(); + q.bytes -= f.bytes; + } +} + +unsafe fn submit_on_title_queue(dev: &ID3D12Device, queue: &ID3D12CommandQueue, batch: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { + let (failed, f) = texture::submit_batch(dev, queue, batch)?; + let Some(f) = f else { return Ok(failed) }; + let mut g = ON_QUEUE.lock().unwrap(); + let key = queue.as_raw() as usize; + if !g.contains_key(&key) { + match dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { + Ok(fence) => { + g.insert(key, QueueUploads { fence, value: 0, in_flight: std::collections::VecDeque::new(), bytes: 0 }); + } + Err(e) => { + texture::wait(dev, queue)?; + drop(f); + return Err(e.to_string()); + } + } + } + let q = g.get_mut(&key).unwrap(); + q.value += 1; + if let Err(e) = queue.Signal(&q.fence, q.value) { + q.value -= 1; + texture::wait(dev, queue)?; + drop(f); + return Err(e.to_string()); + } + q.bytes += f.bytes; + let v = q.value; + q.in_flight.push_back((v, f)); + reclaim(dev, q, IN_FLIGHT_BYTES, 10_000); + Ok(failed) +} + /// The uploads `todo`, in batches of up to `BATCH_BYTES` and `BATCH_ITEMS` (one list and one wait each). -unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { +unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12CommandQueue>) { static N: AtomicU64 = AtomicU64::new(0); let warn = |e: &str| { if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -1140,6 +1211,18 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { } let d = device as *mut c_void; let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; + if let Some(tq) = title_queue_for(dev, title) { + match own_work(|| submit_on_title_queue(dev, &tq, &batch)) { + Ok(failed) => { + for (_, e) in failed { + warn(&e); + } + UPLOADS.fetch_add(batch.len() as u64, Ordering::Relaxed); + } + Err(e) => warn(&e), + } + continue; + } let queue = match upload_queue(dev, device) { Ok(q) => q, Err(e) => { @@ -1517,6 +1600,139 @@ mod tests { forget(b); } + unsafe fn read_r8(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) -> Vec { + own_work(|| { + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0; + dev.GetCopyableFootprints(&texture.GetDesc(), 0, 1, 0, Some(&mut footprint), None, None, Some(&mut total)); + let mut readback = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }, + D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback, + ).unwrap(); + let readback: ID3D12Resource = readback.unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let barrier = |before, after| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(texture), Subresource: 0, StateBefore: before, StateAfter: after }) }, + ..Default::default() + }; + list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, dev, None, 5_000).unwrap(); + let mut data = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut data)).unwrap(); + let mut out = Vec::with_capacity(64 * 64); + for y in 0..64 { + out.extend_from_slice(std::slice::from_raw_parts((data as *const u8).add(footprint.Offset as usize + y * footprint.Footprint.RowPitch as usize), 64)); + } + readback.Unmap(0, None); + out + }) + } + + #[test] + fn gpu_uploads_on_the_title_queue_run_before_its_later_work_and_are_released() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let compute: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + assert!(title_queue_for(dev, Some(&queue)).is_some()); + assert!(title_queue_for(dev, Some(&compute)).is_none()); + assert!(title_queue_for(dev, None).is_none()); + let mut texture = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let key = queue.as_raw() as usize; + let upload = |value: u8| { + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![value; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + }; + for value in [0x21, 0xC4] { + upload(value); + assert_eq!(read_r8(dev, &queue, &texture), vec![value; 64 * 64], "the title queue's next work sees the upload"); + } + upload(0x5E); + { + let mut g = ON_QUEUE.lock().unwrap(); + let q = g.get_mut(&key).unwrap(); + assert_eq!(q.value, 3); + reclaim(dev, q, 0, 10_000); + assert!(q.in_flight.is_empty() && q.bytes == 0, "over the cap the oldest uploads are waited for and released"); + assert!(q.fence.GetCompletedValue() >= 3); + } + assert_eq!(read_r8(dev, &queue, &texture), vec![0x5E; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + + #[test] + fn gpu_an_upload_still_running_is_kept_when_its_wait_times_out() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + let mut texture = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let key = queue.as_raw() as usize; + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x77; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + { + let mut g = ON_QUEUE.lock().unwrap(); + let q = g.get_mut(&key).unwrap(); + reclaim(dev, q, 0, 50); + assert_eq!(q.in_flight.len(), 1, "a batch the GPU has not run stays in flight when its wait times out"); + assert!(q.bytes > 0); + } + gate.Signal(1).unwrap(); + { + let mut g = ON_QUEUE.lock().unwrap(); + let q = g.get_mut(&key).unwrap(); + reclaim(dev, q, 0, 10_000); + assert!(q.in_flight.is_empty() && q.bytes == 0); + } + assert_eq!(read_r8(dev, &queue, &texture), vec![0x77; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + /// Real uploads, dirty-page detection and a source changing after registration: /// bookkeeping alone cannot show that the bytes the GPU sees follow the mirror. #[test] @@ -1565,45 +1781,6 @@ mod tests { assert!(kernelx::in_graphics_reservation(at), "fallback must be write-watched"); reservation } - unsafe fn read_r8(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) -> Vec { - own_work(|| { - let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); - let mut total = 0; - dev.GetCopyableFootprints(&texture.GetDesc(), 0, 1, 0, Some(&mut footprint), None, None, Some(&mut total)); - let mut readback = None; - dev.CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, - &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }, - D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback, - ).unwrap(); - let readback: ID3D12Resource = readback.unwrap(); - let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); - let barrier = |before, after| D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, - Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(texture), Subresource: 0, StateBefore: before, StateAfter: after }) }, - ..Default::default() - }; - list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); - let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint } }; - let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; - list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); - list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); - list.Close().unwrap(); - queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); - queue.Signal(&fence, 1).unwrap(); - crate::gpu::fence::wait(&fence, 1, dev, None, 5_000).unwrap(); - let mut data = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut data)).unwrap(); - let mut out = Vec::with_capacity(64 * 64); - for y in 0..64 { - out.extend_from_slice(std::slice::from_raw_parts((data as *const u8).add(footprint.Offset as usize + y * footprint.Footprint.RowPitch as usize), 64)); - } - readback.Unmap(0, None); - out - }) - } unsafe { let raw_device = super::super::real::device_raw(); let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); From e12049fe984eb4f14ae715ae629223288c04f873 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 13:55:12 -0800 Subject: [PATCH 002/265] D3D12.X: a title-queue texture upload waits for the page mappings first With uploads on the title's queue (the commit before), the copies of a batch went out on that queue without the wait for texture page mappings that XCL's own upload queue makes (vram::before_execute). A texture made on another thread after refresh_once's wait, or its levels mapped just before the upload by map_levels_with_texels, could then be copied into tiles whose UpdateTileMappings had not run on the page queue yet. On an RTX 3080 (driver 621.40) with a retail title that was a copy-engine write page fault (DmaPageFaultWrite, EngineResetRequired, 4.6 ms before VidSchErrorHardwarePageFault in a DxgKrnl trace) and a hung device (0x887a0006 with nvlddmkm 153) in 3 of 4 runs of the world load; with the wait, 0 of 7. submit_on_title_queue now waits first, so every title-queue upload does. The test fails without it (the queue never waits for the mapping). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 47 +++++++++++++++++++++ crates/xcl/src/hle/d3d12x/vram.rs | 19 +++++++++ 2 files changed, 66 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 3aa863a15d..25a71253ea 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1127,6 +1127,11 @@ unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u } unsafe fn submit_on_title_queue(dev: &ID3D12Device, queue: &ID3D12CommandQueue, batch: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { + // The textures' tile mappings made since the title queue last waited for them (a texture + // made on another thread after `refresh_once`'s wait, or its levels mapped just now by + // `map_levels_with_texels`): a copy into a tile still unmapped is a copy-engine page fault + // on NVIDIA (`DmaPageFaultWrite`), as the upload queue's own path already waits for. + super::vram::before_execute(queue); let (failed, f) = texture::submit_batch(dev, queue, batch)?; let Some(f) = f else { return Ok(failed) }; let mut g = ON_QUEUE.lock().unwrap(); @@ -1688,6 +1693,48 @@ mod tests { } } + /// An upload on the title's queue waits there for the texture page mappings made before it, + /// as one on XCL's upload queue does: without the wait its copy can run into tiles whose + /// mapping has not run yet (a copy-engine write page fault on NVIDIA). + #[test] + fn gpu_a_title_queue_upload_waits_for_the_page_mappings_before_it() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let Some(mapped) = super::super::vram::note_mapping_for_test(dev) else { + crate::gpu::recomp::runner::skip_test("no texture pages on this device"); + return; + }; + let key = queue.as_raw() as usize; + assert!(super::super::vram::waited_for_test(raw_device as usize, key) < mapped); + let mut texture = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x3C; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + assert_eq!( + super::super::vram::waited_for_test(raw_device as usize, key), + mapped, + "the title queue's upload must wait for the page mappings made before it" + ); + assert_eq!(read_r8(dev, &queue, &texture), vec![0x3C; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + #[test] fn gpu_an_upload_still_running_is_kept_when_its_wait_times_out() { use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index ea49ce6b89..59582fa641 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1233,6 +1233,25 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { #[cfg(test)] pub(super) static VRAM_TEST_LOCK: Mutex<()> = Mutex::new(()); +/// A tile mapping on `dev`'s page queue, as `map` leaves it (the fence advanced and signalled +/// there): the value a queue must wait for before work that uses the pages. None: no pages on +/// this device (no tiled resources). +#[cfg(test)] +pub(super) unsafe fn note_mapping_for_test(dev: &ID3D12Device) -> Option { + let mut g = PAGES.lock().unwrap(); + let pages = g.entry(dev.as_raw() as usize).or_insert_with(|| Pages::new(dev)).as_mut()?; + pages.value += 1; + pages.queue.Signal(&pages.fence, pages.value).ok()?; + Some(pages.value) +} + +/// The page mapping value `queue` was last made to wait for on `dev` (`before_execute`). +#[cfg(test)] +pub(super) fn waited_for_test(dev: usize, queue: usize) -> u64 { + let g = PAGES.lock().unwrap(); + g.get(&dev).and_then(|p| p.as_ref()).and_then(|p| p.waited.get(&queue).copied()).unwrap_or(0) +} + /// Tile identities of one mapped resource: title pages, then extra pages. /// A device-wide byte count also falls when unrelated idle pages are swept. #[cfg(test)] From dab895e5448d2b08efe0f23f3b0ba3c28ac7da7a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 19:56:08 -0800 Subject: [PATCH 003/265] D3D12.X: add an opt-in stall attribution core Establish shared, bounded stall accounting before instrumenting runtime paths. Disabled spans perform one relaxed enable check and avoid clocks, allocation, locking, and counters. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/host.rs | 4 + crates/xcl/src/lib.rs | 1 + crates/xcl/src/stall.rs | 295 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 300 insertions(+) create mode 100644 crates/xcl/src/stall.rs diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 444333d891..c20049322c 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -31,6 +31,10 @@ pub fn host_main(boot_path: &Path) -> i32 { boot.config.title_memory_mb, boot.config.title_memory ); + if std::env::var_os("XCL_STALL_TRACE").is_some() { + crate::stall::enable(); + crate::xlog_info!("stall attribution enabled (XCL_STALL_TRACE)"); + } if std::env::var_os("XCL_UMA_MB").is_none() && boot.config.uma_mb != 0 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index b6bc0d2ec8..df5aada1b7 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -30,6 +30,7 @@ mod rpf_probe; pub mod shaders; #[cfg(test)] mod source_hash; +pub mod stall; pub mod state; pub mod stubs; pub mod tls; diff --git a/crates/xcl/src/stall.rs b/crates/xcl/src/stall.rs new file mode 100644 index 0000000000..8a7f68c461 --- /dev/null +++ b/crates/xcl/src/stall.rs @@ -0,0 +1,295 @@ +//! Opt-in attribution of time spent in coarse runtime operations. +//! +//! A disabled span is one relaxed atomic load. In particular, it does not read the clock, allocate, +//! lock, or update a counter. Callers should keep spans coarse enough that enabled tracing remains +//! useful diagnostics rather than becoming the workload. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +pub const HISTOGRAM_BUCKETS: usize = 64; +pub const SLOW_SPAN_CAPACITY: usize = 128; +pub const SLOW_SPAN_NS: u64 = 50_000_000; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum StallKind { + ShaderTranslation, + DxcQueue, + DxcCompile, + PipelineWait, + DriverCompileGate, + DriverCompile, + SubmitPreparation, + MemorySynchronization, + Residency, + CacheIo, + LockContention, + GpuWait, + Present, + DirectStorage, +} + +impl StallKind { + pub const ALL: [Self; 14] = [ + Self::ShaderTranslation, + Self::DxcQueue, + Self::DxcCompile, + Self::PipelineWait, + Self::DriverCompileGate, + Self::DriverCompile, + Self::SubmitPreparation, + Self::MemorySynchronization, + Self::Residency, + Self::CacheIo, + Self::LockContention, + Self::GpuWait, + Self::Present, + Self::DirectStorage, + ]; + + const fn index(self) -> usize { + self as usize + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct AggregateSnapshot { + pub kind: StallKind, + pub count: u64, + pub total_ns: u64, + pub max_ns: u64, + /// Duration counts in base-2 nanosecond buckets. Bucket zero also contains zero-duration spans. + pub histogram: [u64; HISTOGRAM_BUCKETS], +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SlowSpan { + pub sequence: u64, + pub kind: StallKind, + pub started_ns: u64, + pub duration_ns: u64, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Snapshot { + pub aggregates: Vec, + pub slow_spans: Vec, +} + +struct Aggregate { + count: AtomicU64, + total_ns: AtomicU64, + max_ns: AtomicU64, + histogram: [AtomicU64; HISTOGRAM_BUCKETS], +} + +impl Aggregate { + const fn new() -> Self { + Self { + count: AtomicU64::new(0), + total_ns: AtomicU64::new(0), + max_ns: AtomicU64::new(0), + histogram: [const { AtomicU64::new(0) }; HISTOGRAM_BUCKETS], + } + } + + fn record(&self, duration_ns: u64) { + self.count.fetch_add(1, Ordering::Relaxed); + self.total_ns.fetch_add(duration_ns, Ordering::Relaxed); + self.max_ns.fetch_max(duration_ns, Ordering::Relaxed); + self.histogram[histogram_bucket(duration_ns)].fetch_add(1, Ordering::Relaxed); + } + + fn snapshot(&self, kind: StallKind) -> AggregateSnapshot { + AggregateSnapshot { + kind, + count: self.count.load(Ordering::Relaxed), + total_ns: self.total_ns.load(Ordering::Relaxed), + max_ns: self.max_ns.load(Ordering::Relaxed), + histogram: std::array::from_fn(|i| self.histogram[i].load(Ordering::Relaxed)), + } + } +} + +const fn histogram_bucket(duration_ns: u64) -> usize { + if duration_ns == 0 { 0 } else { (u64::BITS - 1 - duration_ns.leading_zeros()) as usize } +} + +struct SlowSpans { + next_sequence: u64, + spans: VecDeque, +} + +struct Recorder { + enabled: AtomicBool, + aggregates: [Aggregate; StallKind::ALL.len()], + slow_spans: Mutex, +} + +trait Clock: Sync { + fn now_ns(&self) -> u64; +} + +impl Recorder { + const fn new() -> Self { + Self { + enabled: AtomicBool::new(false), + aggregates: [const { Aggregate::new() }; StallKind::ALL.len()], + slow_spans: Mutex::new(SlowSpans { next_sequence: 0, spans: VecDeque::new() }), + } + } + + fn enable(&self) { + self.enabled.store(true, Ordering::Relaxed); + } + + #[inline] + fn start_with<'a>(&'a self, kind: StallKind, clock: &'a dyn Clock) -> Option> { + if !self.enabled.load(Ordering::Relaxed) { + return None; + } + Some(Span { recorder: self, kind, started_ns: clock.now_ns(), clock, finished: false }) + } + + fn record(&self, kind: StallKind, started_ns: u64, duration_ns: u64) { + self.aggregates[kind.index()].record(duration_ns); + if duration_ns < SLOW_SPAN_NS { + return; + } + let mut slow = self.slow_spans.lock().unwrap_or_else(|e| e.into_inner()); + let span = SlowSpan { + sequence: slow.next_sequence, + kind, + started_ns, + duration_ns, + }; + slow.next_sequence = slow.next_sequence.wrapping_add(1); + if slow.spans.len() == SLOW_SPAN_CAPACITY { + slow.spans.pop_front(); + } + slow.spans.push_back(span); + } + + fn snapshot(&self) -> Snapshot { + let aggregates = StallKind::ALL.iter().map(|&kind| self.aggregates[kind.index()].snapshot(kind)).collect(); + let slow_spans = self.slow_spans.lock().unwrap_or_else(|e| e.into_inner()).spans.iter().copied().collect(); + Snapshot { aggregates, slow_spans } + } +} + +pub struct Span<'a> { + recorder: &'a Recorder, + kind: StallKind, + started_ns: u64, + clock: &'a dyn Clock, + finished: bool, +} + +impl Drop for Span<'_> { + fn drop(&mut self) { + if !self.finished { + self.finished = true; + self.recorder.record(self.kind, self.started_ns, self.clock.now_ns().saturating_sub(self.started_ns)); + } + } +} + +static RECORDER: Recorder = Recorder::new(); +static CLOCK: SystemClock = SystemClock; + +pub fn enable() { + RECORDER.enable(); +} + +#[inline] +pub fn span(kind: StallKind) -> Option> { + RECORDER.start_with(kind, &CLOCK) +} + +pub fn snapshot() -> Snapshot { + RECORDER.snapshot() +} + +struct SystemClock; + +impl Clock for SystemClock { + fn now_ns(&self) -> u64 { + static ORIGIN: OnceLock = OnceLock::new(); + ORIGIN.get_or_init(Instant::now).elapsed().as_nanos().min(u64::MAX as u128) as u64 + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, AtomicUsize}; + + struct TestClock { + now: AtomicU64, + calls: AtomicUsize, + } + + impl TestClock { + fn new(now: u64) -> Self { + Self { now: AtomicU64::new(now), calls: AtomicUsize::new(0) } + } + } + + impl Clock for TestClock { + fn now_ns(&self) -> u64 { + self.calls.fetch_add(1, Ordering::Relaxed); + self.now.load(Ordering::Relaxed) + } + } + + #[test] + fn disabled_span_does_not_read_the_clock_or_record() { + let recorder = Recorder::new(); + let clock = TestClock::new(10); + assert!(recorder.start_with(StallKind::DxcCompile, &clock).is_none()); + assert_eq!(clock.calls.load(Ordering::Relaxed), 0); + assert_eq!(recorder.snapshot().aggregates[StallKind::DxcCompile.index()].count, 0); + } + + #[test] + fn a_span_updates_its_aggregate_and_log2_bucket() { + let recorder = Recorder::new(); + recorder.enable(); + let clock = TestClock::new(10); + let span = recorder.start_with(StallKind::PipelineWait, &clock).unwrap(); + clock.now.store(10 + 1024, Ordering::Relaxed); + drop(span); + + let aggregate = &recorder.snapshot().aggregates[StallKind::PipelineWait.index()]; + assert_eq!((aggregate.count, aggregate.total_ns, aggregate.max_ns), (1, 1024, 1024)); + assert_eq!(aggregate.histogram[10], 1); + assert_eq!(aggregate.histogram.iter().sum::(), 1); + assert_eq!(clock.calls.load(Ordering::Relaxed), 2); + } + + #[test] + fn only_slow_spans_enter_the_bounded_ring() { + let recorder = Recorder::new(); + recorder.enable(); + let clock = TestClock::new(0); + for i in 0..SLOW_SPAN_CAPACITY + 3 { + clock.now.store(i as u64, Ordering::Relaxed); + let span = recorder.start_with(StallKind::GpuWait, &clock).unwrap(); + clock.now.store(i as u64 + SLOW_SPAN_NS, Ordering::Relaxed); + drop(span); + } + clock.now.store(1_000_000_000, Ordering::Relaxed); + let fast = recorder.start_with(StallKind::Present, &clock).unwrap(); + clock.now.store(1_000_000_001, Ordering::Relaxed); + drop(fast); + + let snapshot = recorder.snapshot(); + assert_eq!(snapshot.slow_spans.len(), SLOW_SPAN_CAPACITY); + assert_eq!(snapshot.slow_spans[0].sequence, 3); + assert!(snapshot.slow_spans.iter().all(|span| span.kind == StallKind::GpuWait)); + assert_eq!(snapshot.aggregates[StallKind::Present.index()].count, 1); + } +} From 62de4d55eeb850521e67664e5b5175ebef7bf2f4 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 19:56:09 -0800 Subject: [PATCH 004/265] D3D12.X: track exact command-list write intervals Replace capped approximate write ranges with canonical tree-backed intervals. This preserves unwritten gaps without the quadratic insertion cost of an unbounded sorted vector. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 159 +++++++++++++++++++++++++--- 1 file changed, 143 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..17f505c539 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -17,7 +17,7 @@ //! go to that window's buffer (`real::uma_window_buffer`), which is in COMMON between them. //! An index buffer at such an address is given to the PC as the window buffer's GPU address. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::ffi::c_void; use std::mem::{transmute_copy, ManuallyDrop}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; @@ -62,9 +62,6 @@ const WAIT_TIMEOUT: Duration = Duration::from_secs(2); /// cleanly without prematurely breaking synchronization. Overridable via `XCL_GPU_WAIT_TIMEOUT_MS` /// for diagnostics. const GPU_WAIT_WATCHDOG_TIMEOUT: Duration = Duration::from_millis(5000); -/// Cap on tracked per-list written UMA ranges (for same-list write-then-wait detection). -const MAX_WRITTEN_RANGES: usize = 256; - fn wait_timeout() -> Duration { static T: OnceLock = OnceLock::new(); *T.get_or_init(|| { @@ -607,6 +604,69 @@ unsafe fn restore_bindings(this: *mut c_void, b: &Bindings, ty: D3D12_COMMAND_LI } } +/// Canonical half-open UMA ranges written by one command-list recording. +/// +/// Keys are starts and values are exclusive ends. Overlapping and adjacent ranges are merged, +/// so lookup examines at most the predecessor and successor around the requested address. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct RecordedWrites { + ranges: BTreeMap, +} + +impl RecordedWrites { + fn insert(&mut self, va: u64, size: u64) { + if size == 0 { + return; + } + let mut start = va; + let mut end = va.saturating_add(size); + if end <= start { + return; + } + + if let Some((&previous_start, &previous_end)) = self.ranges.range(..=start).next_back() { + if previous_end >= start { + start = previous_start; + end = end.max(previous_end); + self.ranges.remove(&previous_start); + } + } + loop { + let next = self.ranges.range(start..).next().map(|(&s, &e)| (s, e)); + match next { + Some((next_start, next_end)) if next_start <= end => { + end = end.max(next_end); + self.ranges.remove(&next_start); + } + _ => break, + } + } + self.ranges.insert(start, end); + } + + fn overlaps(&self, va: u64, size: u64) -> bool { + if size == 0 { + return false; + } + let end = va.saturating_add(size); + if end <= va { + return false; + } + if self.ranges.range(..=va).next_back().is_some_and(|(_, &range_end)| range_end > va) { + return true; + } + self.ranges.range(va..).next().is_some_and(|(&range_start, _)| range_start < end) + } + + fn clear(&mut self) { + self.ranges.clear(); + } + + fn is_empty(&self) -> bool { + self.ranges.is_empty() + } +} + #[derive(Default)] struct ListState { allocator: usize, @@ -629,7 +689,7 @@ struct ListState { depth_bounds: Option<(f32, f32)>, occlusion: Occlusion, /// UMA address ranges written by this list since last Reset/KickoffX - written_ranges: Vec<(u64, u64)>, + written_ranges: RecordedWrites, /// Sparse-window `(va, bytes)` ranges written by memory ops (`Write32/64`, `Fill*`, /// `CopyMemoryToMemoryX`, timestamps) to copy back to the CPU view after execution. sparse_writes: Vec<(usize, usize)>, @@ -666,13 +726,7 @@ impl ListState { if size == 0 { return; } - let end = va.saturating_add(size); - if self.written_ranges.len() < MAX_WRITTEN_RANGES { - self.written_ranges.push((va, end)); - } else if let Some(last) = self.written_ranges.last_mut() { - last.0 = last.0.min(va); - last.1 = last.1.max(end); - } + self.written_ranges.insert(va, size); if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { if self.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); @@ -705,8 +759,7 @@ impl ListState { } fn has_prior_write(&self, va: u64, size: u64) -> bool { - let end = va.saturating_add(size); - self.written_ranges.iter().any(|&(s, e)| va < e && s < end) + self.written_ranges.overlaps(va, size) } fn clear_waits(&mut self) { @@ -4764,7 +4817,7 @@ mod tests { Format: DXGI_FORMAT_R32_UINT, }); s.depth_bounds = Some((0.25, 0.75)); - s.written_ranges.push((0x6000, 0x6010)); + s.written_ranges.insert(0x6000, 0x10); } super::super::bind::seed_reset_state_for_test(list, 0x111, 0x222, vec![0x4444]); RESET_TEST_REPLACEMENT_VT.store(replacement as u64, Ordering::SeqCst); @@ -4782,7 +4835,7 @@ mod tests { assert!(s.pso_dirty && s.using_fallback_pso); assert_eq!(s.index_buffer.as_ref().unwrap().BufferLocation, 0x5000); assert_eq!(s.depth_bounds, Some((0.25, 0.75))); - assert_eq!(s.written_ranges, vec![(0x6000, 0x6010)]); + assert_eq!(s.written_ranges.ranges, BTreeMap::from([(0x6000, 0x6010)])); } assert_eq!( super::super::bind::reset_state_for_test(list), @@ -4947,6 +5000,80 @@ mod tests { assert!(!s.has_prior_write(0x0FF8, 8)); } + #[test] + fn recorded_writes_merge_ascending_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 8); + writes.insert(0x1008, 8); + writes.insert(0x1010, 8); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1018)])); + } + + #[test] + fn recorded_writes_merge_descending_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1010, 8); + writes.insert(0x1008, 8); + writes.insert(0x1000, 8); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1018)])); + } + + #[test] + fn recorded_writes_merge_adjacent_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 4); + writes.insert(0x1008, 4); + writes.insert(0x1004, 4); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x100c)])); + } + + #[test] + fn recorded_writes_merge_overlapping_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1008, 0x10); + writes.insert(0x1000, 0x10); + writes.insert(0x1004, 0x20); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1024)])); + } + + #[test] + fn recorded_writes_keep_disjoint_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 8); + writes.insert(0x1020, 8); + writes.insert(0x1040, 8); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1008), (0x1020, 0x1028), (0x1040, 0x1048)])); + } + + #[test] + fn recorded_writes_handle_thousands_in_reverse_order() { + let mut writes = RecordedWrites::default(); + for i in (0..4096u64).rev() { + writes.insert(0x1000 + i * 16, 8); + } + assert_eq!(writes.ranges.len(), 4096); + for i in 0..4096u64 { + let va = 0x1000 + i * 16; + assert!(writes.overlaps(va, 8)); + assert!(!writes.overlaps(va + 8, 8)); + } + } + + #[test] + fn recorded_writes_preserve_gaps_when_bridging_neighbors() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 8); + writes.insert(0x1010, 8); + writes.insert(0x1020, 8); + assert!(!writes.overlaps(0x1008, 8)); + assert!(!writes.overlaps(0x1018, 8)); + + writes.insert(0x1008, 8); + assert!(writes.overlaps(0x1008, 8)); + assert!(!writes.overlaps(0x1018, 8)); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1018), (0x1020, 0x1028)])); + } + #[test] fn execute_with_waits_splits_batches_before_unsatisfied_list() { // Use synthetic non-zero list pointers distinct from real COM objects. From e7c522d80d99c7538728f062f71d254b4652c294 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 19:56:09 -0800 Subject: [PATCH 005/265] D3D12.X: add a priority build queue Add a preparation-only queue with stable job identities, monotonic promotion, FIFO priority ordering, pre-start cancellation, and panic-safe completion. Runtime paths are not activated yet. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/build_queue.rs | 379 +++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + 2 files changed, 380 insertions(+) create mode 100644 crates/xcl/src/hle/d3d12x/build_queue.rs diff --git a/crates/xcl/src/hle/d3d12x/build_queue.rs b/crates/xcl/src/hle/d3d12x/build_queue.rs new file mode 100644 index 0000000000..8d0816bf64 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/build_queue.rs @@ -0,0 +1,379 @@ +//! Priority queue shared by pipeline-preparation workers. +//! +//! This module is deliberately not connected to the runtime yet. It gives the DXC and PSO +//! migrations one queue with stable job identities, monotonic priority promotion and completion +//! that survives a panicking job or queue shutdown. + +#![allow(dead_code)] // Used by the following pipeline-preparation changes. + +use std::collections::{HashMap, VecDeque}; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::{Arc, Condvar, Mutex, Weak}; + +type Work = Box; + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +#[repr(u8)] +pub(super) enum Priority { + Speculative, + Preload, + BoundSoon, + Foreground, +} + +impl Priority { + const COUNT: usize = 4; + + fn index(self) -> usize { + self as usize + } +} + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub(super) struct JobId(u64); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum JobStatus { + Queued, + Running, + Complete, + Cancelled, + Panicked, +} + +impl JobStatus { + fn terminal(self) -> bool { + matches!(self, Self::Complete | Self::Cancelled | Self::Panicked) + } +} + +struct Completion { + status: Mutex, + changed: Condvar, +} + +impl Completion { + fn new() -> Self { + Self { status: Mutex::new(JobStatus::Queued), changed: Condvar::new() } + } + + fn set(&self, status: JobStatus) { + *self.status.lock().unwrap_or_else(|e| e.into_inner()) = status; + self.changed.notify_all(); + } + + fn get(&self) -> JobStatus { + *self.status.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn wait(&self) -> JobStatus { + let mut status = self.status.lock().unwrap_or_else(|e| e.into_inner()); + while !status.terminal() { + status = self.changed.wait(status).unwrap_or_else(|e| e.into_inner()); + } + *status + } +} + +pub(super) struct JobHandle { + id: JobId, + queue: Weak, + completion: Arc, +} + +impl JobHandle { + pub(super) fn id(&self) -> JobId { + self.id + } + + pub(super) fn status(&self) -> JobStatus { + self.completion.get() + } + + pub(super) fn wait(&self) -> JobStatus { + self.completion.wait() + } + + /// Raise this queued job to `priority`. Running and completed jobs cannot be promoted. + pub(super) fn promote(&self, priority: Priority) -> bool { + self.queue.upgrade().is_some_and(|q| q.promote(self.id, priority)) + } + + /// Cancel this job only if no worker has started it. + pub(super) fn cancel(&self) -> bool { + self.queue.upgrade().is_some_and(|q| q.cancel(self.id)) + } +} + +#[derive(Clone, Copy)] +struct Ticket { + id: JobId, + generation: u64, +} + +struct Job { + priority: Priority, + generation: u64, + work: Work, + completion: Arc, +} + +struct State { + next_id: u64, + stopped: bool, + jobs: HashMap, + ready: [VecDeque; Priority::COUNT], +} + +struct Inner { + state: Mutex, + changed: Condvar, +} + +impl Inner { + fn promote(&self, id: JobId, priority: Priority) -> bool { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + let Some(job) = state.jobs.get_mut(&id) else { return false }; + if priority <= job.priority { + return true; + } + job.priority = priority; + job.generation += 1; + let ticket = Ticket { id, generation: job.generation }; + state.ready[priority.index()].push_back(ticket); + self.changed.notify_one(); + true + } + + fn cancel(&self, id: JobId) -> bool { + let job = self.state.lock().unwrap_or_else(|e| e.into_inner()).jobs.remove(&id); + if let Some(job) = job { + job.completion.set(JobStatus::Cancelled); + true + } else { + false + } + } + + fn take(&self, wait: bool) -> Option<(Work, Arc)> { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + loop { + for priority in (0..Priority::COUNT).rev() { + while let Some(ticket) = state.ready[priority].pop_front() { + let current = state.jobs.get(&ticket.id).is_some_and(|job| { + job.priority.index() == priority && job.generation == ticket.generation + }); + if current { + let job = state.jobs.remove(&ticket.id).unwrap(); + job.completion.set(JobStatus::Running); + return Some((job.work, job.completion)); + } + } + } + if state.stopped || !wait { + return None; + } + state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + + fn shutdown(&self) { + let jobs = { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.stopped { + return; + } + state.stopped = true; + for ready in &mut state.ready { + ready.clear(); + } + std::mem::take(&mut state.jobs) + }; + for (_, job) in jobs { + job.completion.set(JobStatus::Cancelled); + } + self.changed.notify_all(); + } +} + +pub(super) struct BuildQueue { + inner: Arc, +} + +impl BuildQueue { + pub(super) fn new() -> Self { + Self { + inner: Arc::new(Inner { + state: Mutex::new(State { + next_id: 0, + stopped: false, + jobs: HashMap::new(), + ready: std::array::from_fn(|_| VecDeque::new()), + }), + changed: Condvar::new(), + }), + } + } + + /// Add work to the queue. A stopped queue refuses it without running it. + pub(super) fn submit(&self, priority: Priority, work: Work) -> Option { + let completion = Arc::new(Completion::new()); + let mut state = self.inner.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.stopped { + return None; + } + state.next_id = state.next_id.checked_add(1).expect("build queue job ID overflow"); + let id = JobId(state.next_id); + let generation = 0; + state.jobs.insert(id, Job { priority, generation, work, completion: completion.clone() }); + state.ready[priority.index()].push_back(Ticket { id, generation }); + drop(state); + self.inner.changed.notify_one(); + Some(JobHandle { id, queue: Arc::downgrade(&self.inner), completion }) + } + + pub(super) fn worker(&self) -> Worker { + Worker { inner: self.inner.clone() } + } + + /// Run one ready job on this thread, for callers that help drain a batch. + pub(super) fn try_run_one(&self) -> bool { + self.inner.take(false).is_some_and(|job| { + run(job); + true + }) + } + + pub(super) fn shutdown(&self) { + self.inner.shutdown(); + } +} + +impl Drop for BuildQueue { + fn drop(&mut self) { + self.inner.shutdown(); + } +} + +pub(super) struct Worker { + inner: Arc, +} + +impl Worker { + pub(super) fn run(self) { + while let Some(job) = self.inner.take(true) { + run(job); + } + } +} + +fn run((work, completion): (Work, Arc)) { + let status = if catch_unwind(AssertUnwindSafe(work)).is_ok() { JobStatus::Complete } else { JobStatus::Panicked }; + completion.set(status); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + + fn record(out: &Arc>>, value: u32) -> Work { + let out = out.clone(); + Box::new(move || out.lock().unwrap().push(value)) + } + + #[test] + fn highest_priority_runs_first_and_each_priority_is_fifo() { + let q = BuildQueue::new(); + let out = Arc::new(Mutex::new(Vec::new())); + q.submit(Priority::Speculative, record(&out, 1)).unwrap(); + q.submit(Priority::BoundSoon, record(&out, 2)).unwrap(); + q.submit(Priority::BoundSoon, record(&out, 3)).unwrap(); + q.submit(Priority::Foreground, record(&out, 4)).unwrap(); + q.submit(Priority::Preload, record(&out, 5)).unwrap(); + while q.try_run_one() {} + assert_eq!(*out.lock().unwrap(), [4, 2, 3, 5, 1]); + } + + #[test] + fn promotion_is_monotonic_and_joins_the_new_priority_fifo() { + let q = BuildQueue::new(); + let out = Arc::new(Mutex::new(Vec::new())); + q.submit(Priority::Foreground, record(&out, 1)).unwrap(); + let promoted = q.submit(Priority::Speculative, record(&out, 2)).unwrap(); + assert!(promoted.promote(Priority::Foreground)); + assert!(promoted.promote(Priority::Preload), "a lower request leaves it promoted"); + while q.try_run_one() {} + assert_eq!(*out.lock().unwrap(), [1, 2]); + } + + #[test] + fn job_ids_are_stable_and_not_reused() { + let q = BuildQueue::new(); + let a = q.submit(Priority::Preload, Box::new(|| {})).unwrap(); + let b = q.submit(Priority::Preload, Box::new(|| {})).unwrap(); + assert_ne!(a.id(), b.id()); + let id = a.id(); + assert!(a.cancel()); + assert_eq!(a.id(), id); + } + + #[test] + fn only_a_queued_job_can_be_cancelled() { + let q = BuildQueue::new(); + let cancelled = q.submit(Priority::Preload, Box::new(|| panic!("must not run"))).unwrap(); + assert!(cancelled.cancel()); + assert_eq!(cancelled.wait(), JobStatus::Cancelled); + + let running = Arc::new(AtomicBool::new(false)); + let finish = Arc::new((Mutex::new(false), Condvar::new())); + let (seen, gate) = (running.clone(), finish.clone()); + let handle = q.submit(Priority::Foreground, Box::new(move || { + seen.store(true, Ordering::Release); + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + })).unwrap(); + let worker = q.worker(); + let thread = std::thread::spawn(move || worker.run()); + while !running.load(Ordering::Acquire) { + std::thread::yield_now(); + } + assert_eq!(handle.status(), JobStatus::Running); + assert!(!handle.cancel()); + *finish.0.lock().unwrap() = true; + finish.1.notify_all(); + assert_eq!(handle.wait(), JobStatus::Complete); + q.shutdown(); + thread.join().unwrap(); + } + + #[test] + fn a_panicking_job_completes_and_the_worker_continues() { + let q = BuildQueue::new(); + let panicked = q.submit(Priority::Foreground, Box::new(|| panic!("expected"))).unwrap(); + let ran = Arc::new(AtomicBool::new(false)); + let mark = ran.clone(); + let after = q.submit(Priority::BoundSoon, Box::new(move || mark.store(true, Ordering::Release))).unwrap(); + assert!(q.try_run_one()); + assert_eq!(panicked.wait(), JobStatus::Panicked); + assert!(q.try_run_one()); + assert_eq!(after.wait(), JobStatus::Complete); + assert!(ran.load(Ordering::Acquire)); + } + + #[test] + fn shutdown_cancels_queued_work_and_wakes_workers() { + let q = BuildQueue::new(); + let a = q.submit(Priority::Foreground, Box::new(|| panic!("must not run"))).unwrap(); + let b = q.submit(Priority::Speculative, Box::new(|| panic!("must not run"))).unwrap(); + let worker = q.worker(); + q.shutdown(); + let thread = std::thread::spawn(move || worker.run()); + assert_eq!(a.wait(), JobStatus::Cancelled); + assert_eq!(b.wait(), JobStatus::Cancelled); + assert!(q.submit(Priority::Foreground, Box::new(|| {})).is_none()); + thread.join().unwrap(); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 8886624632..c4553b9395 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -10,6 +10,7 @@ #![allow(non_snake_case)] mod alloc_pool; +mod build_queue; pub mod bind; pub mod console_heap; pub mod console_list; From 0394b45a0c786594b4861aad58ec3bfbaf0abab2 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:01:53 -0800 Subject: [PATCH 006/265] Recompiler: attribute translation and DXC stalls Separate shader translation, DXC queue and memory-admission time, and actual DXC execution in the opt-in stall recorder. Structured translation fallback remains one attributed operation. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/dxc.rs | 25 ++++++++++++++++++++----- crates/xcl/src/gpu/recomp/mod.rs | 8 +++++++- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 379bd8518f..269c4d3069 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -391,6 +391,8 @@ struct Job { reply: std::sync::mpsc::Sender, String>>, /// one of the title's threads waits for it wanted: Wanted, + /// time from submission until a worker admits this compile under the memory limit + queue_stall: Option>, } /// Whether one of the title's threads waits for a compile (asked again while it is held back). @@ -477,11 +479,16 @@ fn pool() -> &'static std::sync::Mutex> { Ok(j) => j, Err(_) => return, }; - let _slot = wait_for_memory(&job.wanted); - let extra: Vec<&str> = job.extra.iter().map(|s| s.as_str()).collect(); - let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compile_here(&job.src, &job.entry, &job.profile, &extra))) + let Job { src, entry, profile, extra, reply, wanted, queue_stall } = job; + let _slot = wait_for_memory(&wanted); + drop(queue_stall); + let extra: Vec<&str> = extra.iter().map(|s| s.as_str()).collect(); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _stall = crate::stall::span(crate::stall::StallKind::DxcCompile); + compile_here(&src, &entry, &profile, &extra) + })) .unwrap_or_else(|_| Err("DXC: panic in the compile thread".into())); - let _ = job.reply.send(r); + let _ = reply.send(r); }); } std::sync::Mutex::new(tx) @@ -491,7 +498,15 @@ fn pool() -> &'static std::sync::Mutex> { /// Compile HLSL to signed DXIL. `profile` e.g. "cs_6_6"; `extra` are dxc arguments. pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { let (reply, rx) = std::sync::mpsc::channel(); - let job = Job { src: src.into(), entry: entry.into(), profile: profile.into(), extra: extra.iter().map(|s| s.to_string()).collect(), reply, wanted: crate::hle::d3d12x::pso_async::wanted_here() }; + let job = Job { + src: src.into(), + entry: entry.into(), + profile: profile.into(), + extra: extra.iter().map(|s| s.to_string()).collect(), + reply, + wanted: crate::hle::d3d12x::pso_async::wanted_here(), + queue_stall: crate::stall::span(crate::stall::StallKind::DxcQueue), + }; pool().lock().unwrap().send(job).map_err(|_| "DXC: no compile threads".to_string())?; rx.recv().map_err(|_| "DXC: the compile thread exited".to_string())? } diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 528493d6e5..6f7e1a1440 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1497,7 +1497,13 @@ pub(crate) fn needs_coherent_mem(insts: &[Decoded]) -> bool { }) } +#[inline] pub fn translate(code: &[u8], opt: &Options) -> Result { + let _stall = crate::stall::span(crate::stall::StallKind::ShaderTranslation); + translate_inner(code, opt) +} + +fn translate_inner(code: &[u8], opt: &Options) -> Result { let program = code; let normalized; let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { @@ -1609,7 +1615,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // smaller for DXC and the driver on big programs) emit_structured(&sctx, &mut em, &mut code, 0, u64::MAX, None, 0, &Conts::default(), &BTreeSet::new(), 1, &mut blocks, &mut flags); if code.len() > STRUCTURED_BYTES_PER_CODE_BYTE * program.len() { - return translate(program, &Options { structured: false, ..opt.clone() }); + return translate_inner(program, &Options { structured: false, ..opt.clone() }); } } else { if gs_jump.is_some() && opt.split_wave64 && opt.wave64 { From 1b0b589cf364c185f01d55b6fcf13c0d0216f3e7 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:01:54 -0800 Subject: [PATCH 007/265] D3D12.X: snapshot command-list effects before submit Capture waits, signals, sparse writes and deferred CPU writes once before submission. Split execution and post-submit consumers use the immutable snapshot instead of repeatedly reading mutable list state. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 245 ++++++++++++++++++++++------ crates/xcl/src/hle/d3d12x/real.rs | 16 +- 2 files changed, 204 insertions(+), 57 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 17f505c539..82c8488dc4 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -763,16 +763,10 @@ impl ListState { } fn clear_waits(&mut self) { - if !self.pending_waits.is_empty() { - self.pending_waits.clear(); - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - } + self.pending_waits.clear(); } fn push_wait(&mut self, w: PendingWait) { - if self.pending_waits.is_empty() { - PENDING_WAIT_LISTS.fetch_add(1, Ordering::AcqRel); - } self.pending_waits.push(w); } } @@ -786,8 +780,6 @@ struct QueueInfo { static LISTS: Mutex>> = Mutex::new(None); static LIVE_QUEUES: Mutex> = Mutex::new(Vec::new()); -/// Number of lists with at least one pending `Wait32/64BitValueX` (fast-path guard for ExecuteCommandLists). -static PENDING_WAIT_LISTS: AtomicUsize = AtomicUsize::new(0); /// Number of lists with recorded sparse-window memory writes (fast-path guard for post-execute readback). static SPARSE_WRITE_LISTS: AtomicUsize = AtomicUsize::new(0); /// Number of lists with recorded non-timestamp `Write64BitValue*` signals (fast-path guard). @@ -797,6 +789,63 @@ 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); +/// Immutable effects recorded by one physical command-list segment at submission planning time. +#[derive(Clone, Default)] +pub(super) struct SegmentEffects { + waits: Vec, + write64_signals: Vec<(u64, u64)>, + sparse_writes: Vec<(usize, usize)>, + cpu_writes: Vec, +} + +/// One queue submission's physical lists and their effects, kept in matching chronological order. +pub(super) struct SubmissionPlan { + lists: Vec<*mut c_void>, + effects: Vec, + has_waits: bool, +} + +impl SubmissionPlan { + fn capture(lists: &[*mut c_void]) -> Self { + if lists.is_empty() { + return Self { lists: Vec::new(), effects: Vec::new(), has_waits: false }; + } + let g = LISTS.lock().unwrap(); + let effects: Vec = lists + .iter() + .map(|&list| { + g.as_ref() + .and_then(|m| m.get(&(list as usize))) + .map(|s| SegmentEffects { + waits: s.pending_waits.clone(), + write64_signals: s.write64_signals.clone(), + sparse_writes: s.sparse_writes.clone(), + cpu_writes: s.cpu_writes.clone(), + }) + .unwrap_or_default() + }) + .collect(); + let has_waits = effects.iter().any(|e| !e.waits.is_empty()); + Self { lists: lists.to_vec(), effects, has_waits } + } +} + +#[derive(Clone, Copy)] +pub(super) struct SubmissionChunk<'a> { + lists: &'a [*mut c_void], + effects: &'a [SegmentEffects], +} + +impl<'a> SubmissionChunk<'a> { + pub(super) fn lists(self) -> &'a [*mut c_void] { + self.lists + } + + pub(super) unsafe fn submit_effects(self, queue: *mut c_void) { + submit_segment_effects(queue, self.effects); + } +} + /// Record a newly created title command queue so `KickoffX` can find a compatible queue. pub fn on_queue_create(queue: usize, device: usize, ty: D3D12_COMMAND_LIST_TYPE) { if queue == 0 { @@ -867,9 +916,6 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C let m = g.get_or_insert_with(HashMap::new); 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); - } if !old.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } @@ -903,9 +949,6 @@ pub(super) fn on_release(list: usize) { super::title_textures::list_reset(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); - } if !old.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } @@ -2142,43 +2185,60 @@ pub(super) unsafe fn cpu_writes_after(queue: *mut c_void, lists: &[*mut c_void]) super::cpu_writes::after(queue, writes); } -/// Submit `lists` through `submit`, splitting the batch before any list whose `Wait32/64BitValueX` -/// condition is not yet satisfied so earlier lists in the same batch can run on the GPU first. -/// When `queue` is non-null, monotonic 64-bit waits backed by a recorded `Write64BitValue*` are -/// bridged to GPU-side `queue.Wait` without blocking the submitter thread on the CPU. -pub(super) unsafe fn execute_with_waits_on(queue: *mut c_void, lists: &[*mut c_void], mut submit: impl FnMut(&[*mut c_void])) { - if lists.is_empty() || PENDING_WAIT_LISTS.load(Ordering::Acquire) == 0 { - submit(lists); +/// Capture every mutable per-list effect once, before any part of this submission reaches the +/// driver. Resetting or re-recording a list after this point cannot change the returned plan. +pub(super) fn submission_plan(lists: &[*mut c_void]) -> SubmissionPlan { + SubmissionPlan::capture(lists) +} + +/// Publish the effects of an already-submitted chunk in the same order as the legacy consumers. +unsafe fn submit_segment_effects(queue: *mut c_void, effects: &[SegmentEffects]) { + let write64_signals: Vec<(u64, u64)> = effects.iter().flat_map(|e| e.write64_signals.iter().copied()).collect(); + signal_write64_pairs(queue, &write64_signals); + + let sparse_writes: Vec<(usize, usize)> = effects.iter().flat_map(|e| e.sparse_writes.iter().copied()).collect(); + if !sparse_writes.is_empty() { + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { + super::sparse::readback_after_execute(q, &sparse_writes); + } + } + + let cpu_writes: Vec = effects.iter().flat_map(|e| e.cpu_writes.iter().cloned()).collect(); + super::cpu_writes::after(queue, cpu_writes); +} + +/// Execute an immutable submission plan, splitting before an unsatisfied memory wait. +pub(super) unsafe fn execute_submission_plan_on(queue: *mut c_void, plan: &SubmissionPlan, mut submit: impl FnMut(SubmissionChunk<'_>)) { + let chunk = |start, end| SubmissionChunk { lists: &plan.lists[start..end], effects: &plan.effects[start..end] }; + if !plan.has_waits { + submit(chunk(0, plan.lists.len())); return; } - let per_list: Vec<(Vec, Vec<(u64, u64)>)> = { - let g = LISTS.lock().unwrap(); - lists - .iter() - .map(|&l| { - g.as_ref() - .and_then(|m| m.get(&(l as usize))) - .map(|s| (s.pending_waits.clone(), s.write64_signals.clone())) - .unwrap_or_default() - }) - .collect() - }; let mut start = 0usize; - for (i, (waits, list_writes)) in per_list.iter().enumerate() { - if waits.is_empty() || waits.iter().all(|w| w.is_satisfied()) { + for (i, effects) in plan.effects.iter().enumerate() { + if effects.waits.is_empty() || effects.waits.iter().all(|w| w.is_satisfied()) { continue; } if i > start { - submit(&lists[start..i]); + submit(chunk(start, i)); } - wait_all_on(queue, waits, list_writes); + wait_all_on(queue, &effects.waits, &effects.write64_signals); start = i; } - if start < lists.len() { - submit(&lists[start..]); + if start < plan.lists.len() { + submit(chunk(start, plan.lists.len())); } } +/// Submit `lists` through `submit`, splitting the batch before any list whose `Wait32/64BitValueX` +/// condition is not yet satisfied so earlier lists in the same batch can run on the GPU first. +/// When `queue` is non-null, monotonic 64-bit waits backed by a recorded `Write64BitValue*` are +/// bridged to GPU-side `queue.Wait` without blocking the submitter thread on the CPU. +pub(super) unsafe fn execute_with_waits_on(queue: *mut c_void, lists: &[*mut c_void], mut submit: impl FnMut(&[*mut c_void])) { + let plan = submission_plan(lists); + execute_submission_plan_on(queue, &plan, |chunk| submit(chunk.lists())); +} + #[cfg(test)] pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], submit: impl FnMut(&[*mut c_void])) { execute_with_waits_on(std::ptr::null_mut(), lists, submit); @@ -2890,9 +2950,6 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ let m = g.get_or_insert_with(HashMap::new); let old = m.remove(&(next_pc as usize)); if let Some(ref o) = old { - if !o.pending_waits.is_empty() { - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - } if !o.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } @@ -3337,12 +3394,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { return; }; let active_query = s.occlusion.end_active_early(); - let waits = if s.pending_waits.is_empty() { - Vec::new() - } else { - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - std::mem::take(&mut s.pending_waits) - }; + let waits = std::mem::take(&mut s.pending_waits); let sparse_writes = s.clear_sparse_writes(); let write64_signals = s.clear_write64_signals(); s.written_ranges.clear(); @@ -5074,6 +5126,101 @@ mod tests { assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1018), (0x1020, 0x1028)])); } + #[test] + fn submission_plan_preserves_segment_and_effect_order() { + let lists = [0x7ffe_1001usize as *mut c_void, 0x7ffe_1002usize as *mut c_void, 0x7ffe_1003usize as *mut c_void]; + { + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + for (i, &list) in lists.iter().enumerate() { + m.insert( + list as usize, + ListState { + write64_signals: vec![(0x1000 + i as u64, 10 + i as u64)], + sparse_writes: vec![(0x2000 + i, 4 + i)], + cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x3000 + i, vec![i as u32])], + ..Default::default() + }, + ); + } + } + + let plan = SubmissionPlan::capture(&lists); + { + let mut g = LISTS.lock().unwrap(); + let m = g.as_mut().unwrap(); + for &list in &lists { + m.remove(&(list as usize)); + } + } + + assert_eq!(plan.lists, lists); + for (i, effects) in plan.effects.iter().enumerate() { + assert_eq!(effects.write64_signals, vec![(0x1000 + i as u64, 10 + i as u64)]); + assert_eq!(effects.sparse_writes, vec![(0x2000 + i, 4 + i)]); + match effects.cpu_writes.as_slice() { + [super::super::cpu_writes::Write::Immediate(va, words)] => assert_eq!((*va, words.as_slice()), (0x3000 + i, &[i as u32][..])), + _ => panic!("unexpected CPU write snapshot"), + } + } + } + + #[test] + fn submission_plan_is_isolated_from_reset_and_rerecord() { + let list = 0x7ffe_2001usize as *mut c_void; + let old_wait = PendingWait { va: 0x4000, width: 8, comparison: 7, value: 4, mask: u64::MAX, after_write64: true }; + { + let mut g = LISTS.lock().unwrap(); + g.get_or_insert_with(HashMap::new).insert( + list as usize, + ListState { + pending_waits: vec![old_wait], + write64_signals: vec![(0x4000, 4)], + sparse_writes: vec![(0x5000, 8)], + cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x6000, vec![4])], + ..Default::default() + }, + ); + } + let plan = SubmissionPlan::capture(&[list]); + + { + let mut g = LISTS.lock().unwrap(); + let state = g.as_mut().unwrap().get_mut(&(list as usize)).unwrap(); + state.pending_waits = vec![PendingWait { value: 9, ..old_wait }]; + state.write64_signals = vec![(0x4000, 9)]; + state.sparse_writes = vec![(0x7000, 16)]; + state.cpu_writes = vec![super::super::cpu_writes::Write::Immediate(0x8000, vec![9])]; + } + + let effects = &plan.effects[0]; + assert_eq!(effects.waits, vec![old_wait]); + assert_eq!(effects.write64_signals, vec![(0x4000, 4)]); + assert_eq!(effects.sparse_writes, vec![(0x5000, 8)]); + match effects.cpu_writes.as_slice() { + [super::super::cpu_writes::Write::Immediate(va, words)] => assert_eq!((*va, words.as_slice()), (0x6000, &[4][..])), + _ => panic!("unexpected CPU write snapshot"), + } + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + } + + #[test] + fn empty_submission_plan_uses_the_lock_free_fast_path() { + let lists_guard = LISTS.lock().unwrap(); + let plan = SubmissionPlan::capture(&[]); + drop(lists_guard); + assert!(plan.lists.is_empty() && plan.effects.is_empty() && !plan.has_waits); + + let mut submitted = 0; + unsafe { + execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| { + assert!(chunk.lists().is_empty()); + submitted += 1; + }); + } + assert_eq!(submitted, 1); + } + #[test] fn execute_with_waits_splits_batches_before_unsatisfied_list() { // Use synthetic non-zero list pointers distinct from real COM objects. diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..9cdcabfe22 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7277,14 +7277,14 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis } } super::list_x::note_queue_for_lists(this as usize, &mapped); - super::list_x::execute_with_waits_on(this, &mapped, |chunk| { - let _ = super::alloc_pool::note_resubmits(this, chunk); - f(this, chunk.len() as u32, chunk.as_ptr()); - super::list_x::copy_scratch_submitted(this, chunk); - super::alloc_pool::executed(this, chunk); - super::list_x::signal_write64_fences(this, chunk); - super::list_x::readback_sparse_writes(this, chunk); - super::list_x::cpu_writes_after(this, chunk); + let plan = super::list_x::submission_plan(&mapped); + super::list_x::execute_submission_plan_on(this, &plan, |chunk| { + let lists = chunk.lists(); + let _ = super::alloc_pool::note_resubmits(this, lists); + f(this, lists.len() as u32, lists.as_ptr()); + super::list_x::copy_scratch_submitted(this, lists); + super::alloc_pool::executed(this, lists); + chunk.submit_effects(this); }); // the next uploads into textures kept in step start from the states these lists leave super::title_textures::submitted(&mapped); From 6f6b5a272f143f4be1a2bc21c2b8af4b81634e49 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:01:54 -0800 Subject: [PATCH 008/265] D3D12.X: separate pipeline builds from stand-ins Move job, completion, demand and result ownership into a distinct Build shared by the title-visible Pending object. Every stand-in still has a unique build, preserving scheduling behavior while establishing safe ownership for later coalescing. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 205 ++++++++++++++----------- 1 file changed, 119 insertions(+), 86 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 63d62a7df4..a66e56f184 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -12,27 +12,33 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; struct Pending { - /// the build, until a worker – or a bind that cannot wait for the queue – takes it - job: Mutex>, - /// the build went to the workers (a lazy one goes on its first `resolve`) - sent: std::sync::atomic::AtomicBool, - /// the real pipeline state (raw pointer), 0 while building or when building failed - real: AtomicUsize, + build: Arc, /// the driver pipeline binds get till then (`shared`); 0: the stand-in is one itself driver: AtomicUsize, - done: Mutex, - cv: Condvar, compute: bool, /// of its shaders (`used`); 0 = none key: u64, /// it was used (`used::note` is told once) used: std::sync::atomic::AtomicBool, - /// the stand-in was released before the real pipeline was built - orphan: std::sync::atomic::AtomicBool, /// a bind waited for it longer than `wait_budget`: binds go on without it until it is built late: std::sync::atomic::AtomicBool, /// its dispatches may be left out while it is built (`image_only`): binds do not wait for it spared: std::sync::atomic::AtomicBool, +} + +/// A pipeline build independent of the title-visible stand-in that requested it. +/// Each `Pending` has a unique build for now; separating the ownership does not deduplicate work. +struct Build { + /// the build, until a worker – or a bind that cannot wait for the queue – takes it + job: Mutex>, + /// the build went to the workers (a lazy one goes on its first `resolve`) + sent: std::sync::atomic::AtomicBool, + /// the real pipeline state (raw pointer), 0 while building or when building failed + real: AtomicUsize, + done: Mutex, + cv: Condvar, + /// every stand-in interested in this build was released before it finished + orphan: std::sync::atomic::AtomicBool, demand: Mutex, } @@ -48,41 +54,41 @@ struct Demand { thread_local! { /// what this worker is building - static BUILDING: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + static BUILDING: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } /// This thread is a worker and one of the title's threads waits for what it is building: the /// build must not stand back for the title's sake (`real::big_compile_turn`). pub(super) fn build_is_wanted() -> bool { - BUILDING.with(|b| b.borrow().as_ref().is_some_and(|p| p.demand.lock().unwrap().wanted)) + BUILDING.with(|b| b.borrow().as_ref().is_some_and(|build| build.demand.lock().unwrap().wanted)) } /// Whether one of the title's threads waits for what this thread is doing, to be asked later and /// from another thread: a worker's build as `build_is_wanted`; a thread that is not XCL's is the /// title's own. pub fn wanted_here() -> crate::gpu::recomp::dxc::Wanted { - if let Some(p) = BUILDING.with(|b| b.borrow().clone()) { - return Box::new(move || p.demand.lock().unwrap().wanted); + if let Some(build) = BUILDING.with(|b| b.borrow().clone()) { + return Box::new(move || build.demand.lock().unwrap().wanted); } let own = crate::state::boot().is_some() && !std::thread::current().name().is_some_and(|n| n.starts_with("xcl-")); Box::new(move || own) } -/// A worker's build of `p` (`preload`: by one of the lowest-priority workers). -fn build(p: &Arc, job: Job, preload: bool) { +/// A worker's pipeline build (`preload`: by one of the lowest-priority workers). +fn run_build(build: &Arc, job: Job, preload: bool) { use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL}; - BUILDING.with(|b| *b.borrow_mut() = Some(p.clone())); + BUILDING.with(|b| *b.borrow_mut() = Some(build.clone())); if preload { - let mut d = p.demand.lock().unwrap(); + let mut d = build.demand.lock().unwrap(); d.preload_thread = unsafe { GetCurrentThreadId() }; if d.wanted { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } - complete(p, job()); + complete(build, job()); if preload { // (under the lock: `want` does not raise this thread after it) - let mut d = p.demand.lock().unwrap(); + let mut d = build.demand.lock().unwrap(); d.preload_thread = 0; if d.wanted { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST) }; @@ -91,7 +97,19 @@ fn build(p: &Arc, job: Job, preload: bool) { BUILDING.with(|b| *b.borrow_mut() = None); } -impl Pending { +impl Build { + fn new(job: Job, sent: bool) -> Self { + Self { + job: Mutex::new(Some(job)), + sent: std::sync::atomic::AtomicBool::new(sent), + real: AtomicUsize::new(0), + done: Mutex::new(false), + cv: Condvar::new(), + orphan: Default::default(), + demand: Default::default(), + } + } + /// One of the title's threads is about to wait for it: the worker building it goes on now, /// at a normal priority. fn want(&self) { @@ -108,7 +126,9 @@ impl Pending { } } } +} +impl Pending { fn note_use(&self) { if self.key != 0 && !self.used.swap(true, Ordering::Relaxed) { used::note(self.key); @@ -120,20 +140,20 @@ impl Pending { static PENDING: Mutex>>> = Mutex::new(None); /// The build is done (`real`: its pipeline, 0 = failed). -fn complete(p: &Pending, real: usize) { +fn complete(build: &Build, real: usize) { if real == 0 { FAILED.fetch_add(1, Ordering::Relaxed); } else { BUILT.fetch_add(1, Ordering::Relaxed); } let orphan = { - let mut done = p.done.lock().unwrap(); - let orphan = p.orphan.load(Ordering::Acquire); + let mut done = build.done.lock().unwrap(); + let orphan = build.orphan.load(Ordering::Acquire); if !orphan { - p.real.store(real, Ordering::Release); + build.real.store(real, Ordering::Release); } *done = true; - p.cv.notify_all(); + build.cv.notify_all(); orphan }; // outside `done`: the Release override takes PENDING (`counts` takes PENDING, then `done`) @@ -270,20 +290,20 @@ pub fn enabled() -> bool { pub type Job = Box usize + Send>; /// pipelines a submit will wait for: the workers take these before their queue (`need_by_submit`) -static NEEDED: Mutex>> = Mutex::new(std::collections::VecDeque::new()); +static NEEDED: Mutex>> = Mutex::new(std::collections::VecDeque::new()); -fn next_needed() -> Option> { +fn next_needed() -> Option> { NEEDED.lock().unwrap().pop_front() } /// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. -fn drop_unstarted_job(p: &Pending) { - let job = p.job.lock().unwrap().take(); +fn drop_unstarted_job(build: &Build) { + let job = build.job.lock().unwrap().take(); if let Some(job) = job { { - let mut done = p.done.lock().unwrap(); + let mut done = build.done.lock().unwrap(); *done = true; - p.cv.notify_all(); + build.cv.notify_all(); } drop(job); } @@ -303,8 +323,8 @@ fn queue() -> &'static Mutex> { let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { let next = rx.lock().unwrap().recv(); let Ok(work) = next else { return }; - while let Some(p) = next_needed() { - build_queued(&p); + while let Some(build) = next_needed() { + build_queued(&build); } work(); }); @@ -313,20 +333,20 @@ fn queue() -> &'static Mutex> { }) } -fn enqueue(p: Arc) { - let _ = queue().lock().unwrap().send(Box::new(move || build_queued(&p))); +fn enqueue(build: Arc) { + let _ = queue().lock().unwrap().send(Box::new(move || build_queued(&build))); } -fn build_queued(p: &Arc) { +fn build_queued(build: &Arc) { // (released by the title meanwhile) - if p.orphan.load(Ordering::Acquire) { - drop_unstarted_job(p); + if build.orphan.load(Ordering::Acquire) { + drop_unstarted_job(build); return; } // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); + let job = build.job.lock().unwrap().take(); if let Some(job) = job { - build(p, job, false); + run_build(build, job, false); } } @@ -386,20 +406,15 @@ pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { } fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { + let build = Arc::new(Build::new(job, send)); let p = Arc::new(Pending { - job: Mutex::new(Some(job)), - sent: std::sync::atomic::AtomicBool::new(send), - real: AtomicUsize::new(0), + build: build.clone(), driver: AtomicUsize::new(0), - done: Mutex::new(false), - cv: Condvar::new(), compute, key, used: Default::default(), - orphan: Default::default(), late: Default::default(), spared: Default::default(), - demand: Default::default(), }); PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); @@ -407,10 +422,10 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); }); if send { - enqueue(p); + enqueue(build); } else if used::known(key) { if let Some(q) = preload() { - q.list.lock().unwrap().push_back(p); + q.list.lock().unwrap().push_back(build); q.cv.notify_one(); } } @@ -501,7 +516,7 @@ mod used { /// priority: a pipeline that is bound is not held up by the ones made ahead (whoever takes /// `job` first builds it), and the title's own threads are not either. struct Preload { - list: Mutex>>, + list: Mutex>>, cv: Condvar, } @@ -526,7 +541,7 @@ fn preload() -> Option<&'static Preload> { } static DONE: AtomicUsize = AtomicUsize::new(0); loop { - let p = { + let build = { let mut g = q.list.lock().unwrap(); loop { if let Some(p) = g.pop_front() { @@ -536,14 +551,14 @@ fn preload() -> Option<&'static Preload> { } }; // (released by the title meanwhile) - if p.orphan.load(Ordering::Acquire) { - drop_unstarted_job(&p); + if build.orphan.load(Ordering::Acquire) { + drop_unstarted_job(&build); continue; } // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); + let job = build.job.lock().unwrap().take(); if let Some(job) = job { - build(&p, job, true); + run_build(&build, job, true); let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; if n.is_power_of_two() { crate::xlog_info!("D3D12.X: {n} pipelines built ahead of their first use"); @@ -560,6 +575,24 @@ fn preload() -> Option<&'static Preload> { mod used_tests { use super::*; + #[test] + fn build_completion_reaches_all_owners() { + let build = Arc::new(Build::new(Box::new(|| 0), false)); + let waiter_build = build.clone(); + assert!(Arc::ptr_eq(&build, &waiter_build)); + let waiter = std::thread::spawn(move || { + let mut done = waiter_build.done.lock().unwrap(); + while !*done { + done = waiter_build.cv.wait(done).unwrap(); + } + waiter_build.real.load(Ordering::Acquire) + }); + + complete(&build, 0xB017_D001); + assert_eq!(waiter.join().unwrap(), 0xB017_D001); + assert_eq!(build.real.swap(0, Ordering::AcqRel), 0xB017_D001); + } + /// A PC call that has kept one of the title's threads for long holds the title, a short one /// does not, and the hold ends with the call. #[test] @@ -1051,12 +1084,12 @@ pub fn shared(standin: usize, driver: usize) { pub fn resolve(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); - match p.real.load(Ordering::Acquire) { + match p.build.real.load(Ordering::Acquire) { 0 => { // a lazy one is wanted now: to the workers let stand = p.stand(pso); - if !p.sent.swap(true, Ordering::AcqRel) { - enqueue(p); + if !p.build.sent.swap(true, Ordering::AcqRel) { + enqueue(p.build.clone()); } stand } @@ -1078,20 +1111,20 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { return resolve_spared(&p, pso); } // (the title's thread is held from here until the pipeline is built or the budget is over) - let _held = (!*p.done.lock().unwrap()).then(Held::new); + let _held = (!*p.build.done.lock().unwrap()).then(Held::new); if let Some(budget) = budget { return resolve_within(&p, pso, budget); } - let job = p.job.lock().unwrap().take(); + let job = p.build.job.lock().unwrap().take(); if let Some(job) = job { - complete(&p, job()); + complete(&p.build, job()); } - p.want(); - let mut done = p.done.lock().unwrap(); + p.build.want(); + let mut done = p.build.done.lock().unwrap(); while !*done { - done = p.cv.wait(done).unwrap(); + done = p.build.cv.wait(done).unwrap(); } - match p.real.load(Ordering::Acquire) { + match p.build.real.load(Ordering::Acquire) { 0 => p.stand(pso), r => r, } @@ -1110,21 +1143,21 @@ fn wait_budget() -> Option { /// pipeline not built by then is `late` – it and later binds of it get the stand-in (their /// dispatches are skipped) until a worker has built it. fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> usize { - let built = |p: &Pending| match p.real.load(Ordering::Acquire) { + let built = |p: &Pending| match p.build.real.load(Ordering::Acquire) { 0 => p.stand(pso), r => r, }; - if *p.done.lock().unwrap() { + if *p.build.done.lock().unwrap() { return built(p); } - if !p.sent.swap(true, Ordering::AcqRel) { - enqueue(p.clone()); + if !p.build.sent.swap(true, Ordering::AcqRel) { + enqueue(p.build.clone()); } if p.late.load(Ordering::Acquire) { return p.stand(pso); } - p.want(); - let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); + p.build.want(); + let (done, _) = p.build.cv.wait_timeout_while(p.build.done.lock().unwrap(), budget, |d| !*d).unwrap(); if *done { return built(p); } @@ -1163,12 +1196,12 @@ pub fn image_only(standin: usize) { /// else the stand-in, with the build sent to the workers. Nobody waits, so the build is not /// `wanted`: a big one takes its turn among the driver's compiles and waits for free commit. fn resolve_spared(p: &Arc, pso: usize) -> usize { - match p.real.load(Ordering::Acquire) { + match p.build.real.load(Ordering::Acquire) { 0 => { - if !p.sent.swap(true, Ordering::AcqRel) { - enqueue(p.clone()); + if !p.build.sent.swap(true, Ordering::AcqRel) { + enqueue(p.build.clone()); } - if !*p.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { + if !*p.build.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); if n < 16 || n.is_power_of_two() { @@ -1196,40 +1229,40 @@ pub fn resolve_for_bind(pso: usize) -> usize { pub fn released(pso: usize) -> usize { let Some(p) = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)) else { return 0 }; { - let done = p.done.lock().unwrap(); + let done = p.build.done.lock().unwrap(); if *done { - return p.real.swap(0, Ordering::AcqRel); + return p.build.real.swap(0, Ordering::AcqRel); } - // the worker stores its result into a Pending nobody will read: mark it orphaned - p.orphan.store(true, Ordering::Release); + // the worker stores its result into a Build nobody will read: mark it orphaned + p.build.orphan.store(true, Ordering::Release); } - drop_unstarted_job(&p); + drop_unstarted_job(&p.build); 0 } /// `pso` is a stand-in whose real pipeline is still being built. pub fn is_pending(pso: usize) -> bool { - entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) + entry(pso).is_some_and(|p| !*p.build.done.lock().unwrap()) } /// One of the title's threads is about to wait for `pso`. pub fn want(pso: usize) { if let Some(p) = entry(pso) { - p.want(); + p.build.want(); } } /// A call with `pso` was put off to the submit: its build goes before the workers' queue. pub fn need_by_submit(pso: usize) { let Some(p) = entry(pso) else { return }; - if !std::mem::replace(&mut p.demand.lock().unwrap().by_submit, true) { - NEEDED.lock().unwrap().push_back(p); + if !std::mem::replace(&mut p.build.demand.lock().unwrap().by_submit, true) { + NEEDED.lock().unwrap().push_back(p.build.clone()); let _ = queue().lock().unwrap().send(Box::new(|| ())); } } /// (built in the background, failed, still building) pub fn counts() -> (usize, usize, usize) { - let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); + let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.build.done.lock().unwrap()).count()); (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), pending) } From e0635a1ca1aeab0e34907f08a66230aeb4279c77 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:11:10 -0800 Subject: [PATCH 009/265] D3D12.X: serialize stall attribution in reports Add an optional versioned stall summary to report.json while keeping tracing-disabled reports and existing text output unchanged. The schema contains bounded category timings only and remains backward-compatible through serde defaults. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/report.rs | 156 +++++++++++++++++++++++++++++++++++++++ crates/xcl/src/stall.rs | 4 +- 2 files changed, 158 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index 45b886e103..c1c9012268 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -11,6 +11,8 @@ use serde::{Deserialize, Serialize}; use crate::resolver::{self, Source}; +pub const STALL_SUMMARY_VERSION: u32 = 1; + #[derive(Debug, Serialize, Deserialize, Default)] pub struct StubCall { pub dll: String, @@ -40,6 +42,95 @@ pub struct VfsInfo { pub whiteouts: Vec, } +#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq)] +pub struct StallAggregate { + #[serde(default)] + pub kind: String, + #[serde(default)] + pub count: u64, + #[serde(default)] + pub total_ns: u64, + #[serde(default)] + pub max_ns: u64, + /// Index N counts durations from 2^N through 2^(N+1)-1 nanoseconds; bucket zero + /// also contains zero-duration spans. + #[serde(default)] + pub histogram_log2_ns: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq)] +pub struct StallEvent { + #[serde(default)] + pub sequence: u64, + #[serde(default)] + pub kind: String, + #[serde(default)] + pub started_ns: u64, + #[serde(default)] + pub duration_ns: u64, +} + +#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq)] +pub struct StallSummary { + #[serde(default)] + pub version: u32, + #[serde(default)] + pub aggregates: Vec, + #[serde(default)] + pub slow_events: Vec, +} + +fn stall_kind_name(kind: crate::stall::StallKind) -> &'static str { + use crate::stall::StallKind; + match kind { + StallKind::ShaderTranslation => "shader_translation", + StallKind::DxcQueue => "dxc_queue", + StallKind::DxcCompile => "dxc_compile", + StallKind::PipelineWait => "pipeline_wait", + StallKind::DriverCompileGate => "driver_compile_gate", + StallKind::DriverCompile => "driver_compile", + StallKind::SubmitPreparation => "submit_preparation", + StallKind::MemorySynchronization => "memory_synchronization", + StallKind::Residency => "residency", + StallKind::CacheIo => "cache_io", + StallKind::LockContention => "lock_contention", + StallKind::GpuWait => "gpu_wait", + StallKind::Present => "present", + StallKind::DirectStorage => "direct_storage", + } +} + +impl From for StallSummary { + fn from(snapshot: crate::stall::Snapshot) -> Self { + let slow_skip = snapshot.slow_spans.len().saturating_sub(crate::stall::SLOW_SPAN_CAPACITY); + Self { + version: STALL_SUMMARY_VERSION, + aggregates: snapshot + .aggregates + .into_iter() + .map(|a| StallAggregate { + kind: stall_kind_name(a.kind).into(), + count: a.count, + total_ns: a.total_ns, + max_ns: a.max_ns, + histogram_log2_ns: a.histogram.into(), + }) + .collect(), + slow_events: snapshot + .slow_spans + .into_iter() + .skip(slow_skip) + .map(|s| StallEvent { + sequence: s.sequence, + kind: stall_kind_name(s.kind).into(), + started_ns: s.started_ns, + duration_ns: s.duration_ns, + }) + .collect(), + } + } +} + #[derive(Debug, Serialize, Deserialize, Default)] pub struct Report { pub xcl_version: String, @@ -79,6 +170,10 @@ pub struct Report { /// `XCL_DSTORAGE_BCPACK_FILL` #[serde(default)] pub dstorage: crate::hle::dstorage::DStorageStats, + /// Coarse runtime timings when `XCL_STALL_TRACE` was enabled. The events contain only + /// categories and monotonic times, never title paths, shader contents, or pipeline keys. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stalls: Option, pub notes: Vec, } @@ -146,6 +241,7 @@ pub fn build() -> Report { audio: crate::hle::xaudio2::stats(), xgameruntime: crate::hle::xgameruntime::api::stats(), dstorage: crate::hle::dstorage::stats(), + stalls: crate::stall::snapshot().map(Into::into), notes: vec![ "D3D12.X methods missing on PC show up in called_stubs as '::#slot (not on PC)'.".into(), "Console-format shaders are replaced (fallback_pipelines) until the RDNA2 recompiler is finished.".into(), @@ -197,6 +293,66 @@ pub fn load(path: &std::path::Path) -> Option { mod tests { use super::*; + #[test] + fn old_reports_without_a_stall_summary_still_deserialize() { + let old = serde_json::to_value(Report::default()).unwrap(); + assert!(old.get("stalls").is_none(), "an absent summary is not serialized"); + let report: Report = serde_json::from_value(old).unwrap(); + assert!(report.stalls.is_none()); + } + + #[test] + fn a_stall_snapshot_has_a_versioned_stable_json_shape() { + let mut histogram = [0; crate::stall::HISTOGRAM_BUCKETS]; + histogram[10] = 2; + let summary = StallSummary::from(crate::stall::Snapshot { + aggregates: vec![crate::stall::AggregateSnapshot { + kind: crate::stall::StallKind::DxcCompile, + count: 2, + total_ns: 2500, + max_ns: 1476, + histogram, + }], + slow_spans: vec![crate::stall::SlowSpan { + sequence: 7, + kind: crate::stall::StallKind::GpuWait, + started_ns: 100, + duration_ns: 50_000_000, + }], + }); + let json = serde_json::to_value(summary).unwrap(); + + assert_eq!(json["version"], STALL_SUMMARY_VERSION); + assert_eq!(json["aggregates"][0]["kind"], "dxc_compile"); + assert_eq!(json["aggregates"][0]["count"], 2); + assert_eq!(json["aggregates"][0]["histogram_log2_ns"][10], 2); + assert_eq!(json["aggregates"][0]["histogram_log2_ns"].as_array().unwrap().len(), crate::stall::HISTOGRAM_BUCKETS); + assert_eq!(json["slow_events"][0]["kind"], "gpu_wait"); + assert_eq!(json["slow_events"][0]["sequence"], 7); + assert_eq!(json["slow_events"][0]["duration_ns"], 50_000_000); + } + + #[test] + fn missing_fields_in_a_stall_summary_take_safe_defaults() { + let summary: StallSummary = serde_json::from_str(r#"{"version":1}"#).unwrap(); + assert_eq!(summary, StallSummary { version: 1, aggregates: Vec::new(), slow_events: Vec::new() }); + } + + #[test] + fn a_stall_summary_keeps_only_the_newest_bounded_events() { + let slow_spans = (0..crate::stall::SLOW_SPAN_CAPACITY + 2) + .map(|sequence| crate::stall::SlowSpan { + sequence: sequence as u64, + kind: crate::stall::StallKind::GpuWait, + started_ns: sequence as u64, + duration_ns: crate::stall::SLOW_SPAN_NS, + }) + .collect(); + let summary = StallSummary::from(crate::stall::Snapshot { aggregates: Vec::new(), slow_spans }); + assert_eq!(summary.slow_events.len(), crate::stall::SLOW_SPAN_CAPACITY); + assert_eq!(summary.slow_events[0].sequence, 2); + } + #[test] fn a_crash_is_kept_while_another_thread_writes_the_report() { let (held, wait_held) = std::sync::mpsc::channel(); diff --git a/crates/xcl/src/stall.rs b/crates/xcl/src/stall.rs index 8a7f68c461..06add3c292 100644 --- a/crates/xcl/src/stall.rs +++ b/crates/xcl/src/stall.rs @@ -209,8 +209,8 @@ pub fn span(kind: StallKind) -> Option> { RECORDER.start_with(kind, &CLOCK) } -pub fn snapshot() -> Snapshot { - RECORDER.snapshot() +pub fn snapshot() -> Option { + RECORDER.enabled.load(Ordering::Relaxed).then(|| RECORDER.snapshot()) } struct SystemClock; From 4d17a73b339f28a7da20e13605fdfb72b12894ca Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:11:11 -0800 Subject: [PATCH 010/265] D3D12.X: generalize command-list segmentation Name split reasons and collect continuation state in one carry object while preserving existing wait and deferred-dispatch behavior. This creates a tested seam for later CPU-mediated ordering without changing when lists split. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 220 ++++++++++++++++++------ crates/xcl/src/hle/d3d12x/title_list.rs | 18 ++ 2 files changed, 183 insertions(+), 55 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 82c8488dc4..536e9e8b21 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -721,6 +721,21 @@ pub(super) enum Deferred { Indirect(usize, u32, usize, u64, usize, u64), } +/// Why a recording needs a physical command-list boundary. +pub(super) enum SegmentReason { + WaitAfterWrite64, + DeferredDispatch(Deferred), +} + +impl SegmentReason { + fn extra_segments(&self) -> usize { + match self { + Self::WaitAfterWrite64 => 1, + Self::DeferredDispatch(_) => 2, + } + } +} + impl ListState { fn note_write(&mut self, va: u64, size: u64) { if size == 0 { @@ -771,6 +786,69 @@ impl ListState { } } +/// Recording state that a PC Reset loses and the continuation segment must inherit. +struct SplitCarry { + allocator: usize, + last_queue: Option, + bound_pso: usize, + depth_bias: Option, + index_buffer: Option, + depth_bounds: Option<(f32, f32)>, + predication: Option, + pred_buf: Option, + pred_in_state: bool, + active_query: Option<(Query, D3D12_QUERY_TYPE)>, + ended_early: Vec, + written_ranges: RecordedWrites, + bindings: Bindings, +} + +impl SplitCarry { + fn take(state: &mut ListState) -> Option { + if state.allocator == 0 { + return None; + } + let active_query = state.occlusion.end_active_early(); + Some(Self { + allocator: state.allocator, + last_queue: state.last_queue, + bound_pso: state.bound_pso, + depth_bias: state.depth_bias, + index_buffer: state.index_buffer, + depth_bounds: state.depth_bounds, + predication: state.predication, + pred_buf: state.pred_buf.clone(), + pred_in_state: std::mem::replace(&mut state.pred_in_state, false), + active_query, + ended_early: std::mem::take(&mut state.occlusion.ended_early), + written_ranges: state.written_ranges.clone(), + bindings: state.bindings.clone(), + }) + } + + fn continuation_state(&self, ty: D3D12_COMMAND_LIST_TYPE) -> ListState { + ListState { + allocator: self.allocator, + list_type: Some(ty), + last_queue: self.last_queue, + bound_pso: self.bound_pso, + depth_bias: self.depth_bias, + native_bias: DepthBias::ZERO, + pso_dirty: false, + using_fallback_pso: false, + index_buffer: self.index_buffer, + depth_bounds: self.depth_bounds, + occlusion: Occlusion { active: None, ended_early: self.ended_early.clone() }, + written_ranges: self.written_ranges.clone(), + pred_buf: self.pred_buf.clone(), + pred_in_state: false, + predication: self.predication, + bindings: self.bindings.clone(), + ..Default::default() + } + } +} + #[derive(Clone, Copy)] struct QueueInfo { queue: usize, @@ -2752,7 +2830,7 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { if !*ENABLED.get_or_init(|| std::env::var("XCL_SPLIT_MIDLIST_WAIT").map_or(true, |v| v.trim() != "0")) { return None; } - let next_pc = split(list, None)?; + let next_pc = split_recording(list, SegmentReason::WaitAfterWrite64)?; static SPLITS: AtomicU64 = AtomicU64::new(0); let n = SPLITS.fetch_add(1, Ordering::Relaxed) + 1; if n <= 4 || (n.is_power_of_two() && n <= 256) { @@ -2763,7 +2841,7 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { /// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { - if split(list, Some(what)).is_none() { + if split_recording(list, SegmentReason::DeferredDispatch(what)).is_none() { return false; } static N: AtomicU64 = AtomicU64::new(0); @@ -2842,18 +2920,18 @@ unsafe fn reset_own_alloc(list: *mut c_void) { } } -/// 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> { +/// Ends `list`'s segment and opens the next, carrying its recording state across the boundary. +pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) -> 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) { + if !super::title_list::can_split(wrapper, reason.extra_segments()) { return None; } let ty = list_type(list); if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { return None; } - let deferred = match dispatch { - Some(what) => { + let deferred = match reason { + SegmentReason::DeferredDispatch(what) => { // (a predicated call stays in its list) let plain = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.allocator != 0 && s.predication.is_none()); if !plain { @@ -2861,39 +2939,27 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } Some((what, deferred_segment(wrapper, list, ty)?)) } - None => None, + SegmentReason::WaitAfterWrite64 => 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 carry = { let mut g = LISTS.lock().unwrap(); let s = g.as_mut()?.get_mut(&(list as usize))?; - if s.allocator == 0 { - 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); - ( - s.allocator, - s.last_queue, - s.bound_pso, - s.depth_bias, - s.index_buffer, - s.depth_bounds, - s.predication, - s.pred_buf.clone(), - pred_in_state, - active_query, - ended_early, - s.written_ranges.clone(), - s.bindings.clone(), - ) + SplitCarry::take(s)? }; - - if let Some(((h, i), qty)) = active_query { + let alloc = carry.allocator; + let bound_pso = carry.bound_pso; + let depth_bias = carry.depth_bias; + let index_buffer = carry.index_buffer; + let depth_bounds = carry.depth_bounds; + let predication = carry.predication; + let pred_buf = &carry.pred_buf; + let bindings = &carry.bindings; + + if let Some(((h, i), qty)) = carry.active_query { pc::(list, PC_END_QUERY)(list, h, qty, i); } - if pred_in_state { - if let Some(ref pb) = pred_buf { + if carry.pred_in_state { + if let Some(pb) = pred_buf { transition(list, pb.as_raw() as usize, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON); } } @@ -2959,32 +3025,14 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } m.insert( next_pc as usize, - ListState { - allocator: alloc, - list_type: Some(ty), - last_queue, - bound_pso, - depth_bias, - native_bias: DepthBias::ZERO, - pso_dirty: false, - using_fallback_pso: false, - index_buffer, - depth_bounds, - occlusion: Occlusion { active: None, ended_early }, - written_ranges, - pred_buf: pred_buf.clone(), - pred_in_state: false, - predication, - bindings: bindings.clone(), - ..Default::default() - }, + carry.continuation_state(ty), ); old }; drop(old_next); super::title_textures::list_reset(next_pc as usize); super::bind::inherit_for_split(list, next_pc, alloc); - restore_bindings(next_pc, &bindings, ty); + restore_bindings(next_pc, bindings, ty); if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { let info = if bound_pso != 0 { device_x::base_depth_bias_info(bound_pso) } else { None }; @@ -3023,7 +3071,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } } if ty != D3D12_COMMAND_LIST_TYPE_COPY { - if let (Some(op), Some(ref pb)) = (predication, pred_buf) { + if let (Some(op), Some(pb)) = (predication, pred_buf) { let pb_raw = pb.as_raw() as usize; transition(next_pc, pb_raw, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PREDICATION); pc::(next_pc, PC_SET_PREDICATION)(next_pc, pb_raw, 0, op); @@ -5221,6 +5269,68 @@ mod tests { assert_eq!(submitted, 1); } + #[test] + fn segment_reasons_keep_the_existing_segment_costs() { + assert_eq!(SegmentReason::WaitAfterWrite64.extra_segments(), 1); + assert_eq!(SegmentReason::DeferredDispatch(Deferred::Dispatch(1, 2, 3)).extra_segments(), 2); + } + + #[test] + fn split_carry_recreates_the_continuation_state() { + let query = (0x7100, 3); + let earlier_query = (0x7000, 2); + let mut state = ListState { + allocator: 0xa110, + list_type: Some(D3D12_COMMAND_LIST_TYPE_DIRECT), + last_queue: Some(0x9000), + bound_pso: 0xb220, + depth_bias: Some(DepthBias::new(-2.5, 0.25, 4.0)), + native_bias: DepthBias::new(-1.0, 1.0, 1.0), + pso_dirty: true, + using_fallback_pso: true, + index_buffer: Some(D3D12_INDEX_BUFFER_VIEW { BufferLocation: 0xc330, SizeInBytes: 24, Format: DXGI_FORMAT_R32_UINT }), + depth_bounds: Some((0.2, 0.8)), + pred_in_state: true, + predication: Some(D3D12_PREDICATION_OP_NOT_EQUAL_ZERO), + pending_waits: vec![PendingWait { va: 0xd440, width: 8, comparison: 7, value: 5, mask: u64::MAX, after_write64: false }], + write64_signals: vec![(0xe550, 6)], + sparse_writes: vec![(0xf660, 8)], + bindings: Bindings { heaps: vec![0x1010, 0x2020], topology: Some(4), stencil: Some(9), ..Default::default() }, + ..Default::default() + }; + state.written_ranges.insert(0x3000, 0x20); + state.occlusion.ended_early.push(earlier_query); + assert!(state.occlusion.begin(query, D3D12_QUERY_TYPE_OCCLUSION).is_none()); + + let carry = SplitCarry::take(&mut state).unwrap(); + state.bindings.heaps.clear(); + state.written_ranges.clear(); + let continued = carry.continuation_state(D3D12_COMMAND_LIST_TYPE_DIRECT); + + assert_eq!(carry.active_query, Some((query, D3D12_QUERY_TYPE_OCCLUSION))); + assert!(!state.pred_in_state && state.occlusion.active.is_none() && state.occlusion.ended_early.is_empty()); + assert_eq!(continued.allocator, 0xa110); + assert_eq!(continued.last_queue, Some(0x9000)); + assert_eq!(continued.bound_pso, 0xb220); + assert_eq!(continued.depth_bias, Some(DepthBias::new(-2.5, 0.25, 4.0))); + assert_eq!(continued.native_bias, DepthBias::ZERO); + assert!(!continued.pso_dirty && !continued.using_fallback_pso); + assert_eq!(continued.index_buffer.as_ref().unwrap().BufferLocation, 0xc330); + assert_eq!(continued.depth_bounds, Some((0.2, 0.8))); + assert_eq!(continued.predication, Some(D3D12_PREDICATION_OP_NOT_EQUAL_ZERO)); + assert!(!continued.pred_in_state); + assert_eq!(continued.occlusion.ended_early, vec![earlier_query, query]); + assert_eq!(continued.bindings.heaps, vec![0x1010, 0x2020]); + assert_eq!(continued.bindings.topology, Some(4)); + assert_eq!(continued.bindings.stencil, Some(9)); + assert!(continued.written_ranges.overlaps(0x3010, 4)); + assert!(continued.pending_waits.is_empty() && continued.write64_signals.is_empty() && continued.sparse_writes.is_empty()); + assert!(continued.cpu_writes.is_empty() && continued.deferred.is_none() && continued.own_alloc.is_none()); + assert_eq!(state.pending_waits.len(), 1, "effects remain on the closed segment"); + assert_eq!(state.write64_signals, vec![(0xe550, 6)]); + assert_eq!(state.sparse_writes, vec![(0xf660, 8)]); + } + #[test] fn execute_with_waits_splits_batches_before_unsatisfied_list() { // Use synthetic non-zero list pointers distinct from real COM objects. diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index a41e5643fc..10d6ba52f2 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -453,6 +453,24 @@ mod tests { this as u64 + a + 10 * b + 100 * c + 1000 * d } + #[test] + fn split_limit_counts_every_physical_extra_segment() { + let wrapper = 0x7ffe_3001usize as *mut c_void; + { + let mut sg = SEGMENTS.lock().unwrap(); + sg.get_or_insert_with(HashMap::new).insert( + wrapper as usize, + SegmentBook { extra_active: (0..MAX_EXTRA_SEGMENTS - 1).map(|i| 0x8000 + i).collect(), ..Default::default() }, + ); + } + assert!(can_split(wrapper, 1)); + assert!(!can_split(wrapper, 2), "a deferred dispatch needs two physical segments"); + push_segment(wrapper, 0x9000usize as *mut c_void); + assert!(!can_split(wrapper, 1)); + assert!(can_split(wrapper, 0)); + SEGMENTS.lock().unwrap().as_mut().unwrap().remove(&(wrapper as usize)); + } + /// 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() { From 2ccea5e1ee9071fab229ec90a7ba6225479705c4 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:13:08 -0800 Subject: [PATCH 011/265] D3D12.X: prioritize asynchronous pipeline builds Route normal and preload PSO work through worker bands in the shared build queue. Foreground demand promotes queued work without duplicating it, while caller stealing, wait budgets, and result ownership remain unchanged. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/build_queue.rs | 104 ++++++-- crates/xcl/src/hle/d3d12x/pso_async.rs | 300 ++++++++++++++--------- 2 files changed, 272 insertions(+), 132 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/build_queue.rs b/crates/xcl/src/hle/d3d12x/build_queue.rs index 8d0816bf64..1829d29514 100644 --- a/crates/xcl/src/hle/d3d12x/build_queue.rs +++ b/crates/xcl/src/hle/d3d12x/build_queue.rs @@ -1,16 +1,15 @@ //! Priority queue shared by pipeline-preparation workers. //! -//! This module is deliberately not connected to the runtime yet. It gives the DXC and PSO -//! migrations one queue with stable job identities, monotonic priority promotion and completion -//! that survives a panicking job or queue shutdown. +//! PSO preparation uses worker bands so background preloads cannot occupy the workers reserved +//! for builds that the title will need soon. -#![allow(dead_code)] // Used by the following pipeline-preparation changes. +#![allow(dead_code)] // Some operations are seams for the following preparation changes. use std::collections::{HashMap, VecDeque}; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::sync::{Arc, Condvar, Mutex, Weak}; -type Work = Box; +pub(super) type Work = Box; #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] #[repr(u8)] @@ -127,10 +126,31 @@ struct State { struct Inner { state: Mutex, - changed: Condvar, + preload_changed: Condvar, + foreground_changed: Condvar, + all_changed: Condvar, } impl Inner { + fn changed(&self, low: Priority, high: Priority) -> &Condvar { + if high <= Priority::Preload { + &self.preload_changed + } else if low >= Priority::BoundSoon { + &self.foreground_changed + } else { + &self.all_changed + } + } + + fn wake(&self, priority: Priority) { + if priority <= Priority::Preload { + self.preload_changed.notify_one(); + } else { + self.foreground_changed.notify_one(); + } + self.all_changed.notify_one(); + } + fn promote(&self, id: JobId, priority: Priority) -> bool { let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); let Some(job) = state.jobs.get_mut(&id) else { return false }; @@ -141,7 +161,7 @@ impl Inner { job.generation += 1; let ticket = Ticket { id, generation: job.generation }; state.ready[priority.index()].push_back(ticket); - self.changed.notify_one(); + self.wake(priority); true } @@ -155,10 +175,11 @@ impl Inner { } } - fn take(&self, wait: bool) -> Option<(Work, Arc)> { + fn take(&self, wait: bool, low: Priority, high: Priority) -> Option<(Work, Arc)> { let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + let changed = self.changed(low, high); loop { - for priority in (0..Priority::COUNT).rev() { + for priority in (low.index()..=high.index()).rev() { while let Some(ticket) = state.ready[priority].pop_front() { let current = state.jobs.get(&ticket.id).is_some_and(|job| { job.priority.index() == priority && job.generation == ticket.generation @@ -173,7 +194,7 @@ impl Inner { if state.stopped || !wait { return None; } - state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); + state = changed.wait(state).unwrap_or_else(|e| e.into_inner()); } } @@ -192,7 +213,9 @@ impl Inner { for (_, job) in jobs { job.completion.set(JobStatus::Cancelled); } - self.changed.notify_all(); + self.preload_changed.notify_all(); + self.foreground_changed.notify_all(); + self.all_changed.notify_all(); } } @@ -210,7 +233,9 @@ impl BuildQueue { jobs: HashMap::new(), ready: std::array::from_fn(|_| VecDeque::new()), }), - changed: Condvar::new(), + preload_changed: Condvar::new(), + foreground_changed: Condvar::new(), + all_changed: Condvar::new(), }), } } @@ -228,17 +253,25 @@ impl BuildQueue { state.jobs.insert(id, Job { priority, generation, work, completion: completion.clone() }); state.ready[priority.index()].push_back(Ticket { id, generation }); drop(state); - self.inner.changed.notify_one(); + self.inner.wake(priority); Some(JobHandle { id, queue: Arc::downgrade(&self.inner), completion }) } pub(super) fn worker(&self) -> Worker { - Worker { inner: self.inner.clone() } + self.worker_between(Priority::Speculative, Priority::Foreground) + } + + pub(super) fn worker_between(&self, low: Priority, high: Priority) -> Worker { + Worker { inner: self.inner.clone(), low, high } } /// Run one ready job on this thread, for callers that help drain a batch. pub(super) fn try_run_one(&self) -> bool { - self.inner.take(false).is_some_and(|job| { + self.try_run_one_between(Priority::Speculative, Priority::Foreground) + } + + pub(super) fn try_run_one_between(&self, low: Priority, high: Priority) -> bool { + self.inner.take(false, low, high).is_some_and(|job| { run(job); true }) @@ -257,11 +290,13 @@ impl Drop for BuildQueue { pub(super) struct Worker { inner: Arc, + low: Priority, + high: Priority, } impl Worker { pub(super) fn run(self) { - while let Some(job) = self.inner.take(true) { + while let Some(job) = self.inner.take(true, self.low, self.high) { run(job); } } @@ -307,6 +342,43 @@ mod tests { assert_eq!(*out.lock().unwrap(), [1, 2]); } + #[test] + fn foreground_worker_band_is_not_trapped_by_preload_work() { + let q = BuildQueue::new(); + let normal = q.worker_between(Priority::BoundSoon, Priority::Foreground); + let preload = q.worker_between(Priority::Speculative, Priority::Preload); + let normal_thread = std::thread::Builder::new().name("normal-band".into()).spawn(move || normal.run()).unwrap(); + let preload_thread = std::thread::Builder::new().name("preload-band".into()).spawn(move || preload.run()).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + for (priority, label) in [(Priority::Preload, "preload"), (Priority::Foreground, "foreground")] { + let tx = tx.clone(); + q.submit(priority, Box::new(move || { + tx.send((label, std::thread::current().name().unwrap().to_string())).unwrap(); + })).unwrap(); + } + let mut ran = vec![ + rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(), + rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(), + ]; + ran.sort_unstable(); + assert_eq!(ran, [("foreground", "normal-band".into()), ("preload", "preload-band".into())]); + q.shutdown(); + normal_thread.join().unwrap(); + preload_thread.join().unwrap(); + } + + #[test] + fn promoted_preload_moves_to_the_foreground_worker_band() { + let q = BuildQueue::new(); + let ran = Arc::new(AtomicBool::new(false)); + let mark = ran.clone(); + let job = q.submit(Priority::Preload, Box::new(move || mark.store(true, Ordering::Release))).unwrap(); + assert!(job.promote(Priority::Foreground)); + assert!(!q.try_run_one_between(Priority::Speculative, Priority::Preload)); + assert!(q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(ran.load(Ordering::Acquire)); + } + #[test] fn job_ids_are_stable_and_not_reused() { let q = BuildQueue::new(); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index a66e56f184..e65b3a7a25 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -11,6 +11,8 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +use super::build_queue::{BuildQueue, JobHandle, Priority}; + struct Pending { build: Arc, /// the driver pipeline binds get till then (`shared`); 0: the stand-in is one itself @@ -40,6 +42,7 @@ struct Build { /// every stand-in interested in this build was released before it finished orphan: std::sync::atomic::AtomicBool, demand: Mutex, + queued: Mutex>, } /// Whether one of the title's threads waits for the pipeline, and the preload worker building it. @@ -55,6 +58,8 @@ struct Demand { thread_local! { /// what this worker is building static BUILDING: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + /// this is one of the workers reserved for low-priority preload builds + static PRELOAD_WORKER: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// This thread is a worker and one of the title's threads waits for what it is building: the @@ -74,9 +79,40 @@ pub fn wanted_here() -> crate::gpu::recomp::dxc::Wanted { Box::new(move || own) } +struct RunningBuild<'a> { + build: &'a Build, + preload: bool, +} + +impl Drop for RunningBuild<'_> { + fn drop(&mut self) { + if self.preload { + // (under the lock: `want` does not raise this thread after it) + let mut demand = self.build.demand.lock().unwrap(); + demand.preload_thread = 0; + if demand.wanted { + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); + } + } + } + BUILDING.with(|b| *b.borrow_mut() = None); + } +} + +struct RestoreBuilding(Option>); + +impl Drop for RestoreBuilding { + fn drop(&mut self) { + BUILDING.with(|b| *b.borrow_mut() = self.0.take()); + } +} + /// A worker's pipeline build (`preload`: by one of the lowest-priority workers). -fn run_build(build: &Arc, job: Job, preload: bool) { - use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL}; +fn run_build(build: &Arc, job: Job) { + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_NORMAL}; + let preload = PRELOAD_WORKER.get(); BUILDING.with(|b| *b.borrow_mut() = Some(build.clone())); if preload { let mut d = build.demand.lock().unwrap(); @@ -85,16 +121,8 @@ fn run_build(build: &Arc, job: Job, preload: bool) { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } + let _running = RunningBuild { build, preload }; complete(build, job()); - if preload { - // (under the lock: `want` does not raise this thread after it) - let mut d = build.demand.lock().unwrap(); - d.preload_thread = 0; - if d.wanted { - unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST) }; - } - } - BUILDING.with(|b| *b.borrow_mut() = None); } impl Build { @@ -107,6 +135,19 @@ impl Build { cv: Condvar::new(), orphan: Default::default(), demand: Default::default(), + queued: Mutex::new(None), + } + } + + fn promote(&self, priority: Priority) { + if let Some(job) = self.queued.lock().unwrap().as_ref() { + let _ = job.promote(priority); + } + } + + fn cancel_queued(&self) { + if let Some(job) = self.queued.lock().unwrap().take() { + let _ = job.cancel(); } } @@ -115,6 +156,8 @@ impl Build { fn want(&self) { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_PRIORITY_NORMAL, THREAD_SET_LIMITED_INFORMATION}; + start_normal_workers(); + self.promote(Priority::Foreground); let mut d = self.demand.lock().unwrap(); if !std::mem::replace(&mut d.wanted, true) && d.preload_thread != 0 { unsafe { @@ -289,17 +332,11 @@ pub fn enabled() -> bool { /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box usize + Send>; -/// pipelines a submit will wait for: the workers take these before their queue (`need_by_submit`) -static NEEDED: Mutex>> = Mutex::new(std::collections::VecDeque::new()); - -fn next_needed() -> Option> { - NEEDED.lock().unwrap().pop_front() -} - /// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. fn drop_unstarted_job(build: &Build) { let job = build.job.lock().unwrap().take(); if let Some(job) = job { + build.cancel_queued(); { let mut done = build.done.lock().unwrap(); *done = true; @@ -309,44 +346,97 @@ fn drop_unstarted_job(build: &Build) { } } -type Work = Box; +fn queue() -> &'static BuildQueue { + static Q: OnceLock = OnceLock::new(); + Q.get_or_init(BuildQueue::new) +} -fn queue() -> &'static Mutex> { - static Q: OnceLock>> = OnceLock::new(); - Q.get_or_init(|| { - let (tx, rx) = mpsc::channel::(); - let rx = Arc::new(Mutex::new(rx)); +fn start_normal_workers() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let q = queue(); // translation recurses deeply on big programs; DXC itself runs on its own pool let n = crate::gpu::recomp::dxc::compile_threads(); for k in 0..n { - let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { - let next = rx.lock().unwrap().recv(); - let Ok(work) = next else { return }; - while let Some(build) = next_needed() { - build_queued(&build); + let worker = q.worker_between(Priority::BoundSoon, Priority::Foreground); + let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || worker.run()); + } + }); +} + +fn start_preload_workers() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let q = queue(); + let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); + for k in 0..n { + let worker = q.worker_between(Priority::Speculative, Priority::Preload); + let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); } - work(); + PRELOAD_WORKER.set(true); + worker.run(); }); } - Mutex::new(tx) - }) + }); +} + +fn submit_job(q: &BuildQueue, build: &Arc, priority: Priority, preload: bool) -> Option { + let queued_build = build.clone(); + q.submit(priority, Box::new(move || { + let on_preload_worker = PRELOAD_WORKER.get(); + let built = build_queued(&queued_build); + if built && preload && on_preload_worker { + static DONE: AtomicUsize = AtomicUsize::new(0); + let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: {n} pipelines built ahead of their first use"); + } + } + queued_build.queued.lock().unwrap().take(); + })) +} + +#[cfg(test)] +fn enqueue_on(q: &BuildQueue, build: &Arc, priority: Priority, preload: bool) { + *build.queued.lock().unwrap() = submit_job(q, build, priority, preload); } -fn enqueue(build: Arc) { - let _ = queue().lock().unwrap().send(Box::new(move || build_queued(&build))); +fn schedule(build: &Arc, priority: Priority, preload: bool) { + if preload { + start_preload_workers(); + } else { + start_normal_workers(); + } + let mut queued = build.queued.lock().unwrap(); + if !build.sent.swap(true, Ordering::AcqRel) { + let priority = if { + let demand = build.demand.lock().unwrap(); + demand.wanted || demand.by_submit + } { + Priority::Foreground + } else { + priority + }; + *queued = submit_job(queue(), build, priority, preload); + } } -fn build_queued(build: &Arc) { +fn build_queued(build: &Arc) -> bool { // (released by the title meanwhile) if build.orphan.load(Ordering::Acquire) { drop_unstarted_job(build); - return; + return false; } // (None: a bind took it and builds it itself) let job = build.job.lock().unwrap().take(); if let Some(job) = job { - run_build(build, job, false); + run_build(build, job); + true + } else { + false } } @@ -363,12 +453,13 @@ pub(super) fn build_pieces(jobs: Vec) -> Vec { }; // the helpers build for this worker's pipeline: the title waiting for it waits for them too let parent = BUILDING.with(|b| b.borrow().clone()); + start_normal_workers(); for _ in 1..count.min(crate::gpu::recomp::dxc::compile_threads()) { let (drain, parent) = (drain.clone(), parent.clone()); - let _ = queue().lock().unwrap().send(Box::new(move || { + let _ = queue().submit(Priority::BoundSoon, Box::new(move || { let before = BUILDING.with(|b| b.replace(parent)); + let _restore = RestoreBuilding(before); drain(); - BUILDING.with(|b| *b.borrow_mut() = before); })); } drain(); @@ -406,7 +497,7 @@ pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { } fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { - let build = Arc::new(Build::new(job, send)); + let build = Arc::new(Build::new(job, false)); let p = Arc::new(Pending { build: build.clone(), driver: AtomicUsize::new(0), @@ -422,12 +513,9 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); }); if send { - enqueue(build); - } else if used::known(key) { - if let Some(q) = preload() { - q.list.lock().unwrap().push_back(build); - q.cv.notify_one(); - } + schedule(&build, Priority::BoundSoon, false); + } else if used::known(key) && preload_enabled() { + schedule(&build, Priority::Preload, true); } } @@ -511,64 +599,10 @@ mod used { } } -/// The workers that build the pipelines of an earlier run ahead of their first use -/// (`XCL_PSO_PRELOAD=0`: off). Apart from the ones a bind sends to (`queue`) and at the lowest -/// priority: a pipeline that is bound is not held up by the ones made ahead (whoever takes -/// `job` first builds it), and the title's own threads are not either. -struct Preload { - list: Mutex>>, - cv: Condvar, -} - -fn preload() -> Option<&'static Preload> { - static Q: OnceLock> = OnceLock::new(); - static STARTED: std::sync::Once = std::sync::Once::new(); - let q = Q - .get_or_init(|| { - if std::env::var("XCL_PSO_PRELOAD").is_ok_and(|v| v.trim() == "0") { - return None; - } - Some(Preload { list: Mutex::new(Default::default()), cv: Condvar::new() }) - }) - .as_ref()?; - STARTED.call_once(|| { - let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); - for k in 0..n { - let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { - unsafe { - use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); - } - static DONE: AtomicUsize = AtomicUsize::new(0); - loop { - let build = { - let mut g = q.list.lock().unwrap(); - loop { - if let Some(p) = g.pop_front() { - break p; - } - g = q.cv.wait(g).unwrap(); - } - }; - // (released by the title meanwhile) - if build.orphan.load(Ordering::Acquire) { - drop_unstarted_job(&build); - continue; - } - // (None: a bind took it and builds it itself) - let job = build.job.lock().unwrap().take(); - if let Some(job) = job { - run_build(&build, job, true); - let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; - if n.is_power_of_two() { - crate::xlog_info!("D3D12.X: {n} pipelines built ahead of their first use"); - } - } - } - }); - } - }); - Some(q) +/// Build pipelines from an earlier run in the preload worker band (`XCL_PSO_PRELOAD=0`: off). +fn preload_enabled() -> bool { + static ENABLED: OnceLock = OnceLock::new(); + *ENABLED.get_or_init(|| !std::env::var("XCL_PSO_PRELOAD").is_ok_and(|v| v.trim() == "0")) } #[cfg(test)] @@ -593,6 +627,44 @@ mod used_tests { assert_eq!(build.real.swap(0, Ordering::AcqRel), 0xB017_D001); } + #[test] + fn wanted_preload_moves_to_foreground_and_builds_once() { + let q = BuildQueue::new(); + let runs = Arc::new(AtomicUsize::new(0)); + let count = runs.clone(); + let build = Arc::new(Build::new(Box::new(move || { + count.fetch_add(1, Ordering::Relaxed); + 0xB017_D002 + }), true)); + enqueue_on(&q, &build, Priority::Preload, true); + + build.want(); + assert!(!q.try_run_one_between(Priority::Speculative, Priority::Preload)); + assert!(q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(!q.try_run_one()); + assert_eq!(runs.load(Ordering::Relaxed), 1); + assert_eq!(build.real.swap(0, Ordering::AcqRel), 0xB017_D002); + } + + #[test] + fn caller_can_steal_a_queued_build_without_running_it_twice() { + let q = BuildQueue::new(); + let runs = Arc::new(AtomicUsize::new(0)); + let count = runs.clone(); + let build = Arc::new(Build::new(Box::new(move || { + count.fetch_add(1, Ordering::Relaxed); + 0xB017_D003 + }), true)); + enqueue_on(&q, &build, Priority::BoundSoon, false); + + let job = build.job.lock().unwrap().take().unwrap(); + build.cancel_queued(); + complete(&build, job()); + assert!(!q.try_run_one()); + assert_eq!(runs.load(Ordering::Relaxed), 1); + assert_eq!(build.real.swap(0, Ordering::AcqRel), 0xB017_D003); + } + /// A PC call that has kept one of the title's threads for long holds the title, a short one /// does not, and the hold ends with the call. #[test] @@ -1088,9 +1160,8 @@ pub fn resolve(pso: usize) -> usize { 0 => { // a lazy one is wanted now: to the workers let stand = p.stand(pso); - if !p.build.sent.swap(true, Ordering::AcqRel) { - enqueue(p.build.clone()); - } + schedule(&p.build, Priority::BoundSoon, false); + p.build.promote(Priority::Foreground); stand } r => r, @@ -1117,6 +1188,7 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { } let job = p.build.job.lock().unwrap().take(); if let Some(job) = job { + p.build.cancel_queued(); complete(&p.build, job()); } p.build.want(); @@ -1150,9 +1222,7 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> if *p.build.done.lock().unwrap() { return built(p); } - if !p.build.sent.swap(true, Ordering::AcqRel) { - enqueue(p.build.clone()); - } + schedule(&p.build, Priority::BoundSoon, false); if p.late.load(Ordering::Acquire) { return p.stand(pso); } @@ -1198,9 +1268,7 @@ pub fn image_only(standin: usize) { fn resolve_spared(p: &Arc, pso: usize) -> usize { match p.build.real.load(Ordering::Acquire) { 0 => { - if !p.build.sent.swap(true, Ordering::AcqRel) { - enqueue(p.build.clone()); - } + schedule(&p.build, Priority::BoundSoon, false); if !*p.build.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); @@ -1256,8 +1324,8 @@ pub fn want(pso: usize) { pub fn need_by_submit(pso: usize) { let Some(p) = entry(pso) else { return }; if !std::mem::replace(&mut p.build.demand.lock().unwrap().by_submit, true) { - NEEDED.lock().unwrap().push_back(p.build.clone()); - let _ = queue().lock().unwrap().send(Box::new(|| ())); + schedule(&p.build, Priority::BoundSoon, false); + p.build.promote(Priority::Foreground); } } From b3d9441e1a403d448a80858329b52b583d2a2150 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:18:05 -0800 Subject: [PATCH 012/265] D3D12.X: classify command-list write producers Separate writes completed by the submitted GPU segment from writes applied by the CPU after that segment. Snapshot producer ranges per physical segment while retaining cumulative recording knowledge, without changing the existing wait policy. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 149 ++++++++++++++++++++++------ 1 file changed, 120 insertions(+), 29 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 536e9e8b21..a9c0b3435f 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -667,6 +667,53 @@ impl RecordedWrites { } } +/// When a recorded write becomes visible to later work. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum WriteProducer { + InSegmentGpu, + CpuAfterSegment, +} + +/// Exact written ranges kept separately for each visibility class. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct RecordedWriteProducers { + in_segment_gpu: RecordedWrites, + cpu_after_segment: RecordedWrites, +} + +impl RecordedWriteProducers { + fn ranges(&self, producer: WriteProducer) -> &RecordedWrites { + match producer { + WriteProducer::InSegmentGpu => &self.in_segment_gpu, + WriteProducer::CpuAfterSegment => &self.cpu_after_segment, + } + } + + fn ranges_mut(&mut self, producer: WriteProducer) -> &mut RecordedWrites { + match producer { + WriteProducer::InSegmentGpu => &mut self.in_segment_gpu, + WriteProducer::CpuAfterSegment => &mut self.cpu_after_segment, + } + } + + fn insert(&mut self, producer: WriteProducer, va: u64, size: u64) { + self.ranges_mut(producer).insert(va, size); + } + + fn overlaps(&self, producer: WriteProducer, va: u64, size: u64) -> bool { + self.ranges(producer).overlaps(va, size) + } + + fn clear(&mut self) { + self.in_segment_gpu.clear(); + self.cpu_after_segment.clear(); + } + + fn is_empty(&self) -> bool { + self.in_segment_gpu.is_empty() && self.cpu_after_segment.is_empty() + } +} + #[derive(Default)] struct ListState { allocator: usize, @@ -688,8 +735,10 @@ struct ListState { /// Last `OMSetDepthBounds` values, restored after `KickoffX` depth_bounds: Option<(f32, f32)>, occlusion: Occlusion, - /// UMA address ranges written by this list since last Reset/KickoffX - written_ranges: RecordedWrites, + /// Address ranges written by this list since last Reset/KickoffX, by visibility class. + written_ranges: RecordedWriteProducers, + /// Writes produced by this physical segment only (not cumulative across a split). + segment_write_producers: RecordedWriteProducers, /// Sparse-window `(va, bytes)` ranges written by memory ops (`Write32/64`, `Fill*`, /// `CopyMemoryToMemoryX`, timestamps) to copy back to the CPU view after execution. sparse_writes: Vec<(usize, usize)>, @@ -737,12 +786,13 @@ impl SegmentReason { } impl ListState { - fn note_write(&mut self, va: u64, size: u64) { + fn note_write(&mut self, producer: WriteProducer, va: u64, size: u64) { if size == 0 { return; } - self.written_ranges.insert(va, size); - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { + self.written_ranges.insert(producer, va, size); + self.segment_write_producers.insert(producer, va, size); + if producer == WriteProducer::InSegmentGpu && crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { if self.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); } @@ -774,7 +824,8 @@ impl ListState { } fn has_prior_write(&self, va: u64, size: u64) -> bool { - self.written_ranges.overlaps(va, size) + // Keep the existing wait policy until deferred producers gain their own split boundary. + self.written_ranges.overlaps(WriteProducer::InSegmentGpu, va, size) } fn clear_waits(&mut self) { @@ -799,7 +850,7 @@ struct SplitCarry { pred_in_state: bool, active_query: Option<(Query, D3D12_QUERY_TYPE)>, ended_early: Vec, - written_ranges: RecordedWrites, + written_ranges: RecordedWriteProducers, bindings: Bindings, } @@ -871,11 +922,18 @@ static PREDICATION_USED: AtomicBool = AtomicBool::new(false); #[derive(Clone, Default)] pub(super) struct SegmentEffects { waits: Vec, + write_producers: RecordedWriteProducers, write64_signals: Vec<(u64, u64)>, sparse_writes: Vec<(usize, usize)>, cpu_writes: Vec, } +impl SegmentEffects { + pub(super) fn producer_overlaps(&self, producer: WriteProducer, va: u64, size: u64) -> bool { + self.write_producers.overlaps(producer, va, size) + } +} + /// One queue submission's physical lists and their effects, kept in matching chronological order. pub(super) struct SubmissionPlan { lists: Vec<*mut c_void>, @@ -896,6 +954,7 @@ impl SubmissionPlan { .and_then(|m| m.get(&(list as usize))) .map(|s| SegmentEffects { waits: s.pending_waits.clone(), + write_producers: s.segment_write_producers.clone(), write64_signals: s.write64_signals.clone(), sparse_writes: s.sparse_writes.clone(), cpu_writes: s.cpu_writes.clone(), @@ -1048,6 +1107,7 @@ pub(super) fn clear_segment_state(list: usize) { if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { s.occlusion = Occlusion::default(); s.written_ranges.clear(); + s.segment_write_producers.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); @@ -1203,8 +1263,8 @@ fn pick_queue(last_queue: Option, device: usize, ty: D3D12_COMMAND_LIST_T g.iter().rev().find(|info| info.ty == ty && (device == 0 || info.device == 0 || info.device == device)).map(|info| info.queue) } -fn note_write(list: usize, va: u64, size: u64) { - LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); +fn note_write(list: usize, producer: WriteProducer, va: u64, size: u64) { + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(producer, va, size); } // --------------------------------------------------------------------------------------- @@ -2341,7 +2401,7 @@ pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, if d == s && dst < src + size && src < dst + size { return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) overlap")); } - note_write(this as usize, dst, size); + note_write(this as usize, WriteProducer::InSegmentGpu, dst, size); if d == s { // one window: one buffer cannot be in COPY_SOURCE and COPY_DEST at once (#958), so the // bytes go through a scratch buffer of the list @@ -2599,7 +2659,7 @@ unsafe fn fill(list: *mut c_void, va: u64, size: u64, pat: [u8; 16], unit: u64, let Some(src) = pattern_buffer(list, pat, size) else { return warn(&N, what, format_args!("no pattern buffer for {pat:x?}")); }; - note_write(list as usize, va, size); + note_write(list as usize, WriteProducer::InSegmentGpu, va, size); as_copy_dest(list, d, || copy_buffer_region(list, d, off, src, 0, size)); } @@ -2640,13 +2700,14 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF // the title's own memory: written by the CPU once the GPU is there if super::cpu_writes::writable(va as usize, n as usize) { if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.note_write(WriteProducer::CpuAfterSegment, va, n); s.cpu_writes.push(super::cpu_writes::Write::Immediate(va as usize, words.to_vec())); return; } } return warn(&N, what, format_args!("{va:#x} is not in unified memory")); }; - note_write(list as usize, va, n); + note_write(list as usize, WriteProducer::InSegmentGpu, va, n); let params: Vec = words.iter().enumerate().map(|(i, &w)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + 4 * i as u64, Value: w }).collect(); let modes = vec![mode; words.len()]; type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, *const D3D12_WRITEBUFFERIMMEDIATE_MODE); @@ -2739,7 +2800,7 @@ unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { let i = NEXT_TIMESTAMP.fetch_add(1, Ordering::Relaxed) % TIMESTAMP_SLOTS; type Resolve = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); if let Some((d, off)) = uma_dst { - note_write(list as usize, va, 8); + note_write(list as usize, WriteProducer::InSegmentGpu, va, 8); pc::(list, PC_END_QUERY)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i); as_copy_dest(list, d, || pc::(list, PC_RESOLVE_QUERY_DATA)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i, 1, d, off)); } else if let Some((rb, base)) = readback { @@ -2750,6 +2811,7 @@ unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { }; let rb_raw = rb.as_raw() as usize; let off = i as u64 * 8; + s.note_write(WriteProducer::CpuAfterSegment, va, 8); s.cpu_writes.push(super::cpu_writes::Write::ReadbackU64 { va: va as usize, src: base + off as usize, _buf: rb }); drop(g); pc::(list, PC_END_QUERY)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i); @@ -3446,6 +3508,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let sparse_writes = s.clear_sparse_writes(); let write64_signals = s.clear_write64_signals(); s.written_ranges.clear(); + s.segment_write_producers.clear(); let cpu_writes = std::mem::take(&mut s.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); @@ -3542,6 +3605,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { s.pred_in_state = false; s.occlusion = Occlusion { active: None, ended_early }; s.written_ranges.clear(); + s.segment_write_producers.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); @@ -4238,6 +4302,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.depth_bounds = None; s.occlusion = Occlusion::default(); s.written_ranges.clear(); + s.segment_write_producers.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); @@ -4917,7 +4982,7 @@ mod tests { Format: DXGI_FORMAT_R32_UINT, }); s.depth_bounds = Some((0.25, 0.75)); - s.written_ranges.insert(0x6000, 0x10); + s.written_ranges.insert(WriteProducer::InSegmentGpu, 0x6000, 0x10); } super::super::bind::seed_reset_state_for_test(list, 0x111, 0x222, vec![0x4444]); RESET_TEST_REPLACEMENT_VT.store(replacement as u64, Ordering::SeqCst); @@ -4935,7 +5000,7 @@ mod tests { assert!(s.pso_dirty && s.using_fallback_pso); assert_eq!(s.index_buffer.as_ref().unwrap().BufferLocation, 0x5000); assert_eq!(s.depth_bounds, Some((0.25, 0.75))); - assert_eq!(s.written_ranges.ranges, BTreeMap::from([(0x6000, 0x6010)])); + assert_eq!(s.written_ranges.in_segment_gpu.ranges, BTreeMap::from([(0x6000, 0x6010)])); } assert_eq!( super::super::bind::reset_state_for_test(list), @@ -5092,7 +5157,7 @@ mod tests { #[test] fn written_ranges_detect_same_list_overlap() { let mut s = ListState::default(); - s.note_write(0x1000, 8); + s.note_write(WriteProducer::InSegmentGpu, 0x1000, 8); assert!(s.has_prior_write(0x1000, 4)); assert!(s.has_prior_write(0x1004, 4)); assert!(s.has_prior_write(0x0FFC, 8)); @@ -5100,6 +5165,20 @@ mod tests { assert!(!s.has_prior_write(0x0FF8, 8)); } + #[test] + fn write_producer_ranges_keep_overlapping_kinds_separate() { + let mut s = ListState::default(); + s.note_write(WriteProducer::InSegmentGpu, 0x1000, 0x10); + s.note_write(WriteProducer::CpuAfterSegment, 0x1008, 0x10); + + assert!(s.written_ranges.overlaps(WriteProducer::InSegmentGpu, 0x1008, 8)); + assert!(!s.written_ranges.overlaps(WriteProducer::InSegmentGpu, 0x1010, 8)); + assert!(s.written_ranges.overlaps(WriteProducer::CpuAfterSegment, 0x1010, 8)); + assert!(!s.written_ranges.overlaps(WriteProducer::CpuAfterSegment, 0x1000, 8)); + assert!(s.has_prior_write(0x1008, 8)); + assert!(!s.has_prior_write(0x1010, 8), "deferred CPU writes do not change wait policy in this wave"); + } + #[test] fn recorded_writes_merge_ascending_ranges() { let mut writes = RecordedWrites::default(); @@ -5219,16 +5298,16 @@ mod tests { let old_wait = PendingWait { va: 0x4000, width: 8, comparison: 7, value: 4, mask: u64::MAX, after_write64: true }; { let mut g = LISTS.lock().unwrap(); - g.get_or_insert_with(HashMap::new).insert( - list as usize, - ListState { - pending_waits: vec![old_wait], - write64_signals: vec![(0x4000, 4)], - sparse_writes: vec![(0x5000, 8)], - cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x6000, vec![4])], - ..Default::default() - }, - ); + let mut state = ListState { + pending_waits: vec![old_wait], + write64_signals: vec![(0x4000, 4)], + sparse_writes: vec![(0x5000, 8)], + cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x6000, vec![4])], + ..Default::default() + }; + state.note_write(WriteProducer::InSegmentGpu, 0x4100, 8); + state.note_write(WriteProducer::CpuAfterSegment, 0x4200, 8); + g.get_or_insert_with(HashMap::new).insert(list as usize, state); } let plan = SubmissionPlan::capture(&[list]); @@ -5239,12 +5318,18 @@ mod tests { state.write64_signals = vec![(0x4000, 9)]; state.sparse_writes = vec![(0x7000, 16)]; state.cpu_writes = vec![super::super::cpu_writes::Write::Immediate(0x8000, vec![9])]; + state.written_ranges.clear(); + state.segment_write_producers.clear(); + state.note_write(WriteProducer::CpuAfterSegment, 0x4300, 8); } let effects = &plan.effects[0]; assert_eq!(effects.waits, vec![old_wait]); assert_eq!(effects.write64_signals, vec![(0x4000, 4)]); assert_eq!(effects.sparse_writes, vec![(0x5000, 8)]); + assert!(effects.producer_overlaps(WriteProducer::InSegmentGpu, 0x4100, 8)); + assert!(effects.producer_overlaps(WriteProducer::CpuAfterSegment, 0x4200, 8)); + assert!(!effects.producer_overlaps(WriteProducer::CpuAfterSegment, 0x4300, 8)); match effects.cpu_writes.as_slice() { [super::super::cpu_writes::Write::Immediate(va, words)] => assert_eq!((*va, words.as_slice()), (0x6000, &[4][..])), _ => panic!("unexpected CPU write snapshot"), @@ -5298,7 +5383,7 @@ mod tests { bindings: Bindings { heaps: vec![0x1010, 0x2020], topology: Some(4), stencil: Some(9), ..Default::default() }, ..Default::default() }; - state.written_ranges.insert(0x3000, 0x20); + state.written_ranges.insert(WriteProducer::InSegmentGpu, 0x3000, 0x20); state.occlusion.ended_early.push(earlier_query); assert!(state.occlusion.begin(query, D3D12_QUERY_TYPE_OCCLUSION).is_none()); @@ -5323,12 +5408,14 @@ mod tests { assert_eq!(continued.bindings.heaps, vec![0x1010, 0x2020]); assert_eq!(continued.bindings.topology, Some(4)); assert_eq!(continued.bindings.stencil, Some(9)); - assert!(continued.written_ranges.overlaps(0x3010, 4)); + assert!(continued.written_ranges.overlaps(WriteProducer::InSegmentGpu, 0x3010, 4)); + assert!(continued.segment_write_producers.is_empty(), "a continuation has not produced the carried ranges"); assert!(continued.pending_waits.is_empty() && continued.write64_signals.is_empty() && continued.sparse_writes.is_empty()); assert!(continued.cpu_writes.is_empty() && continued.deferred.is_none() && continued.own_alloc.is_none()); assert_eq!(state.pending_waits.len(), 1, "effects remain on the closed segment"); assert_eq!(state.write64_signals, vec![(0xe550, 6)]); assert_eq!(state.sparse_writes, vec![(0xf660, 8)]); + assert!(state.segment_write_producers.overlaps(WriteProducer::InSegmentGpu, 0x3010, 4)); } #[test] @@ -6322,7 +6409,11 @@ mod tests { write64_bottom_x(list_ptr, bottom_va, 0, 0, BOTTOM_TIMESTAMPS); { let g = LISTS.lock().unwrap(); - assert_eq!(g.as_ref().unwrap()[&(list_ptr as usize)].cpu_writes.len(), 2); + let state = &g.as_ref().unwrap()[&(list_ptr as usize)]; + assert_eq!(state.cpu_writes.len(), 2); + assert!(state.written_ranges.overlaps(WriteProducer::CpuAfterSegment, top_va, 8)); + assert!(state.written_ranges.overlaps(WriteProducer::CpuAfterSegment, bottom_va, 8)); + assert!(!state.written_ranges.overlaps(WriteProducer::InSegmentGpu, top_va, 8)); } // Restore the real vtable before closing and executing on the PC queue. From 5bdaa54ee9b9bece2e7867ad183165bcd8d9d11f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:19:10 -0800 Subject: [PATCH 013/265] Scripts: add reproducible cold and warm performance runs Build a clean locked release and run one workload against fresh ephemeral XCL caches, then the exact same workload against those caches warm. Preserve only logs, reports, and a versioned environment manifest while explicitly leaving the driver cache uncontrolled. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 21 ++++ scripts/perf-run.ps1 | 209 +++++++++++++++++++++++++++++++++++++ scripts/perf-run.tests.ps1 | 108 +++++++++++++++++++ 3 files changed, 338 insertions(+) create mode 100644 scripts/perf-run.ps1 create mode 100644 scripts/perf-run.tests.ps1 diff --git a/README.md b/README.md index 321cc03a9e..33e80879fa 100644 --- a/README.md +++ b/README.md @@ -328,10 +328,31 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder +## Reproducible cold and warm runs + +On a clean commit, build and run the same title once with fresh XCL caches and once with those +exact caches warm: + +```powershell +.\scripts\perf-run.ps1 -Game 'D:\Games\SomeTitle' -OutDir 'D:\xcl-perf\run-1' -Seconds 120 +``` + +The script builds `xcl` in release mode and refuses a dirty worktree or a non-empty output +folder. Both runs use a new temporary `XCL_DATA_ROOT` and `XCL_DXIL_CACHE`; the warm run reuses +the cold run's directories. They are deleted afterwards, and existing user caches are never read, +changed, or deleted. The output folder contains only each run's `xcl.log` and `report.json`, plus +a versioned `manifest.json` with the commit, run order, hardware/toolchain, selected XCL +environment, cache identity, durations, and exit status. It contains no game files or cache data. + +The manifest calls these states **XCL-cold** and **XCL-warm**. GPU driver caches are +driver-controlled and are explicitly recorded as `uncontrolled`; this is not a fully cold-driver +benchmark. + ## Tests ```powershell .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace +.\scripts\perf-run.tests.ps1 # cold/warm runner fixture (no game is run) ``` Unit tests, an end-to-end test with our own "console title" (`tests/testtitle`) and GPU tests diff --git a/scripts/perf-run.ps1 b/scripts/perf-run.ps1 new file mode 100644 index 0000000000..277c6cf68c --- /dev/null +++ b/scripts/perf-run.ps1 @@ -0,0 +1,209 @@ +# Reproducible paired runtime measurement: an XCL-cold run followed by an XCL-warm run +# against the same ephemeral XCL data and DXIL cache. The GPU driver's own cache is not +# controlled and is named as such in the manifest. +param( + [Parameter(Mandatory = $true)][string]$Game, + [Parameter(Mandatory = $true)][string]$OutDir, + [int]$Seconds = 120 +) +$ErrorActionPreference = 'Stop' + +if ($Seconds -lt 1) { throw '-Seconds must be at least 1' } +if (-not (Test-Path -LiteralPath $Game -PathType Container)) { throw "game folder not found: $Game" } +$gamePath = [IO.Path]::GetFullPath($Game) +$root = Split-Path $PSScriptRoot -Parent + +function Run-Git([string[]]$Arguments) { + $out = @(& git.exe -C $root @Arguments) + if ($LASTEXITCODE -ne 0) { throw "git $($Arguments -join ' ') failed with exit code $LASTEXITCODE" } + return $out +} + +$commit = ((Run-Git -Arguments @('rev-parse', 'HEAD')) -join '').Trim() +$dirtyLines = @(Run-Git -Arguments @('status', '--porcelain', '--untracked-files=all')) +if ($dirtyLines.Count -ne 0) { throw 'perf-run requires a clean worktree so the executable names an exact commit' } + +if (Test-Path -LiteralPath $OutDir) { + if (@(Get-ChildItem -LiteralPath $OutDir -Force).Count -ne 0) { throw "output folder is not empty: $OutDir" } +} else { + $null = New-Item -ItemType Directory -Path $OutDir +} +$outPath = [IO.Path]::GetFullPath($OutDir) + +Push-Location $root +try { + & cargo build --locked --release -p xcl + if ($LASTEXITCODE -ne 0) { throw "release build failed with exit code $LASTEXITCODE" } +} finally { + Pop-Location +} +if (@(Run-Git -Arguments @('status', '--porcelain', '--untracked-files=all')).Count -ne 0) { + throw 'the worktree changed during the release build' +} + +$xcl = Join-Path $root 'target\release\xcl.exe' +# Test scripts use a command file after still exercising the clean-tree and release-build steps. +if ($env:XCL_PERF_RUN_TESTING -eq '1' -and $env:XCL_PERF_RUN_TEST_XCL) { + $xcl = $env:XCL_PERF_RUN_TEST_XCL +} +if (-not (Test-Path -LiteralPath $xcl)) { throw "release build did not produce $xcl" } + +$cacheId = [guid]::NewGuid().ToString('n') +$cacheRoot = Join-Path ([IO.Path]::GetTempPath()) ("xcl-perf-$cacheId") +$dataRoot = Join-Path $cacheRoot 'data' +$dxilCache = Join-Path $cacheRoot 'dxil' +$null = New-Item -ItemType Directory -Path $dataRoot +$null = New-Item -ItemType Directory -Path $dxilCache + +$environmentNames = @( + 'XCL_ACTIVITY', 'XCL_ADAPTER', 'XCL_DEVICE_TYPE', 'XCL_DIRECT_DXIL', + 'XCL_DXC_THREADS', 'XCL_FRAME_INTERVAL_US', 'XCL_HEAP_WINDOWS', + 'XCL_LAZY_PSO', 'XCL_NETWORK', 'XCL_PRESS_AT', 'XCL_PSO_PRELOAD', + 'XCL_REQUIRE_GPU', 'XCL_RUN_SECONDS', 'XCL_STALL_TRACE' +) +$changedNames = @('XCL_ACTIVITY', 'XCL_DATA_ROOT', 'XCL_DXIL_CACHE', 'XCL_NETWORK', 'XCL_RUN_SECONDS', 'XCL_STALL_TRACE') +$savedEnvironment = @{} +foreach ($name in $changedNames) { + $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') +} + +function Video-Driver([string]$Adapter) { + try { + $controllers = @(Get-CimInstance Win32_VideoController) + $controller = $controllers | Where-Object { + $Adapter -and ($Adapter.Contains($_.Name) -or $_.Name.Contains($Adapter)) + } | Select-Object -First 1 + if (-not $controller) { $controller = $controllers | Where-Object { $_.Name -notmatch 'Basic' } | Select-Object -First 1 } + return $controller.DriverVersion + } catch { + return $null + } +} + +function Invoke-PerfRun([string]$Mode, [int]$Order) { + $runName = '{0:d2}-{1}' -f $Order, $Mode + $artifactDir = Join-Path (Join-Path $outPath 'runs') $runName + $null = New-Item -ItemType Directory -Path $artifactDir -Force + + $psi = New-Object System.Diagnostics.ProcessStartInfo + if ($xcl -match '\.(cmd|bat)$') { + $psi.FileName = 'cmd.exe' + $psi.Arguments = '/d /c ""' + $xcl + '" run "' + $gamePath + '""' + } else { + $psi.FileName = $xcl + $psi.Arguments = 'run "' + $gamePath + '"' + } + $psi.WorkingDirectory = $root + $psi.UseShellExecute = $false + $psi.CreateNoWindow = $true + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + $psi.StandardOutputEncoding = [Text.Encoding]::UTF8 + $psi.StandardErrorEncoding = [Text.Encoding]::UTF8 + + $process = New-Object System.Diagnostics.Process + $process.StartInfo = $psi + $watch = [Diagnostics.Stopwatch]::StartNew() + $null = $process.Start() + $stdoutTask = $process.StandardOutput.ReadToEndAsync() + $stderrTask = $process.StandardError.ReadToEndAsync() + $timedOut = -not $process.WaitForExit(($Seconds + 120) * 1000) + if ($timedOut -and -not $process.HasExited) { $process.Kill() } + $process.WaitForExit() + $watch.Stop() + $stdout = $stdoutTask.Result + $null = $stderrTask.Result + + $logLine = ($stdout -split '\r?\n' | Where-Object { $_ -match '^Log:\s+(.+)$' } | Select-Object -Last 1) + if (-not $logLine) { throw "XCL printed no log path during the $Mode run" } + $log = ($logLine -replace '^Log:\s+', '').Trim() + if (-not (Test-Path -LiteralPath $log)) { throw "XCL's $Mode log does not exist: $log" } + Copy-Item -LiteralPath $log -Destination (Join-Path $artifactDir 'xcl.log') + + $sourceReport = Join-Path (Split-Path $log -Parent) 'report.json' + $reportArtifact = $null + $adapter = $null + if (Test-Path -LiteralPath $sourceReport) { + $reportArtifact = 'report.json' + Copy-Item -LiteralPath $sourceReport -Destination (Join-Path $artifactDir $reportArtifact) + try { + $adapter = ((Get-Content -LiteralPath $sourceReport -Raw -Encoding utf8 | ConvertFrom-Json).d3d12.adapter -replace '\s*\([^()]*VRAM\)$', '') + } catch { } + } + + return [ordered]@{ + order = $Order + cache_state = "xcl-$Mode" + duration_requested_seconds = $Seconds + duration_actual_ms = $watch.ElapsedMilliseconds + exit_code = if ($timedOut) { $null } else { $process.ExitCode } + timed_out = $timedOut + gpu = $adapter + gpu_driver = Video-Driver $adapter + artifacts = [ordered]@{ log = 'xcl.log'; report = $reportArtifact } + } +} + +try { + $env:XCL_DATA_ROOT = $dataRoot + $env:XCL_DXIL_CACHE = $dxilCache + $env:XCL_NETWORK = '0' + $env:XCL_RUN_SECONDS = "$Seconds" + $env:XCL_ACTIVITY = '1' + $env:XCL_STALL_TRACE = '1' + + $recordedEnvironment = [ordered]@{} + foreach ($name in $environmentNames) { + $recordedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') + } + + $runs = @() + $runs += Invoke-PerfRun 'cold' 1 + $runs += Invoke-PerfRun 'warm' 2 + + $cpu = $null + $windows = $null + try { $cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name } catch { } + try { + $os = Get-CimInstance Win32_OperatingSystem + $windows = "$($os.Caption) $($os.Version) build $($os.BuildNumber)" + } catch { } + $rust = (& rustc -Vv) -join [Environment]::NewLine + if ($LASTEXITCODE -ne 0) { throw 'rustc -Vv failed' } + $sha = [Security.Cryptography.SHA256]::Create() + $workloadId = -join ($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes((Split-Path $gamePath -Leaf).Trim()))[0..7] | ForEach-Object { $_.ToString('x2') }) + $sha.Dispose() + + $manifest = [ordered]@{ + schema = 'xcl-perf-run' + version = 1 + commit = $commit + dirty = $false + build = [ordered]@{ profile = 'release'; command = 'cargo build --locked --release -p xcl' } + workload_id = $workloadId + run_order = @('xcl-cold', 'xcl-warm') + system = [ordered]@{ cpu = $cpu; windows = $windows; rust = $rust } + environment = $recordedEnvironment + cache = [ordered]@{ + identity = $cacheId + xcl_data = 'fresh for cold; same ephemeral directory reused for warm' + dxil = 'fresh for cold; same ephemeral directory reused for warm' + driver = 'uncontrolled' + } + runs = $runs + } + $manifest | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $outPath 'manifest.json') -Encoding utf8 + Write-Host "Performance artifacts: $outPath" +} finally { + foreach ($name in $changedNames) { + $old = $savedEnvironment[$name] + if ($null -eq $old) { + Remove-Item -Path "Env:$name" -ErrorAction SilentlyContinue + } else { + Set-Item -Path "Env:$name" -Value $old + } + } + if (Test-Path -LiteralPath $cacheRoot) { + Remove-Item -LiteralPath $cacheRoot -Recurse -Force + } +} diff --git a/scripts/perf-run.tests.ps1 b/scripts/perf-run.tests.ps1 new file mode 100644 index 0000000000..f2863fca63 --- /dev/null +++ b/scripts/perf-run.tests.ps1 @@ -0,0 +1,108 @@ +# Run on Windows with powershell.exe or pwsh.exe. Uses a clean temporary repository and mock +# cargo/XCL commands; no game executable is run. +$ErrorActionPreference = 'Stop' +$runnerSource = Join-Path $PSScriptRoot 'perf-run.ps1' +$fixture = Join-Path ([IO.Path]::GetTempPath()) ('xcl-perf-run-test-' + [guid]::NewGuid()) +$repo = Join-Path $fixture 'repo' +$scripts = Join-Path $repo 'scripts' +$game = Join-Path $fixture 'Mock Game' +$out = Join-Path $fixture 'artifacts' +$bin = Join-Path $fixture 'bin' +$userData = Join-Path $fixture 'user-data' +$userDxil = Join-Path $fixture 'user-dxil' +$cargoMarker = Join-Path $fixture 'cargo.txt' +$mockXcl = Join-Path $bin 'mock-xcl.cmd' +$oldPath = $env:PATH +$oldTest = $env:XCL_PERF_RUN_TESTING +$oldTestXcl = $env:XCL_PERF_RUN_TEST_XCL +$oldData = $env:XCL_DATA_ROOT +$oldDxil = $env:XCL_DXIL_CACHE +$oldPress = $env:XCL_PRESS_AT + +try { + $null = New-Item -ItemType Directory -Path $scripts, $game, $bin, $userData, $userDxil + Copy-Item -LiteralPath $runnerSource -Destination (Join-Path $scripts 'perf-run.ps1') + 'target/' | Set-Content -LiteralPath (Join-Path $repo '.gitignore') -Encoding Ascii + 'not copied' | Set-Content -LiteralPath (Join-Path $game 'game-data.bin') -Encoding Ascii + 'keep' | Set-Content -LiteralPath (Join-Path $userData 'sentinel.txt') -Encoding Ascii + 'keep' | Set-Content -LiteralPath (Join-Path $userDxil 'sentinel.txt') -Encoding Ascii + + @' +@echo off +echo %* > "%MOCK_CARGO_MARKER%" +exit /b 0 +'@ | Set-Content -LiteralPath (Join-Path $bin 'cargo.cmd') -Encoding Ascii + @' +@echo off +echo rustc 1.test +echo host: x86_64-pc-windows-msvc +exit /b 0 +'@ | Set-Content -LiteralPath (Join-Path $bin 'rustc.cmd') -Encoding Ascii + @' +@echo off +set STATE=warm +if not exist "%XCL_DXIL_CACHE%\seen" set STATE=cold +if exist "%XCL_DXIL_CACHE%\seen" goto marker_done +echo seen>"%XCL_DXIL_CACHE%\seen" +:marker_done +if not exist "%XCL_DATA_ROOT%\MockTitle\logs" mkdir "%XCL_DATA_ROOT%\MockTitle\logs" +echo cache=%STATE%>"%XCL_DATA_ROOT%\MockTitle\logs\xcl.log" +echo {"d3d12":{"adapter":"Mock GPU"}}>"%XCL_DATA_ROOT%\MockTitle\logs\report.json" +echo Log: %XCL_DATA_ROOT%\MockTitle\logs\xcl.log +exit /b 0 +'@ | Set-Content -LiteralPath $mockXcl -Encoding Ascii + + & git.exe -C $repo init | Out-Null + & git.exe -C $repo add . + & git.exe -C $repo -c user.name='XCL test' -c user.email='xcl-test@example.invalid' -c commit.gpgsign=false commit -m fixture | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'could not create clean fixture repository' } + + $env:PATH = $bin + [IO.Path]::PathSeparator + $oldPath + $env:MOCK_CARGO_MARKER = $cargoMarker + $env:XCL_PERF_RUN_TESTING = '1' + $env:XCL_PERF_RUN_TEST_XCL = $mockXcl + $env:XCL_DATA_ROOT = $userData + $env:XCL_DXIL_CACHE = $userDxil + $env:XCL_PRESS_AT = '20:A,24:A' + + & (Join-Path $scripts 'perf-run.ps1') -Game $game -OutDir $out -Seconds 2 + if ($LASTEXITCODE -ne 0) { throw "perf-run.ps1 exited with $LASTEXITCODE" } + + $manifest = Get-Content -LiteralPath (Join-Path $out 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + if ($manifest.schema -ne 'xcl-perf-run' -or $manifest.version -ne 1) { throw 'wrong manifest schema/version' } + if ($manifest.dirty -ne $false -or $manifest.build.profile -ne 'release') { throw 'build identity was not recorded' } + if (($manifest.run_order -join ',') -ne 'xcl-cold,xcl-warm') { throw 'run order was not cold then warm' } + if ($manifest.cache.driver -ne 'uncontrolled') { throw 'driver cache was not labelled uncontrolled' } + if ($manifest.environment.XCL_PRESS_AT -ne '20:A,24:A') { throw 'input schedule was not recorded' } + if ($manifest.runs.Count -ne 2 -or $manifest.runs[0].cache_state -ne 'xcl-cold' -or $manifest.runs[1].cache_state -ne 'xcl-warm') { throw 'run records are incomplete' } + if ((Get-Content -LiteralPath (Join-Path $out 'runs\01-cold\xcl.log') -Raw) -notmatch 'cache=cold') { throw 'cold run did not start with a fresh DXIL cache' } + if ((Get-Content -LiteralPath (Join-Path $out 'runs\02-warm\xcl.log') -Raw) -notmatch 'cache=warm') { throw 'warm run did not reuse the cold cache' } + if (-not (Test-Path -LiteralPath (Join-Path $out 'runs\01-cold\report.json')) -or -not (Test-Path -LiteralPath (Join-Path $out 'runs\02-warm\report.json'))) { throw 'reports were not preserved' } + $artifactFiles = @(Get-ChildItem -LiteralPath $out -Recurse -File) + $unexpectedArtifacts = @($artifactFiles | Where-Object { $_.Name -notin @('manifest.json', 'xcl.log', 'report.json') }) + if ($artifactFiles.Count -ne 5 -or $unexpectedArtifacts.Count -ne 0) { throw 'the artifact folder contains something other than logs, reports, and the manifest' } + if ($env:XCL_DATA_ROOT -ne $userData -or $env:XCL_DXIL_CACHE -ne $userDxil) { throw 'the caller environment was not restored' } + if (-not (Test-Path -LiteralPath (Join-Path $userData 'sentinel.txt')) -or -not (Test-Path -LiteralPath (Join-Path $userDxil 'sentinel.txt'))) { throw 'a user cache was touched' } + if (Test-Path -LiteralPath (Join-Path ([IO.Path]::GetTempPath()) ("xcl-perf-$($manifest.cache.identity)"))) { throw 'the ephemeral cache was not removed' } + if ((Get-Content -LiteralPath $cargoMarker -Raw) -notmatch 'build --locked --release -p xcl') { throw 'release build command was not run' } + + Add-Content -LiteralPath (Join-Path $repo '.gitignore') -Value '# dirty' + $refused = $false + try { + & (Join-Path $scripts 'perf-run.ps1') -Game $game -OutDir (Join-Path $fixture 'dirty-out') -Seconds 2 + } catch { + $refused = $_.Exception.Message -match 'clean worktree' + } + if (-not $refused) { throw 'a dirty worktree was not refused' } + + Write-Host 'perf-run tests: all assertions passed' +} finally { + $env:PATH = $oldPath + $env:XCL_PERF_RUN_TESTING = $oldTest + $env:XCL_PERF_RUN_TEST_XCL = $oldTestXcl + $env:XCL_DATA_ROOT = $oldData + $env:XCL_DXIL_CACHE = $oldDxil + $env:XCL_PRESS_AT = $oldPress + Remove-Item Env:MOCK_CARGO_MARKER -ErrorAction SilentlyContinue + if (Test-Path -LiteralPath $fixture) { Remove-Item -LiteralPath $fixture -Recurse -Force } +} From 0fef9d5ad602da9f2b1a6f8d62d865a4db2d70fa Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:21:02 -0800 Subject: [PATCH 014/265] D3D12.X: define canonical compute build identity Capture every semantic input to translated compute preparation before work begins, while excluding title root-signature, cached-blob, and padding noise. Retain the identity inertly on each build so coalescing can be added as a separate change. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/pso.rs | 42 +++++ crates/xcl/src/hle/d3d12x/pso_async.rs | 35 +++- crates/xcl/src/hle/d3d12x/real.rs | 12 +- .../src/hle/d3d12x/real/compute_build_key.rs | 167 ++++++++++++++++++ 4 files changed, 250 insertions(+), 6 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/real/compute_build_key.rs diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b8b0cde0f1..7f0217ce0d 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -26,6 +26,48 @@ pub enum Stage { Mesh, } +/// Output-affecting process policy for a compute shader translation. This is kept semantic: +/// diagnostic/cache switches are absent, while environment values are normalized to the choices +/// the translators actually make. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) struct ComputePolicyKey { + pub direct: bool, + pub structured: bool, + pub precise_x64_masks: bool, + pub wave64_spin: bool, + pub safe_barrier: bool, + pub direct_compact: Option, + pub direct_compact_nest: Option, + pub direct_piece_limit: usize, + pub per_lane: bool, + pub disabled_dxil_optimizations: u8, +} + +pub(crate) fn compute_policy_key() -> ComputePolicyKey { + let direct = crate::gpu::dxil::kernel::enabled(); + let disabled = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); + let skip = |name: &str| disabled.split(',').any(|v| { + let v = v.trim(); + v == name || v == "all" + }); + ComputePolicyKey { + direct, + structured: std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none(), + precise_x64_masks: std::env::var_os("XCL_X64_ALL_MASKS").is_none(), + wave64_spin: std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0"), + safe_barrier: std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0"), + // The HLSL path can route enormous compute programs through the direct translator too. + direct_compact: crate::gpu::dxil::kernel::compact_mode(), + direct_compact_nest: crate::gpu::dxil::kernel::compact_nest_tag(), + direct_piece_limit: crate::gpu::dxil::kernel::dispatch_piece_limit(), + per_lane: crate::gpu::recomp::lower_dxil::enabled(), + disabled_dxil_optimizations: ["phi", "cse", "dce", "merge"] + .iter() + .enumerate() + .fold(0, |bits, (i, name)| bits | ((skip(name) as u8) << i)), + } +} + /// A console (xbox-native) shader container? pub fn is_console(blob: &[u8]) -> bool { xbox::is_xbox(blob) || fspx(blob).is_some() diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index e65b3a7a25..44294e9d35 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -31,6 +31,8 @@ struct Pending { /// A pipeline build independent of the title-visible stand-in that requested it. /// Each `Pending` has a unique build for now; separating the ownership does not deduplicate work. struct Build { + /// Canonical preparation identity; retained for later coalescing, not consulted yet. + _compute_key: Option, /// the build, until a worker – or a bind that cannot wait for the queue – takes it job: Mutex>, /// the build went to the workers (a lazy one goes on its first `resolve`) @@ -127,7 +129,12 @@ fn run_build(build: &Arc, job: Job) { impl Build { fn new(job: Job, sent: bool) -> Self { + Self::new_keyed(job, sent, None) + } + + fn new_keyed(job: Job, sent: bool, compute_key: Option) -> Self { Self { + _compute_key: compute_key, job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(sent), real: AtomicUsize::new(0), @@ -477,7 +484,16 @@ pub fn release(p: usize) { /// `standin` went to the title; `job` builds the real pipeline on a worker. pub fn submit(standin: usize, compute: bool, job: Job) { - submit_as(standin, compute, job, true, 0); + submit_keyed(standin, compute, job, None); +} + +pub(super) fn submit_keyed( + standin: usize, + compute: bool, + job: Job, + compute_key: Option, +) { + submit_as(standin, compute, job, true, 0, compute_key); } /// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get @@ -493,11 +509,22 @@ pub fn lazy() -> bool { /// `submit`, sent to the workers only on its first `resolve` (`lazy`) – or now, at a low /// priority, when an earlier run used a pipeline of these shaders (`key`, 0 = none; `used`). pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { - submit_as(standin, compute, job, false, key); + submit_lazy_keyed(standin, compute, job, key, None); +} + +pub(super) fn submit_lazy_keyed( + standin: usize, + compute: bool, + job: Job, + key: u64, + compute_key: Option, +) { + submit_as(standin, compute, job, false, key, compute_key); } -fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { - let build = Arc::new(Build::new(job, false)); +fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, compute_key: Option) { + debug_assert!(compute || compute_key.is_none()); + let build = Arc::new(Build::new_keyed(job, false, compute_key)); let p = Arc::new(Pending { build: build.clone(), driver: AtomicUsize::new(0), diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9cdcabfe22..c13d0b8d46 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5363,6 +5363,8 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const // non-blocking pipeline creation (see `pso_async`) // --------------------------------------------------------------------------------------- +pub(in crate::hle::d3d12x) mod compute_build_key; + /// A pipeline description that owns what it points to (shader blobs, input layout and its /// semantic names), so a worker can build the pipeline after the title's memory is gone. /// The root signature pointer is kept as is (the translated paths replace it). @@ -5631,6 +5633,12 @@ unsafe fn go_background( } let dev = Dev(this as usize, f as usize); let key = owned.shaders_key(); + let build_key = match &owned { + OwnedDesc::Compute(desc, shaders) => shaders.first().map(|shader| { + compute_build_key::ComputeBuildKey::capture(this as usize, desc, shader, wave32_only(this)) + }), + _ => None, + }; // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); let job: super::pso_async::Job = Box::new(move || { @@ -5642,9 +5650,9 @@ unsafe fn go_background( } }); if super::pso_async::lazy() { - super::pso_async::submit_lazy(*ppv as usize, compute, job, key); + super::pso_async::submit_lazy_keyed(*ppv as usize, compute, job, key, build_key); } else { - super::pso_async::submit(*ppv as usize, compute, job); + super::pso_async::submit_keyed(*ppv as usize, compute, job, build_key); } if driver != 0 { super::pso_async::shared(*ppv as usize, driver); diff --git a/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs b/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs new file mode 100644 index 0000000000..1f0d4e4dcd --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs @@ -0,0 +1,167 @@ +use windows::Win32::Graphics::Direct3D12::D3D12_COMPUTE_PIPELINE_STATE_DESC; + +use crate::gpu::recomp::pso::ComputePolicyKey; + +/// The translated compute root-signature layout. A version change must change this tag. +const COMPUTE_ABI_SCHEMA: u32 = 1; + +/// Canonical identity of a requested compute build, before translation begins. +/// +/// `device` is safe identity, rather than an unretained COM pointer: the real backend owns its +/// device reference for the process lifetime. The ABI static-sampler set is transitively and +/// collision-freely identified by the complete shader bytes, translation policy, and sampler +/// base; those bytes also identify the program's intrinsic wave mode. The title root signature +/// and cached PSO are intentionally absent: translation replaces both before calling the PC driver. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(in crate::hle::d3d12x) struct ComputeBuildKey { + device: usize, + node_mask: u32, + flags: i32, + shader: Box<[u8]>, + windows: u32, + split_wave64: bool, + policy: ComputePolicyKey, + abi_schema: u32, + static_sampler_base: u32, +} + +impl ComputeBuildKey { + pub(in crate::hle::d3d12x) fn capture( + device: usize, + desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + shader: &[u8], + split_wave64: bool, + ) -> Self { + Self::from_descriptor( + device, + desc, + shader, + crate::gpu::recomp::pso::mem_windows(), + split_wave64, + crate::gpu::recomp::pso::compute_policy_key(), + ) + } + + fn from_descriptor( + device: usize, + desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + shader: &[u8], + windows: u32, + split_wave64: bool, + policy: ComputePolicyKey, + ) -> Self { + Self::from_parts(device, desc.NodeMask, desc.Flags.0, shader, windows, split_wave64, policy) + } + + fn from_parts( + device: usize, + node_mask: u32, + flags: i32, + shader: &[u8], + windows: u32, + split_wave64: bool, + policy: ComputePolicyKey, + ) -> Self { + debug_assert_ne!(device, 0); + Self { + device, + node_mask, + flags, + shader: shader.into(), + windows, + split_wave64, + policy, + abi_schema: COMPUTE_ABI_SCHEMA, + static_sampler_base: 0, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn policy() -> ComputePolicyKey { + ComputePolicyKey { + direct: false, + structured: true, + precise_x64_masks: true, + wave64_spin: true, + safe_barrier: true, + direct_compact: None, + direct_compact_nest: None, + direct_piece_limit: 0, + per_lane: false, + disabled_dxil_optimizations: 0, + } + } + + fn key() -> ComputeBuildKey { + ComputeBuildKey::from_parts(1, 2, 3, &[4, 5], 6, false, policy()) + } + + #[test] + fn every_compute_build_input_splits_the_key() { + let base = key(); + macro_rules! different { + ($field:ident, $value:expr) => {{ + let mut other = base.clone(); + other.$field = $value; + assert_ne!(base, other, stringify!($field)); + }}; + } + different!(device, 9); + different!(node_mask, 9); + different!(flags, 9); + different!(shader, vec![4, 6].into_boxed_slice()); + different!(windows, 9); + different!(split_wave64, true); + different!(abi_schema, 9); + different!(static_sampler_base, 9); + + let mutate_policy = |f: fn(&mut ComputePolicyKey)| { + let mut other = base.clone(); + f(&mut other.policy); + assert_ne!(base, other); + }; + mutate_policy(|p| p.direct = true); + mutate_policy(|p| p.structured = false); + mutate_policy(|p| p.precise_x64_masks = false); + mutate_policy(|p| p.wave64_spin = false); + mutate_policy(|p| p.safe_barrier = false); + mutate_policy(|p| p.direct_compact = Some(true)); + mutate_policy(|p| p.direct_compact_nest = Some("outer".into())); + mutate_policy(|p| p.direct_piece_limit = 1); + mutate_policy(|p| p.per_lane = true); + mutate_policy(|p| p.disabled_dxil_optimizations = 1); + } + + #[test] + fn shader_identity_compares_all_bytes_not_only_a_digest() { + let mut other = key(); + other.shader = vec![4, 5, 0].into_boxed_slice(); + assert_ne!(key(), other); + assert_eq!(key(), key()); + } + + #[test] + fn descriptor_padding_is_not_part_of_the_key() { + let mut a = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + let mut b = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + a.NodeMask = 7; + b.NodeMask = 7; + a.Flags = windows::Win32::Graphics::Direct3D12::D3D12_PIPELINE_STATE_FLAGS(1); + b.Flags = windows::Win32::Graphics::Direct3D12::D3D12_PIPELINE_STATE_FLAGS(1); + let padding = std::mem::offset_of!(D3D12_COMPUTE_PIPELINE_STATE_DESC, NodeMask) + + std::mem::size_of::(); + let padding_end = std::mem::offset_of!(D3D12_COMPUTE_PIPELINE_STATE_DESC, CachedPSO); + assert!(padding_end > padding); + unsafe { + std::ptr::write_bytes((&mut b as *mut _ as *mut u8).add(padding), 0xa5, padding_end - padding); + } + assert_eq!( + ComputeBuildKey::from_descriptor(1, &a, &[2, 3], 4, false, policy()), + ComputeBuildKey::from_descriptor(1, &b, &[2, 3], 4, false, policy()), + ); + } +} From fd237b1b6ebb59b9e714c675370f47ef26984459 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:25:45 -0800 Subject: [PATCH 015/265] Scripts: compare reproducible performance artifacts Validate that baseline and candidate runs describe the same workload, environment, system, GPU, driver, and schedule. Report raw cold/warm duration and structured stall deltas without inventing percentages or statistical significance. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 13 ++ scripts/perf-compare.ps1 | 211 +++++++++++++++++++++++++++++++++ scripts/perf-compare.tests.ps1 | 111 +++++++++++++++++ 3 files changed, 335 insertions(+) create mode 100644 scripts/perf-compare.ps1 create mode 100644 scripts/perf-compare.tests.ps1 diff --git a/README.md b/README.md index 33e80879fa..d598768a3f 100644 --- a/README.md +++ b/README.md @@ -348,11 +348,24 @@ The manifest calls these states **XCL-cold** and **XCL-warm**. GPU driver caches driver-controlled and are explicitly recorded as `uncontrolled`; this is not a fully cold-driver benchmark. +Compare two completed artifact folders without modifying them: + +```powershell +.\scripts\perf-compare.ps1 -Baseline 'D:\xcl-perf\main' -Candidate 'D:\xcl-perf\change' > comparison.json +``` + +The console shows raw cold/warm duration, exit/timeout state, and available stall totals, counts, +and maxima. The redirected JSON keeps those values, raw deltas, and log2 histograms. The tool +refuses different workloads, run order, requested duration, runtime environment, system, GPU, or +GPU driver. Missing reports and stall summaries are labelled as missing; it does not infer +significance or percentages. + ## Tests ```powershell .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace .\scripts\perf-run.tests.ps1 # cold/warm runner fixture (no game is run) +.\scripts\perf-compare.tests.ps1 # comparison fixture (synthetic artifacts) ``` Unit tests, an end-to-end test with our own "console title" (`tests/testtitle`) and GPU tests diff --git a/scripts/perf-compare.ps1 b/scripts/perf-compare.ps1 new file mode 100644 index 0000000000..c78dc8c3c0 --- /dev/null +++ b/scripts/perf-compare.ps1 @@ -0,0 +1,211 @@ +# Compare two version-1 perf-run artifact folders without changing either one. Concise text goes +# to the host; the success stream is one machine-readable JSON document. +param( + [Parameter(Mandatory = $true)][string]$Baseline, + [Parameter(Mandatory = $true)][string]$Candidate +) +$ErrorActionPreference = 'Stop' + +function Read-Json([string]$Path) { + if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "missing artifact: $Path" } + try { + return Get-Content -LiteralPath $Path -Raw -Encoding utf8 | ConvertFrom-Json + } catch { + throw "invalid JSON in $($Path): $($_.Exception.Message)" + } +} + +function Has-Property($Object, [string]$Name) { + return $null -ne $Object -and $null -ne $Object.PSObject.Properties[$Name] +} + +function Require-Same-Property($Before, $After, [string]$Name, [string]$Description) { + $beforeHas = Has-Property $Before $Name + $afterHas = Has-Property $After $Name + if ($beforeHas -ne $afterHas) { throw "$Description differs; runs are incomparable" } + if ($beforeHas) { + $beforeValue = $Before.$Name | ConvertTo-Json -Compress -Depth 6 + $afterValue = $After.$Name | ConvertTo-Json -Compress -Depth 6 + if ($beforeValue -ne $afterValue) { throw "$Description differs; runs are incomparable" } + } +} + +function Read-Manifest([string]$Root, [string]$Side) { + $manifest = Read-Json (Join-Path $Root 'manifest.json') + if ($manifest.schema -ne 'xcl-perf-run' -or [int]$manifest.version -ne 1) { + throw "$Side has unsupported manifest schema/version" + } + if ($manifest.dirty -ne $false -or $manifest.build.profile -ne 'release') { + throw "$Side is not a clean release run" + } + if ([string]::IsNullOrWhiteSpace([string]$manifest.commit) -or -not (Has-Property $manifest 'environment')) { + throw "$Side manifest is missing commit/environment" + } + if ([string]::IsNullOrWhiteSpace([string]$manifest.workload_id)) { + throw "$Side has no workload_id" + } + $labels = @($manifest.run_order) + if ($labels.Count -ne 2 -or $labels[0] -ne 'xcl-cold' -or $labels[1] -ne 'xcl-warm') { + throw "$Side run_order must be xcl-cold, xcl-warm" + } + $runs = @($manifest.runs) + if ($runs.Count -ne 2) { throw "$Side must contain exactly two run records" } + for ($i = 0; $i -lt 2; $i++) { + if ([int]$runs[$i].order -ne $i + 1 -or $runs[$i].cache_state -ne $labels[$i]) { + throw "$Side run record $($i + 1) does not match run_order" + } + if (-not (Has-Property $runs[$i] 'duration_requested_seconds') -or $null -eq $runs[$i].duration_requested_seconds) { + throw "$Side run record $($i + 1) has no requested duration" + } + } + return $manifest +} + +function Read-Stalls([string]$Root, [int]$Order, [string]$Label) { + $mode = $Label.Substring(4) + $report = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'report.json')) + if (-not (Test-Path -LiteralPath $report -PathType Leaf)) { + return [ordered]@{ status = 'missing_report'; aggregates = @{} } + } + $json = Read-Json $report + if (-not (Has-Property $json 'stalls') -or $null -eq $json.stalls) { + return [ordered]@{ status = 'missing_stalls'; aggregates = @{} } + } + if ([int]$json.stalls.version -ne 1) { throw "unsupported stall summary in $report" } + $aggregates = @{} + foreach ($aggregate in @($json.stalls.aggregates)) { + $kind = [string]$aggregate.kind + if ([string]::IsNullOrWhiteSpace($kind) -or $aggregates.ContainsKey($kind)) { + throw "invalid or duplicate stall kind in $report" + } + $aggregates[$kind] = $aggregate + } + return [ordered]@{ status = 'present'; aggregates = $aggregates } +} + +function Number-Or-Null($Object, [string]$Name) { + if ($null -eq $Object -or -not (Has-Property $Object $Name) -or $null -eq $Object.$Name) { return $null } + return [long]$Object.$Name +} + +function Delta-Or-Null($Before, $After) { + if ($null -eq $Before -or $null -eq $After) { return $null } + return [long]$After - [long]$Before +} + +function Bool-Or-Null($Object, [string]$Name) { + if ($null -eq $Object -or -not (Has-Property $Object $Name) -or $null -eq $Object.$Name) { return $null } + return [bool]$Object.$Name +} + +function Aggregate-Or-Null($Aggregate) { + if ($null -eq $Aggregate) { return $null } + return [ordered]@{ + count = Number-Or-Null $Aggregate 'count' + total_ns = Number-Or-Null $Aggregate 'total_ns' + max_ns = Number-Or-Null $Aggregate 'max_ns' + histogram_log2_ns = @($Aggregate.histogram_log2_ns | ForEach-Object { [long]$_ }) + } +} + +function Compare-Aggregates($BeforeSet, $AfterSet) { + $kinds = @($BeforeSet.Keys) + @($AfterSet.Keys) | Sort-Object -Unique + $out = @() + foreach ($kind in $kinds) { + $beforeRaw = if ($BeforeSet.ContainsKey($kind)) { $BeforeSet[$kind] } else { $null } + $afterRaw = if ($AfterSet.ContainsKey($kind)) { $AfterSet[$kind] } else { $null } + $before = Aggregate-Or-Null $beforeRaw + $after = Aggregate-Or-Null $afterRaw + $histogramDelta = $null + if ($null -ne $before -and $null -ne $after -and $before.histogram_log2_ns.Count -eq $after.histogram_log2_ns.Count) { + $histogramDelta = for ($i = 0; $i -lt $before.histogram_log2_ns.Count; $i++) { + $after.histogram_log2_ns[$i] - $before.histogram_log2_ns[$i] + } + } + $out += [ordered]@{ + kind = $kind + baseline = $before + candidate = $after + delta = [ordered]@{ + count = Delta-Or-Null $before.count $after.count + total_ns = Delta-Or-Null $before.total_ns $after.total_ns + max_ns = Delta-Or-Null $before.max_ns $after.max_ns + histogram_log2_ns = $histogramDelta + } + } + } + return $out +} + +function Display-Value($Value, [string]$Suffix) { + if ($null -eq $Value) { return 'missing' } + return "$Value$Suffix" +} + +$baselineRoot = [IO.Path]::GetFullPath($Baseline) +$candidateRoot = [IO.Path]::GetFullPath($Candidate) +$beforeManifest = Read-Manifest $baselineRoot 'baseline' +$afterManifest = Read-Manifest $candidateRoot 'candidate' + +if ($beforeManifest.workload_id -ne $afterManifest.workload_id) { throw 'workload_id differs; runs are incomparable' } +if ((@($beforeManifest.run_order) -join ',') -ne (@($afterManifest.run_order) -join ',')) { throw 'run order differs; runs are incomparable' } +Require-Same-Property $beforeManifest $afterManifest 'system' 'system information' +if (($beforeManifest.environment | ConvertTo-Json -Compress -Depth 6) -ne ($afterManifest.environment | ConvertTo-Json -Compress -Depth 6)) { + throw 'runtime environment differs; runs are incomparable' +} + +$comparisons = @() +for ($i = 0; $i -lt 2; $i++) { + $beforeRun = @($beforeManifest.runs)[$i] + $afterRun = @($afterManifest.runs)[$i] + Require-Same-Property $beforeRun $afterRun 'gpu' "$($beforeRun.cache_state) GPU" + Require-Same-Property $beforeRun $afterRun 'gpu_driver' "$($beforeRun.cache_state) GPU driver" + if ([long]$beforeRun.duration_requested_seconds -ne [long]$afterRun.duration_requested_seconds) { + throw "$($beforeRun.cache_state) requested duration differs; runs are incomparable" + } + $beforeDuration = Number-Or-Null $beforeRun 'duration_actual_ms' + $afterDuration = Number-Or-Null $afterRun 'duration_actual_ms' + $beforeStalls = Read-Stalls $baselineRoot ($i + 1) $beforeRun.cache_state + $afterStalls = Read-Stalls $candidateRoot ($i + 1) $afterRun.cache_state + $stalls = @(Compare-Aggregates $beforeStalls.aggregates $afterStalls.aggregates) + + $comparison = [ordered]@{ + label = $beforeRun.cache_state + duration_ms = [ordered]@{ + baseline = $beforeDuration + candidate = $afterDuration + delta = Delta-Or-Null $beforeDuration $afterDuration + } + exit_code = [ordered]@{ + baseline = Number-Or-Null $beforeRun 'exit_code' + candidate = Number-Or-Null $afterRun 'exit_code' + } + timed_out = [ordered]@{ + baseline = Bool-Or-Null $beforeRun 'timed_out' + candidate = Bool-Or-Null $afterRun 'timed_out' + } + stalls_status = [ordered]@{ baseline = $beforeStalls.status; candidate = $afterStalls.status } + stalls = $stalls + } + $comparisons += $comparison + + Write-Host "$($comparison.label): duration $(Display-Value $beforeDuration ' ms') -> $(Display-Value $afterDuration ' ms'); delta $(Display-Value $comparison.duration_ms.delta ' ms')" + Write-Host " exit: $(Display-Value $comparison.exit_code.baseline '') -> $(Display-Value $comparison.exit_code.candidate ''); timeout: $(Display-Value $comparison.timed_out.baseline '') -> $(Display-Value $comparison.timed_out.candidate '')" + if ($stalls.Count -eq 0) { + Write-Host " stalls: missing/empty (baseline $($beforeStalls.status), candidate $($afterStalls.status))" + } else { + foreach ($stall in $stalls) { + Write-Host " stall $($stall.kind): total $(Display-Value $stall.baseline.total_ns ' ns') -> $(Display-Value $stall.candidate.total_ns ' ns'); count $(Display-Value $stall.baseline.count '') -> $(Display-Value $stall.candidate.count ''); max $(Display-Value $stall.baseline.max_ns ' ns') -> $(Display-Value $stall.candidate.max_ns ' ns')" + } + } +} + +[ordered]@{ + schema = 'xcl-perf-comparison' + version = 1 + workload_id = $beforeManifest.workload_id + run_order = @($beforeManifest.run_order) + baseline = [ordered]@{ commit = $beforeManifest.commit; path = $baselineRoot } + candidate = [ordered]@{ commit = $afterManifest.commit; path = $candidateRoot } + runs = $comparisons +} | ConvertTo-Json -Depth 12 diff --git a/scripts/perf-compare.tests.ps1 b/scripts/perf-compare.tests.ps1 new file mode 100644 index 0000000000..2a1c41c7d2 --- /dev/null +++ b/scripts/perf-compare.tests.ps1 @@ -0,0 +1,111 @@ +$ErrorActionPreference = 'Stop' +$tool = Join-Path $PSScriptRoot 'perf-compare.ps1' +$fixture = Join-Path ([IO.Path]::GetTempPath()) ('xcl-perf-compare-test-' + [guid]::NewGuid()) +$baseline = Join-Path $fixture 'baseline' +$candidate = Join-Path $fixture 'candidate' + +function Write-Fixture([string]$Root, [string]$Commit, [int]$ColdMs, $WarmMs) { + $null = New-Item -ItemType Directory -Path (Join-Path $Root 'runs\01-cold'), (Join-Path $Root 'runs\02-warm') -Force + $manifest = [ordered]@{ + schema = 'xcl-perf-run' + version = 1 + commit = $Commit + dirty = $false + build = [ordered]@{ profile = 'release' } + workload_id = 'same-workload' + run_order = @('xcl-cold', 'xcl-warm') + environment = [ordered]@{ XCL_PRESS_AT = '20:A' } + runs = @( + [ordered]@{ order = 1; cache_state = 'xcl-cold'; duration_requested_seconds = 60; duration_actual_ms = $ColdMs; exit_code = 0; timed_out = $false }, + [ordered]@{ order = 2; cache_state = 'xcl-warm'; duration_requested_seconds = 60; duration_actual_ms = $WarmMs; exit_code = $null; timed_out = $true } + ) + } + $manifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $Root 'manifest.json') -Encoding utf8 +} + +function Write-Report([string]$Path, [int]$Count, [long]$Total, [long]$Maximum, [switch]$ExtraKind) { + $aggregates = @( + [ordered]@{ kind = 'dxc_compile'; count = $Count; total_ns = $Total; max_ns = $Maximum; histogram_log2_ns = @(0, $Count) } + ) + if ($ExtraKind) { + $aggregates += [ordered]@{ kind = 'gpu_wait'; count = 1; total_ns = 9; max_ns = 9; histogram_log2_ns = @(0, 0, 0, 1) } + } + [ordered]@{ stalls = [ordered]@{ version = 1; aggregates = $aggregates; slow_events = @() } } | + ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $Path -Encoding utf8 +} + +try { + Write-Fixture $baseline 'base-commit' 1000 0 + Write-Fixture $candidate 'candidate-commit' 850 0 + Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 -ExtraKind + [ordered]@{ d3d12 = [ordered]@{} } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $baseline 'runs\02-warm\report.json') -Encoding utf8 + + $json = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json + if ($json.schema -ne 'xcl-perf-comparison' -or $json.version -ne 1) { throw 'wrong output schema' } + if ($json.runs[0].duration_ms.delta -ne -150) { throw 'cold duration delta is wrong' } + if ($json.runs[1].duration_ms.delta -ne 0) { throw 'zero durations were not compared as raw values' } + if ($json.runs[1].exit_code.candidate -ne $null -or $json.runs[1].timed_out.candidate -ne $true) { throw 'missing exit/timeout was not preserved' } + $dxc = $json.runs[0].stalls | Where-Object { $_.kind -eq 'dxc_compile' } + if ($dxc.delta.total_ns -ne -20 -or $dxc.delta.count -ne 1 -or $dxc.delta.max_ns -ne -30) { throw 'stall deltas are wrong' } + $gpu = $json.runs[0].stalls | Where-Object { $_.kind -eq 'gpu_wait' } + if ($null -ne $gpu.baseline -or $gpu.candidate.total_ns -ne 9 -or $null -ne $gpu.delta.total_ns) { throw 'one-sided stall data was not labelled missing' } + if ($json.runs[1].stalls_status.baseline -ne 'missing_stalls' -or $json.runs[1].stalls_status.candidate -ne 'missing_report') { throw 'missing report/stalls states are wrong' } + if (($json | ConvertTo-Json -Depth 12) -match 'percent|ratio|significant') { throw 'output invented a derived significance metric' } + + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.workload_id = 'other-workload' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'workload_id differs' } + if (-not $refused) { throw 'different workloads were not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.runs[1].cache_state = 'xcl-cold' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'does not match run_order' } + if (-not $refused) { throw 'mismatched run labels were not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.version = 2 + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'unsupported manifest schema/version' } + if (-not $refused) { throw 'an unsupported manifest schema was not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest | Add-Member -NotePropertyName system -NotePropertyValue ([pscustomobject]@{ cpu = 'only candidate recorded this' }) + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'system information differs' } + if (-not $refused) { throw 'system information present on only one side was not refused' } + + Write-Fixture $baseline 'base-commit' 1000 0 + Write-Fixture $candidate 'candidate-commit' 850 0 + $baselineManifest = Get-Content -LiteralPath (Join-Path $baseline 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $baselineManifest.runs[0] | Add-Member -NotePropertyName gpu -NotePropertyValue 'GPU A' + $candidateManifest.runs[0] | Add-Member -NotePropertyName gpu -NotePropertyValue 'GPU B' + $baselineManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $baseline 'manifest.json') -Encoding utf8 + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'xcl-cold GPU differs' } + if (-not $refused) { throw 'different GPUs were not refused' } + + Write-Fixture $baseline 'base-commit' 1000 0 + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.runs[1] | Add-Member -NotePropertyName gpu_driver -NotePropertyValue 'only candidate recorded this' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'xcl-warm GPU driver differs' } + if (-not $refused) { throw 'GPU driver present on only one side was not refused' } + + Write-Host 'perf-compare tests: all assertions passed' +} finally { + if (Test-Path -LiteralPath $fixture) { Remove-Item -LiteralPath $fixture -Recurse -Force } +} From 311fc61856fd45cecddde632e121f851b8c7f82c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:27:48 -0800 Subject: [PATCH 016/265] D3D12.X: order waits after deferred CPU writes Split a command list when a memory wait depends on a CPU-after-segment producer, submit the producer segment, and wait for its exact deferred-store completion before evaluating the continuation. Preserve in-segment GPU and Write64 ordering while leaving unrelated CPU writes asynchronous. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/cpu_writes.rs | 62 +++-- crates/xcl/src/hle/d3d12x/list_x.rs | 299 ++++++++++++++++++++---- crates/xcl/src/hle/d3d12x/real.rs | 4 +- 3 files changed, 299 insertions(+), 66 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 0b20bfbd6a..15ec353308 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -34,6 +34,7 @@ struct Job { fence: ID3D12Fence, value: u64, writes: Vec, + done: Option>, } // SAFETY: the fence is a free-threaded COM object; the writes are plain data @@ -79,6 +80,9 @@ fn worker() -> &'static Mutex> { } } } + if let Some(done) = job.done { + let _ = done.send(()); + } } }); if let Err(e) = spawned { @@ -156,12 +160,33 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { && m.BaseAddress as usize + m.RegionSize >= va + bytes } -/// `writes` of lists just submitted to `queue`: done when the GPU has finished them. -pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { +/// Receipt published only after the worker has applied every deferred store in a submission. +pub(super) struct Completion(mpsc::Receiver<()>); + +impl Completion { + pub(super) fn wait(self) -> bool { + self.0.recv().is_ok() + } +} + +#[cfg(test)] +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() { - return; + return None; } - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + 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) + }; let job = { let mut g = FENCES.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); @@ -170,22 +195,31 @@ pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { std::collections::hash_map::Entry::Vacant(v) => { let mut dev: Option = None; if q.GetDevice(&mut dev).is_err() { - return; + return None; } - let Some(dev) = dev else { return }; - let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return }; + let Some(dev) = dev else { return None }; + let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return None }; v.insert(QueueFence { fence, value: 0 }) } }; entry.value += 1; if q.Signal(&entry.fence, entry.value).is_err() { - return; + return None; } - Job { fence: entry.fence.clone(), value: entry.value, writes } + Job { fence: entry.fence.clone(), value: entry.value, writes, 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())); - let _ = worker().lock().unwrap().send(job); + worker().lock().unwrap().send(job).ok()?; + receipt +} + +pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { + let _ = schedule(queue, writes, false); +} + +pub(super) unsafe fn after_with_completion(queue: *mut c_void, writes: Vec) -> Option { + schedule(queue, writes, true) } #[cfg(test)] @@ -209,12 +243,8 @@ mod tests { let cell = Box::new([0u32; 2]); let va = cell.as_ptr() as usize; assert!(writable(va, 8)); - after(q.as_raw(), vec![Write::Immediate(va, vec![7, 9])]); - let t = std::time::Instant::now(); - while (*(va as *const AtomicU32)).load(Ordering::Acquire) != 7 { - assert!(t.elapsed().as_secs() < 5, "never written"); - std::thread::yield_now(); - } + let completion = after_with_completion(q.as_raw(), vec![Write::Immediate(va, vec![7, 9])]).expect("scheduled CPU write"); + assert!(completion.wait()); assert_eq!(*cell, [7, 9]); } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index a9c0b3435f..09cfdf76fd 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -773,18 +773,27 @@ pub(super) enum Deferred { /// Why a recording needs a physical command-list boundary. pub(super) enum SegmentReason { WaitAfterWrite64, + WaitAfterCpuWrite, DeferredDispatch(Deferred), } impl SegmentReason { fn extra_segments(&self) -> usize { match self { - Self::WaitAfterWrite64 => 1, + Self::WaitAfterWrite64 | Self::WaitAfterCpuWrite => 1, Self::DeferredDispatch(_) => 2, } } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum WaitPlacement { + OrderedInSegment, + RecordHere, + SplitAfterCpuWrite, + SplitAfterWrite64, +} + impl ListState { fn note_write(&mut self, producer: WriteProducer, va: u64, size: u64) { if size == 0 { @@ -824,10 +833,22 @@ impl ListState { } fn has_prior_write(&self, va: u64, size: u64) -> bool { - // Keep the existing wait policy until deferred producers gain their own split boundary. + // GPU writes are already ordered before later commands in the same physical list. self.written_ranges.overlaps(WriteProducer::InSegmentGpu, va, size) } + fn wait_placement(&self, va: u64, size: u64) -> WaitPlacement { + if self.written_ranges.overlaps(WriteProducer::CpuAfterSegment, va, size) { + WaitPlacement::SplitAfterCpuWrite + } else if self.has_prior_write(va, size) { + WaitPlacement::OrderedInSegment + } else if !self.write64_signals.is_empty() { + WaitPlacement::SplitAfterWrite64 + } else { + WaitPlacement::RecordHere + } + } + fn clear_waits(&mut self) { self.pending_waits.clear(); } @@ -965,12 +986,29 @@ impl SubmissionPlan { let has_waits = effects.iter().any(|e| !e.waits.is_empty()); Self { lists: lists.to_vec(), effects, has_waits } } + + fn cpu_producer_overlaps(&self, waits: &[PendingWait], before: usize) -> bool { + self.effects[..before].iter().any(|e| { + waits.iter().any(|w| e.producer_overlaps(WriteProducer::CpuAfterSegment, w.va, w.width as u64)) + }) + } + + fn chunk_needs_cpu_completion(&self, start: usize, end: usize, external_waits: &[PendingWait]) -> bool { + self.effects[start..end].iter().any(|producer| { + self.effects[end..] + .iter() + .flat_map(|e| &e.waits) + .chain(external_waits) + .any(|w| producer.producer_overlaps(WriteProducer::CpuAfterSegment, w.va, w.width as u64)) + }) + } } #[derive(Clone, Copy)] pub(super) struct SubmissionChunk<'a> { lists: &'a [*mut c_void], effects: &'a [SegmentEffects], + needs_cpu_completion: bool, } impl<'a> SubmissionChunk<'a> { @@ -978,8 +1016,12 @@ impl<'a> SubmissionChunk<'a> { self.lists } - pub(super) unsafe fn submit_effects(self, queue: *mut c_void) { - submit_segment_effects(queue, self.effects); + pub(super) fn needs_cpu_completion(self) -> bool { + self.needs_cpu_completion + } + + pub(super) unsafe fn submit_effects(self, queue: *mut c_void) -> Option { + submit_segment_effects(queue, self.effects, self.needs_cpu_completion) } } @@ -2330,7 +2372,7 @@ pub(super) fn submission_plan(lists: &[*mut c_void]) -> SubmissionPlan { } /// Publish the effects of an already-submitted chunk in the same order as the legacy consumers. -unsafe fn submit_segment_effects(queue: *mut c_void, effects: &[SegmentEffects]) { +unsafe fn submit_segment_effects(queue: *mut c_void, effects: &[SegmentEffects], needs_cpu_completion: bool) -> Option { let write64_signals: Vec<(u64, u64)> = effects.iter().flat_map(|e| e.write64_signals.iter().copied()).collect(); signal_write64_pairs(queue, &write64_signals); @@ -2342,30 +2384,59 @@ unsafe fn submit_segment_effects(queue: *mut c_void, effects: &[SegmentEffects]) } let cpu_writes: Vec = effects.iter().flat_map(|e| e.cpu_writes.iter().cloned()).collect(); - super::cpu_writes::after(queue, cpu_writes); + if needs_cpu_completion { + super::cpu_writes::after_with_completion(queue, cpu_writes) + } else { + super::cpu_writes::after(queue, cpu_writes); + None + } } -/// Execute an immutable submission plan, splitting before an unsatisfied memory wait. -pub(super) unsafe fn execute_submission_plan_on(queue: *mut c_void, plan: &SubmissionPlan, mut submit: impl FnMut(SubmissionChunk<'_>)) { - let chunk = |start, end| SubmissionChunk { lists: &plan.lists[start..end], effects: &plan.effects[start..end] }; +/// Execute a plan and retain completion receipts for its deferred CPU writes. +pub(super) unsafe fn execute_submission_plan_with_completions( + queue: *mut c_void, + plan: &SubmissionPlan, + external_waits: &[PendingWait], + mut submit: impl FnMut(SubmissionChunk<'_>) -> Option, +) -> Vec { + let chunk = |start, end| SubmissionChunk { + lists: &plan.lists[start..end], + effects: &plan.effects[start..end], + needs_cpu_completion: plan.chunk_needs_cpu_completion(start, end, external_waits), + }; if !plan.has_waits { - submit(chunk(0, plan.lists.len())); - return; + return submit(chunk(0, plan.lists.len())).into_iter().collect(); } + let mut completions = Vec::new(); let mut start = 0usize; for (i, effects) in plan.effects.iter().enumerate() { - if effects.waits.is_empty() || effects.waits.iter().all(|w| w.is_satisfied()) { + let after_cpu_write = plan.cpu_producer_overlaps(&effects.waits, i); + if effects.waits.is_empty() || (!after_cpu_write && effects.waits.iter().all(|w| w.is_satisfied())) { continue; } if i > start { - submit(chunk(start, i)); + completions.extend(submit(chunk(start, i))); + } + if after_cpu_write { + for completion in completions.drain(..) { + let _ = completion.wait(); + } } wait_all_on(queue, &effects.waits, &effects.write64_signals); start = i; } if start < plan.lists.len() { - submit(chunk(start, plan.lists.len())); + completions.extend(submit(chunk(start, plan.lists.len()))); } + completions +} + +/// Execute an immutable submission plan, splitting before an unsatisfied memory wait. +pub(super) unsafe fn execute_submission_plan_on(queue: *mut c_void, plan: &SubmissionPlan, mut submit: impl FnMut(SubmissionChunk<'_>)) { + let _ = execute_submission_plan_with_completions(queue, plan, &[], |chunk| { + submit(chunk); + None + }); } /// Submit `lists` through `submit`, splitting the batch before any list whose `Wait32/64BitValueX` @@ -2878,29 +2949,42 @@ pub(super) unsafe fn reset_stand_in(wrapper: *mut c_void, primary: *mut c_void, Some(spare as usize) } -/// Deferred mid-list split for `Wait32/64BitValueX` recorded after a `Write64BitValue*` in the -/// same command list: closes `list` (preserving its earlier `Write64` signals on segment N) and -/// opens/reuses a sibling PC command list on the same `ID3D12CommandAllocator` as segment N+1, -/// carrying all bound D3D12 + XCL root-argument state across the split. +/// Deferred mid-list split for `Wait32/64BitValueX` that depends on a producer in the current +/// recording. Closes `list` and opens/reuses a sibling PC list on the same allocator, carrying all +/// bound D3D12 + XCL root-argument state across the split. /// /// At `ExecuteCommandLists`, `title_list::push_segments` expands the wrapper into `[seg_0, seg_1, ...]` -/// and `execute_with_waits_on` submits `seg_0` + emits `queue.Signal` for its `Write64`s BEFORE -/// emitting `queue.Wait` for `seg_1`'s `Wait64`, preserving exact Xbox chronological order with -/// zero artificial GPU cycles. -unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { - static ENABLED: OnceLock = OnceLock::new(); - if !*ENABLED.get_or_init(|| std::env::var("XCL_SPLIT_MIDLIST_WAIT").map_or(true, |v| v.trim() != "0")) { - return None; - } - let next_pc = split_recording(list, SegmentReason::WaitAfterWrite64)?; +/// Submission runs segment N's Write64 signal or deferred CPU store before segment N+1's wait. +unsafe fn try_split_for_wait(list: *mut c_void, placement: WaitPlacement) -> Option<*mut c_void> { + let (reason, why) = match placement { + WaitPlacement::SplitAfterCpuWrite => (SegmentReason::WaitAfterCpuWrite, "CPU-after-segment write"), + WaitPlacement::SplitAfterWrite64 => { + static ENABLED: OnceLock = OnceLock::new(); + if !*ENABLED.get_or_init(|| std::env::var("XCL_SPLIT_MIDLIST_WAIT").map_or(true, |v| v.trim() != "0")) { + return None; + } + (SegmentReason::WaitAfterWrite64, "Write64") + } + _ => return None, + }; + let next_pc = split_recording(list, reason)?; static SPLITS: AtomicU64 = AtomicU64::new(0); let n = SPLITS.fetch_add(1, Ordering::Relaxed) + 1; if n <= 4 || (n.is_power_of_two() && n <= 256) { - crate::xlog_info!("D3D12.X: split command list (type {}) around mid-list Wait after Write64 (#{n})", list_type(next_pc).0); + crate::xlog_info!("D3D12.X: split command list (type {}) around mid-list Wait after {why} (#{n})", list_type(next_pc).0); } Some(next_pc) } +fn wait_target_after_split(list: *mut c_void, placement: WaitPlacement, continuation: Option<*mut c_void>) -> Option<*mut c_void> { + match (placement, continuation) { + (_, Some(next)) => Some(next), + (WaitPlacement::SplitAfterCpuWrite, None) => None, + (WaitPlacement::SplitAfterWrite64, None) => Some(list), + _ => Some(list), + } +} + /// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { if split_recording(list, SegmentReason::DeferredDispatch(what)).is_none() { @@ -3001,7 +3085,7 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - } Some((what, deferred_segment(wrapper, list, ty)?)) } - SegmentReason::WaitAfterWrite64 => None, + SegmentReason::WaitAfterWrite64 | SegmentReason::WaitAfterCpuWrite => None, }; let carry = { let mut g = LISTS.lock().unwrap(); @@ -3200,8 +3284,9 @@ unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_CO /// If an earlier write in the same open list already targeted an overlapping UMA range, the /// `COMMON -> COPY_DEST -> COMMON` barrier around that write already orders subsequent work /// on the GPU, so we do not stall before submission (which would deadlock waiting on our own -/// unsubmitted list). If this list already recorded a `Write64BitValue*` to a different cell, -/// we split into a new deferred PC segment so earlier `Write64` signals run BEFORE this wait. +/// unsubmitted list). An overlapping CPU-after-segment write must instead close the producer +/// segment and complete its deferred store before this wait is evaluated. A prior `Write64` to +/// another cell keeps its existing split so its signal runs before the wait. unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, value: u64, mask: u64, what: &str) { static N: AtomicU64 = AtomicU64::new(0); let n = width as u64; @@ -3221,19 +3306,28 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va if comparison == D3D12_COMPARISON_FUNC_NEVER.0 as u32 { return warn(&N, what, format_args!("NEVER comparison at {va:#x} (skipped to avoid hang)")); } - let need_split = { + let placement = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); - if s.has_prior_write(va, n) { - return; - } - if s.write64_signals.is_empty() { - s.push_wait(PendingWait { va, width, comparison, value, mask, after_write64: false }); - return; + let placement = s.wait_placement(va, n); + match placement { + WaitPlacement::OrderedInSegment => return, + WaitPlacement::RecordHere => { + s.push_wait(PendingWait { va, width, comparison, value, mask, after_write64: false }); + return; + } + WaitPlacement::SplitAfterCpuWrite | WaitPlacement::SplitAfterWrite64 => placement, } - true }; - let target = if need_split { try_split_for_wait(list).unwrap_or(list) } else { list }; + let continuation = try_split_for_wait(list, placement); + let Some(target) = wait_target_after_split(list, placement, continuation) else { + static SPLIT_FAILED: AtomicU64 = AtomicU64::new(0); + return warn( + &SPLIT_FAILED, + what, + format_args!("could not create a segment boundary after the deferred CPU write; the dependent wait was not recorded"), + ); + }; let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(target as usize).or_default(); let after_write64 = !s.write64_signals.is_empty(); @@ -3541,18 +3635,21 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); - // If this list was previously split mid-recording around a `Wait64`, flush all earlier closed + // If this list was previously split mid-recording around a memory wait, flush all earlier closed // segments in exact order before submitting `this`, then resume recording on `primary`. let kickoff_split = super::title_list::reclaim_for_kickoff(this); + let mut prior_cpu_completions = Vec::new(); + let mut wait_after_cpu_write = false; if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { - execute_with_waits_on(q_raw, prior, |chunk| { - exec(q_raw, chunk.len() as u32, chunk.as_ptr()); - copy_scratch_submitted(q_raw, chunk); - super::alloc_pool::executed(q_raw, chunk); - signal_write64_fences(q_raw, chunk); - readback_sparse_writes(q_raw, chunk); - cpu_writes_after(q_raw, chunk); + let plan = submission_plan(prior); + wait_after_cpu_write = plan.cpu_producer_overlaps(&waits, plan.effects.len()); + prior_cpu_completions = execute_submission_plan_with_completions(q_raw, &plan, &waits, |chunk| { + let lists = chunk.lists(); + exec(q_raw, lists.len() as u32, lists.as_ptr()); + copy_scratch_submitted(q_raw, lists); + super::alloc_pool::executed(q_raw, lists); + chunk.submit_effects(q_raw) }); super::title_textures::submitted(prior); for &p in prior { @@ -3562,6 +3659,11 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } if !waits.is_empty() { + if wait_after_cpu_write { + for completion in prior_cpu_completions.drain(..) { + let _ = completion.wait(); + } + } wait_all_on(q_raw, &waits, &write64_signals); } @@ -5179,6 +5281,38 @@ mod tests { assert!(!s.has_prior_write(0x1010, 8), "deferred CPU writes do not change wait policy in this wave"); } + #[test] + fn wait_placement_distinguishes_cpu_gpu_and_write64_producers() { + let mut s = ListState::default(); + assert_eq!(s.wait_placement(0x1000, 8), WaitPlacement::RecordHere); + + s.note_write(WriteProducer::CpuAfterSegment, 0x2000, 8); + assert_eq!(s.wait_placement(0x1000, 8), WaitPlacement::RecordHere, "an unrelated CPU write does not split"); + assert_eq!(s.wait_placement(0x2000, 8), WaitPlacement::SplitAfterCpuWrite); + + s.note_write(WriteProducer::InSegmentGpu, 0x3000, 8); + assert_eq!(s.wait_placement(0x3000, 8), WaitPlacement::OrderedInSegment); + s.note_write(WriteProducer::CpuAfterSegment, 0x3004, 4); + assert_eq!(s.wait_placement(0x3000, 8), WaitPlacement::SplitAfterCpuWrite, "CPU completion wins for mixed overlapping producers"); + + s.write64_signals.push((0x4000, 1)); + assert_eq!(s.wait_placement(0x5000, 8), WaitPlacement::SplitAfterWrite64); + assert_eq!(s.wait_placement(0x3000, 4), WaitPlacement::OrderedInSegment, "GPU overlap keeps the existing Write64 behavior"); + } + + #[test] + fn failed_cpu_wait_split_never_reuses_the_producer_segment() { + let producer = 0x7ffe_1801usize as *mut c_void; + let continuation = 0x7ffe_1802usize as *mut c_void; + assert_eq!(wait_target_after_split(producer, WaitPlacement::SplitAfterCpuWrite, Some(continuation)), Some(continuation)); + assert_eq!(wait_target_after_split(producer, WaitPlacement::SplitAfterCpuWrite, None), None); + assert_eq!( + wait_target_after_split(producer, WaitPlacement::SplitAfterWrite64, None), + Some(producer), + "keep the existing Write64 fallback" + ); + } + #[test] fn recorded_writes_merge_ascending_ranges() { let mut writes = RecordedWrites::default(); @@ -5354,9 +5488,78 @@ mod tests { assert_eq!(submitted, 1); } + #[test] + fn cpu_producer_completion_precedes_the_continuation_wait() { + let producer = 0x7ffe_2801usize as *mut c_void; + let continuation = 0x7ffe_2802usize 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); + m.insert( + continuation as usize, + ListState { + pending_waits: vec![PendingWait { + va, + width: 8, + comparison: D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, + value: 1, + mask: u64::MAX, + after_write64: false, + }], + ..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)); + } + assert!(plan.effects[0].producer_overlaps(WriteProducer::CpuAfterSegment, va, 8)); + assert!(!plan.effects[1].producer_overlaps(WriteProducer::CpuAfterSegment, va, 8)); + assert!(plan.chunk_needs_cpu_completion(0, 1, &[])); + assert!(!plan.chunk_needs_cpu_completion(1, 2, &[])); + let unrelated = PendingWait { va: va + 8, width: 8, comparison: 7, value: 1, mask: u64::MAX, after_write64: false }; + assert!(!SubmissionPlan { lists: vec![producer], effects: vec![plan.effects[0].clone()], has_waits: false }.chunk_needs_cpu_completion(0, 1, &[unrelated])); + + let completed = Arc::new(AtomicBool::new(false)); + let mut chunks = Vec::new(); + unsafe { + let leftovers = execute_submission_plan_with_completions(std::ptr::null_mut(), &plan, &[], |chunk| { + let lists = chunk.lists().to_vec(); + chunks.push(lists.clone()); + if lists == vec![producer] { + assert!(chunk.needs_cpu_completion()); + let (receipt, done) = super::super::cpu_writes::completion_pair_for_test(); + let completed = completed.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(20)); + completed.store(true, Ordering::Release); + let _ = done.send(()); + }); + Some(receipt) + } else { + assert!(!chunk.needs_cpu_completion()); + assert!(completed.load(Ordering::Acquire), "the CPU producer must complete before the wait segment is submitted"); + None + } + }); + assert!(leftovers.is_empty()); + } + assert_eq!(chunks, vec![vec![producer], vec![continuation]]); + } + #[test] fn segment_reasons_keep_the_existing_segment_costs() { assert_eq!(SegmentReason::WaitAfterWrite64.extra_segments(), 1); + assert_eq!(SegmentReason::WaitAfterCpuWrite.extra_segments(), 1); assert_eq!(SegmentReason::DeferredDispatch(Deferred::Dispatch(1, 2, 3)).extra_segments(), 2); } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9cdcabfe22..2a97c3bb03 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7278,13 +7278,13 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis } super::list_x::note_queue_for_lists(this as usize, &mapped); let plan = super::list_x::submission_plan(&mapped); - super::list_x::execute_submission_plan_on(this, &plan, |chunk| { + let _ = super::list_x::execute_submission_plan_with_completions(this, &plan, &[], |chunk| { let lists = chunk.lists(); let _ = super::alloc_pool::note_resubmits(this, lists); f(this, lists.len() as u32, lists.as_ptr()); super::list_x::copy_scratch_submitted(this, lists); super::alloc_pool::executed(this, lists); - chunk.submit_effects(this); + chunk.submit_effects(this) }); // the next uploads into textures kept in step start from the states these lists leave super::title_textures::submitted(&mapped); From 67629ad43abf36847cf15e09f01b7f6c648eeb1a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:28:33 -0800 Subject: [PATCH 017/265] D3D12.X: share shader storage with compute build keys Keep descriptor bytecode pointers stable with Arc-backed shader allocations and let canonical compute keys share those exact bytes. This avoids retaining a second full shader copy for every lazy or in-flight build. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 32 ++++++++++--------- .../src/hle/d3d12x/real/compute_build_key.rs | 31 ++++++++++++------ 2 files changed, 38 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index c13d0b8d46..3282090d92 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -21,7 +21,7 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::ffi::c_void; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock}; use serde::Serialize; use windows::core::{Interface, PCSTR}; @@ -5370,34 +5370,36 @@ pub(in crate::hle::d3d12x) mod compute_build_key; /// The root signature pointer is kept as is (the translated paths replace it). #[allow(dead_code)] // the vectors only keep the copies alive enum OwnedDesc { - Compute(Box, Vec>), - Graphics(Box, Vec>, Vec, Vec), - Stream(Box<[usize; 2]>, Vec, Vec>), + Compute(Box, Vec>), + Graphics(Box, Vec>, Vec, Vec), + Stream(Box<[usize; 2]>, Vec, Vec>), } unsafe impl Send for OwnedDesc {} /// A hash of a pipeline's shaders in their order (never 0): what `pso_async` knows a used /// pipeline by in the next run. -pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { +pub(crate) fn shaders_key>(blobs: &[T]) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; for b in blobs { - h = (h ^ crate::gpu::shader::fnv64(b)).wrapping_mul(0x0000_0100_0000_01b3); + h = (h ^ crate::gpu::shader::fnv64(b.as_ref())).wrapping_mul(0x0000_0100_0000_01b3); } h | 1 } #[cfg(test)] mod shaders_key_tests { + use std::sync::Arc; + #[test] fn a_key_follows_the_shaders_and_their_order_and_is_never_zero() { - let (a, b) = (vec![1u8, 2, 3], vec![4u8, 5]); + let (a, b): (Arc<[u8]>, Arc<[u8]>) = ([1u8, 2, 3].into(), [4u8, 5].into()); let key = super::shaders_key(&[a.clone(), b.clone()]); assert_eq!(key, super::shaders_key(&[a.clone(), b.clone()])); assert_ne!(key, super::shaders_key(&[b.clone(), a.clone()])); assert_ne!(key, super::shaders_key(&[a.clone()])); - assert_ne!(key, super::shaders_key(&[a, vec![4u8, 6]])); - assert_ne!(super::shaders_key(&[]), 0); + assert_ne!(key, super::shaders_key(&[a, [4u8, 6].into()])); + assert_ne!(super::shaders_key(&[] as &[Arc<[u8]>]), 0); } } @@ -5420,9 +5422,9 @@ impl OwnedDesc { } /// Copy a shader blob into `blobs` and point `b` at the copy. -unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec>) { +unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec>) { if let Some(bytes) = shader_bytes(b) { - blobs.push(bytes.to_vec()); + blobs.push(bytes.into()); let v = blobs.last().unwrap(); *b = bytecode(v); } else { @@ -5475,7 +5477,7 @@ unsafe fn own_stream(desc: *const c_void) -> Option { return None; } let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec(); - let mut blobs: Vec> = Vec::new(); + let mut blobs: Vec> = Vec::new(); let mut off = 0usize; while off + 8 <= size { let ty = u32::from_le_bytes(buf[off..off + 4].try_into().ok()?); @@ -5492,7 +5494,7 @@ unsafe fn own_stream(desc: *const c_void) -> Option { if p == 0 || n == 0 { buf[at..at + 16].fill(0); } else if crate::gpu::shader::readable(p, n) { - blobs.push(std::slice::from_raw_parts(p as *const u8, n).to_vec()); + blobs.push(std::slice::from_raw_parts(p as *const u8, n).into()); buf[at..at + 8].copy_from_slice(&(blobs.last().unwrap().as_ptr() as u64).to_le_bytes()); } else { return None; @@ -5635,7 +5637,7 @@ unsafe fn go_background( let key = owned.shaders_key(); let build_key = match &owned { OwnedDesc::Compute(desc, shaders) => shaders.first().map(|shader| { - compute_build_key::ComputeBuildKey::capture(this as usize, desc, shader, wave32_only(this)) + compute_build_key::ComputeBuildKey::capture(this as usize, desc, shader.clone(), wave32_only(this)) }), _ => None, }; @@ -8361,7 +8363,7 @@ mod mesh_stream_tests { let owned = own_stream(d_valid.as_ptr() as *const c_void).expect("valid stream"); let OwnedDesc::Stream(_, buf, blobs) = owned else { panic!("expected Stream") }; assert_eq!(blobs.len(), 1); - assert_eq!(blobs[0], shader); + assert_eq!(&*blobs[0], shader.as_slice()); let rebased = u64::from_le_bytes(buf[8..16].try_into().unwrap()) as usize; assert_eq!(rebased, blobs[0].as_ptr() as usize); assert_ne!(rebased, shader.as_ptr() as usize); diff --git a/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs b/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs index 1f0d4e4dcd..0d30eb181d 100644 --- a/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs +++ b/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use windows::Win32::Graphics::Direct3D12::D3D12_COMPUTE_PIPELINE_STATE_DESC; use crate::gpu::recomp::pso::ComputePolicyKey; @@ -17,7 +19,7 @@ pub(in crate::hle::d3d12x) struct ComputeBuildKey { device: usize, node_mask: u32, flags: i32, - shader: Box<[u8]>, + shader: Arc<[u8]>, windows: u32, split_wave64: bool, policy: ComputePolicyKey, @@ -29,7 +31,7 @@ impl ComputeBuildKey { pub(in crate::hle::d3d12x) fn capture( device: usize, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, - shader: &[u8], + shader: Arc<[u8]>, split_wave64: bool, ) -> Self { Self::from_descriptor( @@ -45,7 +47,7 @@ impl ComputeBuildKey { fn from_descriptor( device: usize, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, - shader: &[u8], + shader: Arc<[u8]>, windows: u32, split_wave64: bool, policy: ComputePolicyKey, @@ -57,7 +59,7 @@ impl ComputeBuildKey { device: usize, node_mask: u32, flags: i32, - shader: &[u8], + shader: Arc<[u8]>, windows: u32, split_wave64: bool, policy: ComputePolicyKey, @@ -67,7 +69,7 @@ impl ComputeBuildKey { device, node_mask, flags, - shader: shader.into(), + shader, windows, split_wave64, policy, @@ -97,7 +99,7 @@ mod tests { } fn key() -> ComputeBuildKey { - ComputeBuildKey::from_parts(1, 2, 3, &[4, 5], 6, false, policy()) + ComputeBuildKey::from_parts(1, 2, 3, [4, 5].into(), 6, false, policy()) } #[test] @@ -113,7 +115,7 @@ mod tests { different!(device, 9); different!(node_mask, 9); different!(flags, 9); - different!(shader, vec![4, 6].into_boxed_slice()); + different!(shader, [4, 6].into()); different!(windows, 9); different!(split_wave64, true); different!(abi_schema, 9); @@ -139,7 +141,7 @@ mod tests { #[test] fn shader_identity_compares_all_bytes_not_only_a_digest() { let mut other = key(); - other.shader = vec![4, 5, 0].into_boxed_slice(); + other.shader = [4, 5, 0].into(); assert_ne!(key(), other); assert_eq!(key(), key()); } @@ -160,8 +162,17 @@ mod tests { std::ptr::write_bytes((&mut b as *mut _ as *mut u8).add(padding), 0xa5, padding_end - padding); } assert_eq!( - ComputeBuildKey::from_descriptor(1, &a, &[2, 3], 4, false, policy()), - ComputeBuildKey::from_descriptor(1, &b, &[2, 3], 4, false, policy()), + ComputeBuildKey::from_descriptor(1, &a, [2, 3].into(), 4, false, policy()), + ComputeBuildKey::from_descriptor(1, &b, [2, 3].into(), 4, false, policy()), ); } + + #[test] + fn build_key_shares_the_owned_shader_allocation() { + let shader: Arc<[u8]> = [7, 8, 9].into(); + let pointer = shader.as_ptr(); + let key = ComputeBuildKey::from_parts(1, 0, 0, shader.clone(), 1, false, policy()); + assert_eq!(key.shader.as_ptr(), pointer); + assert_eq!(Arc::strong_count(&shader), 2); + } } From b946815d0a6825aa8c292b2fd26566fc46ecc369 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:28:38 -0800 Subject: [PATCH 018/265] D3D12.X: coalesce identical compute builds Share one in-flight translated compute build across independent title-visible stand-ins with equal canonical identities. Preserve per-stand-in metadata, priority promotion, lazy scheduling, failure wakeups, and a single COM owner released only after the last pending owner. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 191 ++++++++++++++++++++++--- 1 file changed, 174 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 44294e9d35..3c978537b8 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -9,7 +9,7 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock, Weak}; use super::build_queue::{BuildQueue, JobHandle, Priority}; @@ -28,21 +28,22 @@ struct Pending { spared: std::sync::atomic::AtomicBool, } -/// A pipeline build independent of the title-visible stand-in that requested it. -/// Each `Pending` has a unique build for now; separating the ownership does not deduplicate work. +/// A pipeline build independent of the title-visible stand-ins that requested it. struct Build { - /// Canonical preparation identity; retained for later coalescing, not consulted yet. - _compute_key: Option, + compute_key: Option>, /// the build, until a worker – or a bind that cannot wait for the queue – takes it job: Mutex>, /// the build went to the workers (a lazy one goes on its first `resolve`) sent: std::sync::atomic::AtomicBool, - /// the real pipeline state (raw pointer), 0 while building or when building failed + /// the real pipeline state (one owned raw pointer shared by all `Pending`s), 0 until built + /// or when building failed real: AtomicUsize, done: Mutex, cv: Condvar, /// every stand-in interested in this build was released before it finished orphan: std::sync::atomic::AtomicBool, + /// Title-visible `Pending`s sharing this build. Changed while holding `done`. + owners: AtomicUsize, demand: Mutex, queued: Mutex>, } @@ -132,15 +133,16 @@ impl Build { Self::new_keyed(job, sent, None) } - fn new_keyed(job: Job, sent: bool, compute_key: Option) -> Self { + fn new_keyed(job: Job, sent: bool, compute_key: Option>) -> Self { Self { - _compute_key: compute_key, + compute_key, job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(sent), real: AtomicUsize::new(0), done: Mutex::new(false), cv: Condvar::new(), orphan: Default::default(), + owners: AtomicUsize::new(1), demand: Default::default(), queued: Mutex::new(None), } @@ -189,8 +191,21 @@ impl Pending { /// stand-in handed to the title → its real pipeline static PENDING: Mutex>>> = Mutex::new(None); +/// Equal compute requests share only while their build is in flight. Weak values neither retain +/// completed builds nor turn this into another PSO cache. +static IN_FLIGHT: Mutex, Weak>>> = Mutex::new(None); + +fn forget_in_flight(build: &Arc) { + let Some(key) = &build.compute_key else { return }; + let mut registry = IN_FLIGHT.lock().unwrap(); + let Some(builds) = registry.as_mut() else { return }; + if builds.get(key.as_ref()).is_some_and(|weak| Weak::ptr_eq(weak, &Arc::downgrade(build))) { + builds.remove(key.as_ref()); + } +} + /// The build is done (`real`: its pipeline, 0 = failed). -fn complete(build: &Build, real: usize) { +fn complete(build: &Arc, real: usize) { if real == 0 { FAILED.fetch_add(1, Ordering::Relaxed); } else { @@ -210,6 +225,7 @@ fn complete(build: &Build, real: usize) { if orphan { release(real); } + forget_in_flight(build); } static BUILT: AtomicUsize = AtomicUsize::new(0); static FAILED: AtomicUsize = AtomicUsize::new(0); @@ -340,7 +356,7 @@ pub fn enabled() -> bool { pub type Job = Box usize + Send>; /// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. -fn drop_unstarted_job(build: &Build) { +fn drop_unstarted_job(build: &Arc) { let job = build.job.lock().unwrap().take(); if let Some(job) = job { build.cancel_queued(); @@ -350,6 +366,7 @@ fn drop_unstarted_job(build: &Build) { build.cv.notify_all(); } drop(job); + forget_in_flight(build); } } @@ -524,7 +541,32 @@ pub(super) fn submit_lazy_keyed( fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, compute_key: Option) { debug_assert!(compute || compute_key.is_none()); - let build = Arc::new(Build::new_keyed(job, false, compute_key)); + let build = if let Some(compute_key) = compute_key { + let mut registry = IN_FLIGHT.lock().unwrap(); + let builds = registry.get_or_insert_with(HashMap::new); + builds.retain(|_, build| build.strong_count() != 0); + if let Some(build) = builds.get(&compute_key).and_then(Weak::upgrade) { + let done = build.done.lock().unwrap(); + if !*done && !build.orphan.load(Ordering::Acquire) { + build.owners.fetch_add(1, Ordering::Relaxed); + drop(done); + build + } else { + builds.remove(&compute_key); + let compute_key = Arc::new(compute_key); + let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()))); + builds.insert(compute_key, Arc::downgrade(&build)); + build + } + } else { + let compute_key = Arc::new(compute_key); + let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()))); + builds.insert(compute_key, Arc::downgrade(&build)); + build + } + } else { + Arc::new(Build::new(job, false)) + }; let p = Arc::new(Pending { build: build.clone(), driver: AtomicUsize::new(0), @@ -636,6 +678,112 @@ fn preload_enabled() -> bool { mod used_tests { use super::*; + fn compute_key(tag: u8) -> super::super::real::compute_build_key::ComputeBuildKey { + super::super::real::compute_build_key::ComputeBuildKey::capture( + 1, + &windows::Win32::Graphics::Direct3D12::D3D12_COMPUTE_PIPELINE_STATE_DESC::default(), + [tag].into(), + false, + ) + } + + fn submit_compute(standin: usize, tag: u8, job: Job) { + submit_lazy_keyed(standin, true, job, 0, Some(compute_key(tag))); + } + + #[test] + fn concurrent_equal_compute_submissions_run_one_job() { + let standins = [0x7E57_C101usize, 0x7E57_C102]; + let gate = Arc::new(std::sync::Barrier::new(3)); + let runs = Arc::new(AtomicUsize::new(0)); + let threads: Vec<_> = standins.iter().map(|&standin| { + let (gate, runs) = (gate.clone(), runs.clone()); + std::thread::spawn(move || { + gate.wait(); + submit_compute(standin, 0xC1, Box::new(move || { + runs.fetch_add(1, Ordering::Relaxed); + 0xC101 + })); + }) + }).collect(); + gate.wait(); + for thread in threads { thread.join().unwrap() } + + let (a, b) = (entry(standins[0]).unwrap(), entry(standins[1]).unwrap()); + assert!(Arc::ptr_eq(&a.build, &b.build)); + assert_eq!(resolve_wait_for(standins[0], None), 0xC101); + assert_eq!(resolve_wait_for(standins[1], None), 0xC101); + assert_eq!(runs.load(Ordering::Relaxed), 1); + assert_eq!(released(standins[0]), 0, "the shared COM owner stays with the other stand-in"); + assert_eq!(released(standins[1]), 0xC101, "the last stand-in releases the one owned reference"); + } + + #[test] + fn unequal_compute_keys_keep_separate_builds() { + let standins = [0x7E57_C201usize, 0x7E57_C202]; + submit_compute(standins[0], 0xC2, Box::new(|| 0)); + submit_compute(standins[1], 0xC3, Box::new(|| 0)); + assert!(!Arc::ptr_eq(&entry(standins[0]).unwrap().build, &entry(standins[1]).unwrap().build)); + assert_eq!((released(standins[0]), released(standins[1])), (0, 0)); + } + + #[test] + fn failed_coalesced_build_wakes_every_waiter() { + let standins = [0x7E57_C301usize, 0x7E57_C302]; + let runs = Arc::new(AtomicUsize::new(0)); + for &standin in &standins { + let runs = runs.clone(); + submit_compute(standin, 0xC4, Box::new(move || { + runs.fetch_add(1, Ordering::Relaxed); + 0 + })); + } + let threads: Vec<_> = standins.iter().map(|&standin| { + std::thread::spawn(move || resolve_wait_for(standin, None)) + }).collect(); + for (thread, standin) in threads.into_iter().zip(standins) { + assert_eq!(thread.join().unwrap(), standin); + } + assert_eq!(runs.load(Ordering::Relaxed), 1); + assert_eq!((released(standins[0]), released(standins[1])), (0, 0)); + } + + #[test] + fn coalesced_preload_is_promoted_once_for_both_pending_owners() { + let standins = [0x7E57_C401usize, 0x7E57_C402]; + submit_compute(standins[0], 0xC5, Box::new(|| 0xC401)); + submit_compute(standins[1], 0xC5, Box::new(|| panic!("duplicate job ran"))); + let build = entry(standins[0]).unwrap().build.clone(); + assert!(Arc::ptr_eq(&build, &entry(standins[1]).unwrap().build)); + let q = BuildQueue::new(); + enqueue_on(&q, &build, Priority::Preload, true); + entry(standins[1]).unwrap().build.promote(Priority::Foreground); + assert!(!q.try_run_one_between(Priority::Speculative, Priority::Preload)); + assert!(q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert_eq!(build.real.load(Ordering::Acquire), 0xC401); + assert_eq!(released(standins[0]), 0); + assert_eq!(released(standins[1]), 0xC401); + } + + #[test] + fn releasing_one_waiter_does_not_orphan_shared_build() { + let standins = [0x7E57_C501usize, 0x7E57_C502]; + let runs = Arc::new(AtomicUsize::new(0)); + let count = runs.clone(); + submit_compute(standins[0], 0xC6, Box::new(move || { + count.fetch_add(1, Ordering::Relaxed); + 0xC501 + })); + submit_compute(standins[1], 0xC6, Box::new(|| panic!("duplicate job ran"))); + let build = entry(standins[1]).unwrap().build.clone(); + assert_eq!(released(standins[0]), 0); + assert!(!build.orphan.load(Ordering::Acquire)); + assert!(build.job.lock().unwrap().is_some()); + assert_eq!(resolve_wait_for(standins[1], None), 0xC501); + assert_eq!(runs.load(Ordering::Relaxed), 1); + assert_eq!(released(standins[1]), 0xC501); + } + #[test] fn build_completion_reaches_all_owners() { let build = Arc::new(Build::new(Box::new(|| 0), false)); @@ -1319,19 +1467,28 @@ pub fn resolve_for_bind(pso: usize) -> usize { } /// The title released stand-in `pso` for good: forget it (its address may come back for -/// another object) and return its real pipeline to release (0: none, or still being built – -/// the worker's result is then released when it arrives). +/// another object) and return its real pipeline to release when this is its last owner +/// (0: another `Pending` owns the build, none, or still being built – the worker's result is +/// then released when its last owner is gone). pub fn released(pso: usize) -> usize { let Some(p) = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)) else { return 0 }; + let mut orphaned = false; { let done = p.build.done.lock().unwrap(); + let owners = p.build.owners.fetch_sub(1, Ordering::Relaxed) - 1; if *done { - return p.build.real.swap(0, Ordering::AcqRel); + return if owners == 0 { p.build.real.swap(0, Ordering::AcqRel) } else { 0 }; } - // the worker stores its result into a Build nobody will read: mark it orphaned - p.build.orphan.store(true, Ordering::Release); + if owners == 0 { + // the worker stores its result into a Build nobody will read: mark it orphaned + p.build.orphan.store(true, Ordering::Release); + orphaned = true; + } + } + if orphaned { + forget_in_flight(&p.build); + drop_unstarted_job(&p.build); } - drop_unstarted_job(&p.build); 0 } From 9722ba8303191a867565d01cfe8c9b13b11d3213 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:31:29 -0800 Subject: [PATCH 019/265] D3D12.X: report compute build coalescing Track keyed submissions, coalescing hits, unique builds, and current and peak in-flight identities with relaxed atomics. Serialize a versioned preparation summary without taking pipeline registries during report generation. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 96 +++++++++++++++++++++++++- crates/xcl/src/report.rs | 39 +++++++++++ 2 files changed, 133 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 3c978537b8..092320fe48 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -8,7 +8,7 @@ //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock, Weak}; use super::build_queue::{BuildQueue, JobHandle, Priority}; @@ -195,12 +195,75 @@ static PENDING: Mutex>>> = Mutex::new(None); /// completed builds nor turn this into another PSO cache. static IN_FLIGHT: Mutex, Weak>>> = Mutex::new(None); +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub struct ComputeCoalescingStats { + pub keyed_submissions: u64, + pub coalescing_hits: u64, + pub unique_keyed_builds: u64, + pub current_in_flight: usize, + pub peak_in_flight: usize, +} + +struct CoalescingCounters { + coalescing_hits: AtomicU64, + unique_keyed_builds: AtomicU64, + current_in_flight: AtomicUsize, + peak_in_flight: AtomicUsize, +} + +impl CoalescingCounters { + const fn new() -> Self { + Self { + coalescing_hits: AtomicU64::new(0), + unique_keyed_builds: AtomicU64::new(0), + current_in_flight: AtomicUsize::new(0), + peak_in_flight: AtomicUsize::new(0), + } + } + + fn hit(&self) { + self.coalescing_hits.fetch_add(1, Ordering::Relaxed); + } + + fn unique(&self) { + self.unique_keyed_builds.fetch_add(1, Ordering::Relaxed); + let current = self.current_in_flight.fetch_add(1, Ordering::Relaxed) + 1; + self.peak_in_flight.fetch_max(current, Ordering::Relaxed); + } + + fn finished(&self, count: usize) { + if count != 0 { + self.current_in_flight.fetch_sub(count, Ordering::Relaxed); + } + } + + fn snapshot(&self) -> ComputeCoalescingStats { + let coalescing_hits = self.coalescing_hits.load(Ordering::Relaxed); + let unique_keyed_builds = self.unique_keyed_builds.load(Ordering::Relaxed); + ComputeCoalescingStats { + keyed_submissions: coalescing_hits.saturating_add(unique_keyed_builds), + coalescing_hits, + unique_keyed_builds, + current_in_flight: self.current_in_flight.load(Ordering::Relaxed), + peak_in_flight: self.peak_in_flight.load(Ordering::Relaxed), + } + } +} + +static COALESCING: CoalescingCounters = CoalescingCounters::new(); + +pub fn compute_coalescing_stats() -> ComputeCoalescingStats { + COALESCING.snapshot() +} + fn forget_in_flight(build: &Arc) { let Some(key) = &build.compute_key else { return }; let mut registry = IN_FLIGHT.lock().unwrap(); let Some(builds) = registry.as_mut() else { return }; if builds.get(key.as_ref()).is_some_and(|weak| Weak::ptr_eq(weak, &Arc::downgrade(build))) { builds.remove(key.as_ref()); + COALESCING.finished(1); } } @@ -544,24 +607,31 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, comp let build = if let Some(compute_key) = compute_key { let mut registry = IN_FLIGHT.lock().unwrap(); let builds = registry.get_or_insert_with(HashMap::new); + let before = builds.len(); builds.retain(|_, build| build.strong_count() != 0); + COALESCING.finished(before - builds.len()); if let Some(build) = builds.get(&compute_key).and_then(Weak::upgrade) { let done = build.done.lock().unwrap(); if !*done && !build.orphan.load(Ordering::Acquire) { build.owners.fetch_add(1, Ordering::Relaxed); drop(done); + COALESCING.hit(); build } else { - builds.remove(&compute_key); + if builds.remove(&compute_key).is_some() { + COALESCING.finished(1); + } let compute_key = Arc::new(compute_key); let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()))); builds.insert(compute_key, Arc::downgrade(&build)); + COALESCING.unique(); build } } else { let compute_key = Arc::new(compute_key); let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()))); builds.insert(compute_key, Arc::downgrade(&build)); + COALESCING.unique(); build } } else { @@ -678,6 +748,28 @@ fn preload_enabled() -> bool { mod used_tests { use super::*; + #[test] + fn coalescing_counter_math_tracks_lifetime_current_and_peak() { + let counters = CoalescingCounters::new(); + counters.unique(); + counters.hit(); + counters.unique(); + counters.finished(1); + assert_eq!( + counters.snapshot(), + ComputeCoalescingStats { + keyed_submissions: 3, + coalescing_hits: 1, + unique_keyed_builds: 2, + current_in_flight: 1, + peak_in_flight: 2, + } + ); + counters.finished(1); + assert_eq!(counters.snapshot().current_in_flight, 0); + assert_eq!(counters.snapshot().peak_in_flight, 2); + } + fn compute_key(tag: u8) -> super::super::real::compute_build_key::ComputeBuildKey { super::super::real::compute_build_key::ComputeBuildKey::capture( 1, diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index c1c9012268..9d38a4dd14 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -12,6 +12,7 @@ use serde::{Deserialize, Serialize}; use crate::resolver::{self, Source}; pub const STALL_SUMMARY_VERSION: u32 = 1; +pub const PREPARATION_SUMMARY_VERSION: u32 = 1; #[derive(Debug, Serialize, Deserialize, Default)] pub struct StubCall { @@ -131,6 +132,14 @@ impl From for StallSummary { } } +#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq)] +pub struct PreparationSummary { + #[serde(default)] + pub version: u32, + #[serde(default)] + pub compute_build_coalescing: crate::hle::d3d12x::pso_async::ComputeCoalescingStats, +} + #[derive(Debug, Serialize, Deserialize, Default)] pub struct Report { pub xcl_version: String, @@ -156,6 +165,9 @@ pub struct Report { /// none was loaded) #[serde(default)] pub dxc: crate::gpu::recomp::dxc::Toolchain, + /// Versioned preparation-plane counters. Optional so reports from older XCL builds load. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preparation: Option, /// D3D12.X backend: adapter, interface layouts, unknown IIDs, fallbacks, presented frames #[serde(default)] pub d3d12: crate::hle::d3d12x::real::D3d12Stats, @@ -237,6 +249,10 @@ pub fn build() -> Report { vfs, shaders: crate::gpu::shader::stats(), dxc: crate::gpu::recomp::dxc::toolchain(), + preparation: Some(PreparationSummary { + version: PREPARATION_SUMMARY_VERSION, + compute_build_coalescing: crate::hle::d3d12x::pso_async::compute_coalescing_stats(), + }), d3d12: crate::hle::d3d12x::real::stats(), audio: crate::hle::xaudio2::stats(), xgameruntime: crate::hle::xgameruntime::api::stats(), @@ -297,8 +313,31 @@ mod tests { fn old_reports_without_a_stall_summary_still_deserialize() { let old = serde_json::to_value(Report::default()).unwrap(); assert!(old.get("stalls").is_none(), "an absent summary is not serialized"); + assert!(old.get("preparation").is_none(), "an absent preparation summary is not serialized"); let report: Report = serde_json::from_value(old).unwrap(); assert!(report.stalls.is_none()); + assert!(report.preparation.is_none()); + } + + #[test] + fn preparation_summary_has_a_versioned_stable_json_shape() { + let summary = PreparationSummary { + version: PREPARATION_SUMMARY_VERSION, + compute_build_coalescing: crate::hle::d3d12x::pso_async::ComputeCoalescingStats { + keyed_submissions: 12, + coalescing_hits: 5, + unique_keyed_builds: 7, + current_in_flight: 3, + peak_in_flight: 6, + }, + }; + let json = serde_json::to_value(summary).unwrap(); + assert_eq!(json["version"], PREPARATION_SUMMARY_VERSION); + assert_eq!(json["compute_build_coalescing"]["keyed_submissions"], 12); + assert_eq!(json["compute_build_coalescing"]["coalescing_hits"], 5); + assert_eq!(json["compute_build_coalescing"]["unique_keyed_builds"], 7); + assert_eq!(json["compute_build_coalescing"]["current_in_flight"], 3); + assert_eq!(json["compute_build_coalescing"]["peak_in_flight"], 6); } #[test] From dfcd4bbba062eb08d305aba507af1ffe7d1cc857 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:32:22 -0800 Subject: [PATCH 020/265] Scripts: fingerprint performance workloads Identify a workload from a deterministic metadata inventory instead of only its folder name, verify the inventory around each paired run, and require matching identity algorithms in comparisons. Persist no paths or file names and document that the fingerprint is not a content hash. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 12 +++++-- scripts/perf-compare.ps1 | 14 +++++++- scripts/perf-compare.tests.ps1 | 20 ++++++++++++ scripts/perf-run.ps1 | 60 +++++++++++++++++++++++++++++++--- scripts/perf-run.tests.ps1 | 18 ++++++++++ 5 files changed, 116 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index d598768a3f..dad0abee64 100644 --- a/README.md +++ b/README.md @@ -344,6 +344,12 @@ changed, or deleted. The output folder contains only each run's `xcl.log` and `r a versioned `manifest.json` with the commit, run order, hardware/toolchain, selected XCL environment, cache identity, durations, and exit status. It contains no game files or cache data. +The manifest identifies the workload with a SHA-256 metadata fingerprint over its sorted relative +file paths, lengths, and UTC modification-time ticks. Only the fingerprint and its algorithm/version +are recorded; the inventory's file names and absolute paths are not persisted. This is a metadata +fingerprint, not a content hash: a content change that preserves the path, length, and modification +time is not detected. + The manifest calls these states **XCL-cold** and **XCL-warm**. GPU driver caches are driver-controlled and are explicitly recorded as `uncontrolled`; this is not a fully cold-driver benchmark. @@ -356,9 +362,9 @@ Compare two completed artifact folders without modifying them: The console shows raw cold/warm duration, exit/timeout state, and available stall totals, counts, and maxima. The redirected JSON keeps those values, raw deltas, and log2 histograms. The tool -refuses different workloads, run order, requested duration, runtime environment, system, GPU, or -GPU driver. Missing reports and stall summaries are labelled as missing; it does not infer -significance or percentages. +refuses different workload fingerprints or identity algorithm/versions, run order, requested +duration, runtime environment, system, GPU, or GPU driver. Missing reports and stall summaries are +labelled as missing; it does not infer significance or percentages. ## Tests diff --git a/scripts/perf-compare.ps1 b/scripts/perf-compare.ps1 index c78dc8c3c0..8d4f7745e3 100644 --- a/scripts/perf-compare.ps1 +++ b/scripts/perf-compare.ps1 @@ -44,6 +44,10 @@ function Read-Manifest([string]$Root, [string]$Side) { if ([string]::IsNullOrWhiteSpace([string]$manifest.workload_id)) { throw "$Side has no workload_id" } + if ([string]::IsNullOrWhiteSpace([string]$manifest.workload_id_algorithm) -or + -not (Has-Property $manifest 'workload_id_version') -or ([int]$manifest.workload_id_version -lt 1)) { + throw "$Side has no valid workload identity algorithm/version" + } $labels = @($manifest.run_order) if ($labels.Count -ne 2 -or $labels[0] -ne 'xcl-cold' -or $labels[1] -ne 'xcl-warm') { throw "$Side run_order must be xcl-cold, xcl-warm" @@ -147,7 +151,13 @@ $candidateRoot = [IO.Path]::GetFullPath($Candidate) $beforeManifest = Read-Manifest $baselineRoot 'baseline' $afterManifest = Read-Manifest $candidateRoot 'candidate' -if ($beforeManifest.workload_id -ne $afterManifest.workload_id) { throw 'workload_id differs; runs are incomparable' } +if ($beforeManifest.workload_id -cne $afterManifest.workload_id) { throw 'workload_id differs; runs are incomparable' } +if ($beforeManifest.workload_id_algorithm -cne $afterManifest.workload_id_algorithm) { + throw 'workload identity algorithm differs; runs are incomparable' +} +if ([int]$beforeManifest.workload_id_version -ne [int]$afterManifest.workload_id_version) { + throw 'workload identity version differs; runs are incomparable' +} if ((@($beforeManifest.run_order) -join ',') -ne (@($afterManifest.run_order) -join ',')) { throw 'run order differs; runs are incomparable' } Require-Same-Property $beforeManifest $afterManifest 'system' 'system information' if (($beforeManifest.environment | ConvertTo-Json -Compress -Depth 6) -ne ($afterManifest.environment | ConvertTo-Json -Compress -Depth 6)) { @@ -204,6 +214,8 @@ for ($i = 0; $i -lt 2; $i++) { schema = 'xcl-perf-comparison' version = 1 workload_id = $beforeManifest.workload_id + workload_id_algorithm = $beforeManifest.workload_id_algorithm + workload_id_version = [int]$beforeManifest.workload_id_version run_order = @($beforeManifest.run_order) baseline = [ordered]@{ commit = $beforeManifest.commit; path = $baselineRoot } candidate = [ordered]@{ commit = $afterManifest.commit; path = $candidateRoot } diff --git a/scripts/perf-compare.tests.ps1 b/scripts/perf-compare.tests.ps1 index 2a1c41c7d2..3a1212734d 100644 --- a/scripts/perf-compare.tests.ps1 +++ b/scripts/perf-compare.tests.ps1 @@ -13,6 +13,8 @@ function Write-Fixture([string]$Root, [string]$Commit, [int]$ColdMs, $WarmMs) { dirty = $false build = [ordered]@{ profile = 'release' } workload_id = 'same-workload' + workload_id_algorithm = 'sha256-relative-path-length-mtime-utc-ticks' + workload_id_version = 1 run_order = @('xcl-cold', 'xcl-warm') environment = [ordered]@{ XCL_PRESS_AT = '20:A' } runs = @( @@ -43,6 +45,8 @@ try { $json = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json if ($json.schema -ne 'xcl-perf-comparison' -or $json.version -ne 1) { throw 'wrong output schema' } + if ($json.workload_id_algorithm -ne 'sha256-relative-path-length-mtime-utc-ticks' -or + $json.workload_id_version -ne 1) { throw 'workload identity contract is missing from output' } if ($json.runs[0].duration_ms.delta -ne -150) { throw 'cold duration delta is wrong' } if ($json.runs[1].duration_ms.delta -ne 0) { throw 'zero durations were not compared as raw values' } if ($json.runs[1].exit_code.candidate -ne $null -or $json.runs[1].timed_out.candidate -ne $true) { throw 'missing exit/timeout was not preserved' } @@ -60,6 +64,22 @@ try { try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'workload_id differs' } if (-not $refused) { throw 'different workloads were not refused' } + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.workload_id_algorithm = 'other-algorithm' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'workload identity algorithm differs' } + if (-not $refused) { throw 'different workload identity algorithms were not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.workload_id_version = 2 + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'workload identity version differs' } + if (-not $refused) { throw 'different workload identity versions were not refused' } + Write-Fixture $candidate 'candidate-commit' 850 0 $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json $candidateManifest.runs[1].cache_state = 'xcl-cold' diff --git a/scripts/perf-run.ps1 b/scripts/perf-run.ps1 index 277c6cf68c..326d31aa15 100644 --- a/scripts/perf-run.ps1 +++ b/scripts/perf-run.ps1 @@ -12,6 +12,55 @@ if ($Seconds -lt 1) { throw '-Seconds must be at least 1' } if (-not (Test-Path -LiteralPath $Game -PathType Container)) { throw "game folder not found: $Game" } $gamePath = [IO.Path]::GetFullPath($Game) $root = Split-Path $PSScriptRoot -Parent +$workloadAlgorithm = 'sha256-relative-path-length-mtime-utc-ticks' +$workloadAlgorithmVersion = 1 + +function Read-InventoryRecords([string]$Path) { + $separators = [char[]]@([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar) + $prefix = $Path.TrimEnd($separators) + [IO.Path]::DirectorySeparatorChar + $byPath = @{} + try { + foreach ($file in Get-ChildItem -LiteralPath $Path -Recurse -Force -File -ErrorAction Stop) { + $full = [IO.Path]::GetFullPath($file.FullName) + if (-not $full.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { + throw "inventory path escaped the game folder" + } + $info = New-Object IO.FileInfo $full + $info.Refresh() + if (-not $info.Exists) { throw "file disappeared during inventory: $($file.Name)" } + $relative = $full.Substring($prefix.Length).Replace([IO.Path]::DirectorySeparatorChar, '/') + if ($byPath.ContainsKey($relative)) { throw "duplicate relative inventory path: $relative" } + $length = $info.Length.ToString([Globalization.CultureInfo]::InvariantCulture) + $ticks = $info.LastWriteTimeUtc.Ticks.ToString([Globalization.CultureInfo]::InvariantCulture) + $byPath[$relative] = '{0}:{1}|{2}|{3}' -f $relative.Length, $relative, $length, $ticks + } + } catch { + throw "cannot create a complete game metadata inventory: $($_.Exception.Message)" + } + if ($byPath.Count -eq 0) { throw 'cannot fingerprint an empty game folder' } + [string[]]$paths = @($byPath.Keys) + [Array]::Sort($paths, [StringComparer]::Ordinal) + return @($paths | ForEach-Object { $byPath[$_] }) +} + +function Get-WorkloadIdentity([string]$Path) { + $first = @(Read-InventoryRecords $Path) + $second = @(Read-InventoryRecords $Path) + if ($first.Count -ne $second.Count) { throw 'game metadata inventory changed while it was read' } + for ($i = 0; $i -lt $first.Count; $i++) { + if ($first[$i] -cne $second[$i]) { throw 'game metadata inventory changed while it was read' } + } + $bytes = [Text.Encoding]::UTF8.GetBytes([string]::Join([char]10, [string[]]$first)) + $sha = [Security.Cryptography.SHA256]::Create() + try { + $id = -join ($sha.ComputeHash($bytes) | ForEach-Object { $_.ToString('x2') }) + } finally { + $sha.Dispose() + } + return [ordered]@{ algorithm = $workloadAlgorithm; version = $workloadAlgorithmVersion; id = $id } +} + +$workloadIdentity = Get-WorkloadIdentity $gamePath function Run-Git([string[]]$Arguments) { $out = @(& git.exe -C $root @Arguments) @@ -170,9 +219,10 @@ try { } catch { } $rust = (& rustc -Vv) -join [Environment]::NewLine if ($LASTEXITCODE -ne 0) { throw 'rustc -Vv failed' } - $sha = [Security.Cryptography.SHA256]::Create() - $workloadId = -join ($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes((Split-Path $gamePath -Leaf).Trim()))[0..7] | ForEach-Object { $_.ToString('x2') }) - $sha.Dispose() + $verifiedWorkloadIdentity = Get-WorkloadIdentity $gamePath + if ($verifiedWorkloadIdentity.id -ne $workloadIdentity.id) { + throw 'game metadata inventory changed during the performance runs' + } $manifest = [ordered]@{ schema = 'xcl-perf-run' @@ -180,7 +230,9 @@ try { commit = $commit dirty = $false build = [ordered]@{ profile = 'release'; command = 'cargo build --locked --release -p xcl' } - workload_id = $workloadId + workload_id = $workloadIdentity.id + workload_id_algorithm = $workloadIdentity.algorithm + workload_id_version = $workloadIdentity.version run_order = @('xcl-cold', 'xcl-warm') system = [ordered]@{ cpu = $cpu; windows = $windows; rust = $rust } environment = $recordedEnvironment diff --git a/scripts/perf-run.tests.ps1 b/scripts/perf-run.tests.ps1 index f2863fca63..38fb8ce464 100644 --- a/scripts/perf-run.tests.ps1 +++ b/scripts/perf-run.tests.ps1 @@ -7,6 +7,8 @@ $repo = Join-Path $fixture 'repo' $scripts = Join-Path $repo 'scripts' $game = Join-Path $fixture 'Mock Game' $out = Join-Path $fixture 'artifacts' +$otherGame = Join-Path (Join-Path $fixture 'other-build') 'Mock Game' +$otherOut = Join-Path $fixture 'other-artifacts' $bin = Join-Path $fixture 'bin' $userData = Join-Path $fixture 'user-data' $userDxil = Join-Path $fixture 'user-dxil' @@ -69,11 +71,18 @@ exit /b 0 if ($LASTEXITCODE -ne 0) { throw "perf-run.ps1 exited with $LASTEXITCODE" } $manifest = Get-Content -LiteralPath (Join-Path $out 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $manifestRaw = Get-Content -LiteralPath (Join-Path $out 'manifest.json') -Raw -Encoding utf8 if ($manifest.schema -ne 'xcl-perf-run' -or $manifest.version -ne 1) { throw 'wrong manifest schema/version' } if ($manifest.dirty -ne $false -or $manifest.build.profile -ne 'release') { throw 'build identity was not recorded' } if (($manifest.run_order -join ',') -ne 'xcl-cold,xcl-warm') { throw 'run order was not cold then warm' } if ($manifest.cache.driver -ne 'uncontrolled') { throw 'driver cache was not labelled uncontrolled' } if ($manifest.environment.XCL_PRESS_AT -ne '20:A,24:A') { throw 'input schedule was not recorded' } + if ($manifest.workload_id_algorithm -ne 'sha256-relative-path-length-mtime-utc-ticks' -or + $manifest.workload_id_version -ne 1) { throw 'workload identity algorithm/version was not recorded' } + if ($manifest.workload_id -notmatch '^[0-9a-f]{64}$') { throw 'workload identity is not a full SHA-256 value' } + if ($manifestRaw.Contains($game) -or $manifestRaw.Contains('game-data.bin')) { + throw 'workload inventory details leaked into the manifest' + } if ($manifest.runs.Count -ne 2 -or $manifest.runs[0].cache_state -ne 'xcl-cold' -or $manifest.runs[1].cache_state -ne 'xcl-warm') { throw 'run records are incomplete' } if ((Get-Content -LiteralPath (Join-Path $out 'runs\01-cold\xcl.log') -Raw) -notmatch 'cache=cold') { throw 'cold run did not start with a fresh DXIL cache' } if ((Get-Content -LiteralPath (Join-Path $out 'runs\02-warm\xcl.log') -Raw) -notmatch 'cache=warm') { throw 'warm run did not reuse the cold cache' } @@ -86,6 +95,15 @@ exit /b 0 if (Test-Path -LiteralPath (Join-Path ([IO.Path]::GetTempPath()) ("xcl-perf-$($manifest.cache.identity)"))) { throw 'the ephemeral cache was not removed' } if ((Get-Content -LiteralPath $cargoMarker -Raw) -notmatch 'build --locked --release -p xcl') { throw 'release build command was not run' } + $null = New-Item -ItemType Directory -Path $otherGame -Force + 'a different title build with the same folder leaf' | Set-Content -LiteralPath (Join-Path $otherGame 'game-data.bin') -Encoding Ascii + & (Join-Path $scripts 'perf-run.ps1') -Game $otherGame -OutDir $otherOut -Seconds 2 + if ($LASTEXITCODE -ne 0) { throw "second perf-run.ps1 exited with $LASTEXITCODE" } + $otherManifest = Get-Content -LiteralPath (Join-Path $otherOut 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + if ($otherManifest.workload_id -eq $manifest.workload_id) { + throw 'different builds with the same folder leaf received the same workload identity' + } + Add-Content -LiteralPath (Join-Path $repo '.gitignore') -Value '# dirty' $refused = $false try { From 5e56df02c6fc823c2309b27fdef9bde2468cdc4e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:34:13 -0800 Subject: [PATCH 021/265] D3D12.X: attribute pipeline and driver stalls Measure only unresolved blocking pipeline waits, driver admission/headroom waits, and the actual CreatePipelineState driver calls. Keep translation, scheduling, injected failures, and nonblocking resolves outside those scopes. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 4 +++- crates/xcl/src/hle/d3d12x/real.rs | 11 ++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 092320fe48..dd7db587d6 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1449,7 +1449,9 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { return resolve_spared(&p, pso); } // (the title's thread is held from here until the pipeline is built or the budget is over) - let _held = (!*p.build.done.lock().unwrap()).then(Held::new); + let waiting = !*p.build.done.lock().unwrap(); + let _held = waiting.then(Held::new); + let _stall = waiting.then(|| crate::stall::span(crate::stall::StallKind::PipelineWait)).flatten(); if let Some(budget) = budget { return resolve_within(&p, pso, budget); } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 8274c5e7b7..d7f177bc3a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3802,7 +3802,12 @@ pub fn switch_form_retries() -> u64 { unsafe fn driver_pso(f: PsoFn, this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let heap = crate::gpu::recomp::pso::mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0; let injected = heap && INJECTED_OOM.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)).is_ok(); - let hr = if injected { E_OUTOFMEMORY } else { f(this, desc, riid, ppv) }; + let hr = if injected { + E_OUTOFMEMORY + } else { + let _stall = crate::stall::span(crate::stall::StallKind::DriverCompile); + f(this, desc, riid, ppv) + }; if hr == E_OUTOFMEMORY && heap { HEAP_WINDOW_OOM.with(|o| o.set(true)); } @@ -4046,7 +4051,9 @@ fn pso_trace() -> bool { fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Option<(u64, bool)>, build: impl FnOnce() -> R) -> (R, std::time::Duration) { let huge = gate && bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); + let gate_stall = huge.then(|| crate::stall::span(crate::stall::StallKind::DriverCompileGate)).flatten(); let _slot = huge.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + drop(gate_stall); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; @@ -6003,7 +6010,9 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let bytes = stream.shader_bytes() + tp.cs.len(); let gate = bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); + let gate_stall = gate.then(|| crate::stall::span(crate::stall::StallKind::DriverCompileGate)).flatten(); let _slot = gate.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + drop(gate_stall); if gate { crate::xlog_info!("D3D12.X: two-pass {kind} PSO ({bytes} B DXIL) gated, waited {} ms", waited.elapsed().as_millis()); } From 77a80a95bf42f741baf18300b05699638ea1b40f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:35:34 -0800 Subject: [PATCH 022/265] Scripts: compare pipeline preparation counters Read versioned compute-build coalescing counters from performance reports and emit their raw values and deltas. Preserve missing and unsupported summaries as explicit states instead of treating them as zero. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 6 ++- scripts/perf-compare.ps1 | 70 ++++++++++++++++++++++++++++++++++ scripts/perf-compare.tests.ps1 | 52 ++++++++++++++++++++++--- 3 files changed, 121 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index dad0abee64..e8367c3af3 100644 --- a/README.md +++ b/README.md @@ -360,8 +360,10 @@ Compare two completed artifact folders without modifying them: .\scripts\perf-compare.ps1 -Baseline 'D:\xcl-perf\main' -Candidate 'D:\xcl-perf\change' > comparison.json ``` -The console shows raw cold/warm duration, exit/timeout state, and available stall totals, counts, -and maxima. The redirected JSON keeps those values, raw deltas, and log2 histograms. The tool +The console shows raw cold/warm duration, exit/timeout state, stall totals/counts/maxima, and the five +compute-build coalescing counters. The redirected JSON keeps those values, raw deltas, and stall log2 +histograms. Missing reports or preparation summaries and unsupported preparation versions remain +explicit states; they are not treated as zero. The tool refuses different workload fingerprints or identity algorithm/versions, run order, requested duration, runtime environment, system, GPU, or GPU driver. Missing reports and stall summaries are labelled as missing; it does not infer significance or percentages. diff --git a/scripts/perf-compare.ps1 b/scripts/perf-compare.ps1 index 8d4f7745e3..e71f8a909a 100644 --- a/scripts/perf-compare.ps1 +++ b/scripts/perf-compare.ps1 @@ -87,6 +87,48 @@ function Read-Stalls([string]$Root, [int]$Order, [string]$Label) { return [ordered]@{ status = 'present'; aggregates = $aggregates } } +function Read-Nonnegative-Integer($Object, [string]$Name, [string]$Context) { + if (-not (Has-Property $Object $Name) -or $null -eq $Object.$Name -or + $Object.$Name -is [bool] -or $Object.$Name -is [string]) { + throw "malformed $Context counter: $Name" + } + try { $value = [decimal]$Object.$Name } catch { throw "malformed $Context counter: $Name" } + if ($value -lt 0 -or $value -ne [decimal]::Truncate($value) -or + $value -gt [decimal][uint64]::MaxValue) { + throw "malformed $Context counter: $Name" + } + return $value +} + +function Read-Preparation([string]$Root, [int]$Order, [string]$Label) { + $mode = $Label.Substring(4) + $report = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'report.json')) + if (-not (Test-Path -LiteralPath $report -PathType Leaf)) { + return [ordered]@{ status = 'missing_report'; counters = $null } + } + $json = Read-Json $report + if (-not (Has-Property $json 'preparation') -or $null -eq $json.preparation) { + return [ordered]@{ status = 'missing_preparation'; counters = $null } + } + $summary = $json.preparation + $version = Read-Nonnegative-Integer $summary 'version' 'preparation version' + if ($version -eq 0) { throw "malformed preparation version in $report" } + if ($version -ne 1) { + return [ordered]@{ status = 'unsupported_version'; counters = $null } + } + if (-not (Has-Property $summary 'compute_build_coalescing') -or + $null -eq $summary.compute_build_coalescing) { + throw "malformed preparation counters in $report" + } + $raw = $summary.compute_build_coalescing + $counters = [ordered]@{} + foreach ($name in @('keyed_submissions', 'coalescing_hits', 'unique_keyed_builds', + 'current_in_flight', 'peak_in_flight')) { + $counters[$name] = Read-Nonnegative-Integer $raw $name "preparation in $report" + } + return [ordered]@{ status = 'present'; counters = $counters } +} + function Number-Or-Null($Object, [string]$Name) { if ($null -eq $Object -or -not (Has-Property $Object $Name) -or $null -eq $Object.$Name) { return $null } return [long]$Object.$Name @@ -97,6 +139,20 @@ function Delta-Or-Null($Before, $After) { return [long]$After - [long]$Before } +function Counter-Delta-Or-Null($Before, $After) { + if ($null -eq $Before -or $null -eq $After) { return $null } + return [decimal]$After - [decimal]$Before +} + +function Compare-Counters($Before, $After) { + $delta = [ordered]@{} + foreach ($name in @('keyed_submissions', 'coalescing_hits', 'unique_keyed_builds', + 'current_in_flight', 'peak_in_flight')) { + $delta[$name] = Counter-Delta-Or-Null $Before.$name $After.$name + } + return [ordered]@{ baseline = $Before; candidate = $After; delta = $delta } +} + function Bool-Or-Null($Object, [string]$Name) { if ($null -eq $Object -or -not (Has-Property $Object $Name) -or $null -eq $Object.$Name) { return $null } return [bool]$Object.$Name @@ -178,6 +234,9 @@ for ($i = 0; $i -lt 2; $i++) { $beforeStalls = Read-Stalls $baselineRoot ($i + 1) $beforeRun.cache_state $afterStalls = Read-Stalls $candidateRoot ($i + 1) $afterRun.cache_state $stalls = @(Compare-Aggregates $beforeStalls.aggregates $afterStalls.aggregates) + $beforePreparation = Read-Preparation $baselineRoot ($i + 1) $beforeRun.cache_state + $afterPreparation = Read-Preparation $candidateRoot ($i + 1) $afterRun.cache_state + $coalescing = Compare-Counters $beforePreparation.counters $afterPreparation.counters $comparison = [ordered]@{ label = $beforeRun.cache_state @@ -196,6 +255,11 @@ for ($i = 0; $i -lt 2; $i++) { } stalls_status = [ordered]@{ baseline = $beforeStalls.status; candidate = $afterStalls.status } stalls = $stalls + preparation_status = [ordered]@{ + baseline = $beforePreparation.status + candidate = $afterPreparation.status + } + compute_build_coalescing = $coalescing } $comparisons += $comparison @@ -208,6 +272,12 @@ for ($i = 0; $i -lt 2; $i++) { Write-Host " stall $($stall.kind): total $(Display-Value $stall.baseline.total_ns ' ns') -> $(Display-Value $stall.candidate.total_ns ' ns'); count $(Display-Value $stall.baseline.count '') -> $(Display-Value $stall.candidate.count ''); max $(Display-Value $stall.baseline.max_ns ' ns') -> $(Display-Value $stall.candidate.max_ns ' ns')" } } + Write-Host " preparation: $($beforePreparation.status) -> $($afterPreparation.status)" + if ($beforePreparation.status -eq 'present' -or $afterPreparation.status -eq 'present') { + foreach ($name in $coalescing.delta.Keys) { + Write-Host " $($name): $(Display-Value $coalescing.baseline.$name '') -> $(Display-Value $coalescing.candidate.$name ''); delta $(Display-Value $coalescing.delta.$name '')" + } + } } [ordered]@{ diff --git a/scripts/perf-compare.tests.ps1 b/scripts/perf-compare.tests.ps1 index 3a1212734d..046f19c2ad 100644 --- a/scripts/perf-compare.tests.ps1 +++ b/scripts/perf-compare.tests.ps1 @@ -25,22 +25,32 @@ function Write-Fixture([string]$Root, [string]$Commit, [int]$ColdMs, $WarmMs) { $manifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $Root 'manifest.json') -Encoding utf8 } -function Write-Report([string]$Path, [int]$Count, [long]$Total, [long]$Maximum, [switch]$ExtraKind) { +function Write-Report([string]$Path, [int]$Count, [long]$Total, [long]$Maximum, + $Preparation = $null, [int]$PreparationVersion = 1, [switch]$ExtraKind) { $aggregates = @( [ordered]@{ kind = 'dxc_compile'; count = $Count; total_ns = $Total; max_ns = $Maximum; histogram_log2_ns = @(0, $Count) } ) if ($ExtraKind) { $aggregates += [ordered]@{ kind = 'gpu_wait'; count = 1; total_ns = 9; max_ns = 9; histogram_log2_ns = @(0, 0, 0, 1) } } - [ordered]@{ stalls = [ordered]@{ version = 1; aggregates = $aggregates; slow_events = @() } } | + $report = [ordered]@{ stalls = [ordered]@{ version = 1; aggregates = $aggregates; slow_events = @() } } + if ($null -ne $Preparation) { + $report['preparation'] = [ordered]@{ + version = $PreparationVersion + compute_build_coalescing = $Preparation + } + } + $report | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $Path -Encoding utf8 } try { Write-Fixture $baseline 'base-commit' 1000 0 Write-Fixture $candidate 'candidate-commit' 850 0 - Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 - Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 -ExtraKind + $beforePreparation = [ordered]@{ keyed_submissions = 12; coalescing_hits = 5; unique_keyed_builds = 7; current_in_flight = 0; peak_in_flight = 3 } + $afterPreparation = [ordered]@{ keyed_submissions = 10; coalescing_hits = 6; unique_keyed_builds = 4; current_in_flight = 1; peak_in_flight = 5 } + Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation -ExtraKind [ordered]@{ d3d12 = [ordered]@{} } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $baseline 'runs\02-warm\report.json') -Encoding utf8 $json = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json @@ -55,7 +65,39 @@ try { $gpu = $json.runs[0].stalls | Where-Object { $_.kind -eq 'gpu_wait' } if ($null -ne $gpu.baseline -or $gpu.candidate.total_ns -ne 9 -or $null -ne $gpu.delta.total_ns) { throw 'one-sided stall data was not labelled missing' } if ($json.runs[1].stalls_status.baseline -ne 'missing_stalls' -or $json.runs[1].stalls_status.candidate -ne 'missing_report') { throw 'missing report/stalls states are wrong' } - if (($json | ConvertTo-Json -Depth 12) -match 'percent|ratio|significant') { throw 'output invented a derived significance metric' } + $preparation = $json.runs[0].compute_build_coalescing + if ($preparation.baseline.keyed_submissions -ne 12 -or $preparation.candidate.keyed_submissions -ne 10 -or + $preparation.baseline.coalescing_hits -ne 5 -or $preparation.candidate.coalescing_hits -ne 6 -or + $preparation.baseline.unique_keyed_builds -ne 7 -or $preparation.candidate.unique_keyed_builds -ne 4 -or + $preparation.baseline.current_in_flight -ne 0 -or $preparation.candidate.current_in_flight -ne 1 -or + $preparation.baseline.peak_in_flight -ne 3 -or $preparation.candidate.peak_in_flight -ne 5 -or + $preparation.delta.keyed_submissions -ne -2 -or $preparation.delta.coalescing_hits -ne 1 -or + $preparation.delta.unique_keyed_builds -ne -3 -or $preparation.delta.current_in_flight -ne 1 -or + $preparation.delta.peak_in_flight -ne 2) { throw 'preparation counters or deltas are wrong' } + if ($json.runs[1].preparation_status.baseline -ne 'missing_preparation' -or + $json.runs[1].preparation_status.candidate -ne 'missing_report' -or + $null -ne $json.runs[1].compute_build_coalescing.delta.keyed_submissions) { + throw 'missing preparation data was treated as zero' + } + if (($json | ConvertTo-Json -Depth 12) -match '"(percent|percentage|ratio|significance|significant)"\s*:') { + throw 'output invented a derived significance metric' + } + + Write-Report (Join-Path $candidate 'runs\02-warm\report.json') 1 1 1 $afterPreparation 2 + $unsupported = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json + if ($unsupported.runs[1].preparation_status.candidate -ne 'unsupported_version' -or + $null -ne $unsupported.runs[1].compute_build_coalescing.candidate) { + throw 'unsupported preparation version was not preserved as a state' + } + + $badReportPath = Join-Path $candidate 'runs\01-cold\report.json' + $badReport = Get-Content -LiteralPath $badReportPath -Raw -Encoding utf8 | ConvertFrom-Json + $badReport.preparation.compute_build_coalescing.coalescing_hits = -1 + $badReport | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $badReportPath -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed preparation' } + if (-not $refused) { throw 'a malformed preparation counter was not refused' } + Write-Report $badReportPath 3 80 40 $afterPreparation -ExtraKind $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json $candidateManifest.workload_id = 'other-workload' From fedfbe4ca4157e3eaa8fc425981781a2b997259b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:36:47 -0800 Subject: [PATCH 023/265] D3D12.X: cache compute build key shader hashes Hash full shader bytes once when capturing a canonical compute identity and reuse its digest for registry operations. Keep exact byte equality after all cheap fields so hash collisions cannot coalesce different programs. Assisted-by: Codex (GPT-5.6-sol) --- .../src/hle/d3d12x/real/compute_build_key.rs | 92 +++++++++++++++++-- 1 file changed, 84 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs b/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs index 0d30eb181d..c35b505bfe 100644 --- a/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs +++ b/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs @@ -1,4 +1,7 @@ -use std::sync::Arc; +use std::{ + hash::{Hash, Hasher}, + sync::Arc, +}; use windows::Win32::Graphics::Direct3D12::D3D12_COMPUTE_PIPELINE_STATE_DESC; @@ -14,12 +17,14 @@ const COMPUTE_ABI_SCHEMA: u32 = 1; /// collision-freely identified by the complete shader bytes, translation policy, and sampler /// base; those bytes also identify the program's intrinsic wave mode. The title root signature /// and cached PSO are intentionally absent: translation replaces both before calling the PC driver. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug)] pub(in crate::hle::d3d12x) struct ComputeBuildKey { device: usize, node_mask: u32, flags: i32, shader: Arc<[u8]>, + shader_digest: u64, + shader_len: usize, windows: u32, split_wave64: bool, policy: ComputePolicyKey, @@ -27,6 +32,39 @@ pub(in crate::hle::d3d12x) struct ComputeBuildKey { static_sampler_base: u32, } +impl PartialEq for ComputeBuildKey { + fn eq(&self, other: &Self) -> bool { + self.device == other.device + && self.node_mask == other.node_mask + && self.flags == other.flags + && self.windows == other.windows + && self.split_wave64 == other.split_wave64 + && self.policy == other.policy + && self.abi_schema == other.abi_schema + && self.static_sampler_base == other.static_sampler_base + && self.shader_digest == other.shader_digest + && self.shader_len == other.shader_len + && self.shader == other.shader + } +} + +impl Eq for ComputeBuildKey {} + +impl Hash for ComputeBuildKey { + fn hash(&self, state: &mut H) { + self.device.hash(state); + self.node_mask.hash(state); + self.flags.hash(state); + self.windows.hash(state); + self.split_wave64.hash(state); + self.policy.hash(state); + self.abi_schema.hash(state); + self.static_sampler_base.hash(state); + self.shader_digest.hash(state); + self.shader_len.hash(state); + } +} + impl ComputeBuildKey { pub(in crate::hle::d3d12x) fn capture( device: usize, @@ -65,11 +103,30 @@ impl ComputeBuildKey { policy: ComputePolicyKey, ) -> Self { debug_assert_ne!(device, 0); + let shader_digest = crate::gpu::shader::fnv64(&shader); + Self::from_parts_with_digest( + device, node_mask, flags, shader, shader_digest, windows, split_wave64, policy, + ) + } + + fn from_parts_with_digest( + device: usize, + node_mask: u32, + flags: i32, + shader: Arc<[u8]>, + shader_digest: u64, + windows: u32, + split_wave64: bool, + policy: ComputePolicyKey, + ) -> Self { + let shader_len = shader.len(); Self { device, node_mask, flags, shader, + shader_digest, + shader_len, windows, split_wave64, policy, @@ -82,6 +139,13 @@ impl ComputeBuildKey { #[cfg(test)] mod tests { use super::*; + use std::collections::hash_map::DefaultHasher; + + fn hash(key: &ComputeBuildKey) -> u64 { + let mut hasher = DefaultHasher::new(); + key.hash(&mut hasher); + hasher.finish() + } fn policy() -> ComputePolicyKey { ComputePolicyKey { @@ -110,12 +174,12 @@ mod tests { let mut other = base.clone(); other.$field = $value; assert_ne!(base, other, stringify!($field)); + assert_ne!(hash(&base), hash(&other), stringify!($field)); }}; } different!(device, 9); different!(node_mask, 9); different!(flags, 9); - different!(shader, [4, 6].into()); different!(windows, 9); different!(split_wave64, true); different!(abi_schema, 9); @@ -125,6 +189,7 @@ mod tests { let mut other = base.clone(); f(&mut other.policy); assert_ne!(base, other); + assert_ne!(hash(&base), hash(&other)); }; mutate_policy(|p| p.direct = true); mutate_policy(|p| p.structured = false); @@ -136,14 +201,25 @@ mod tests { mutate_policy(|p| p.direct_piece_limit = 1); mutate_policy(|p| p.per_lane = true); mutate_policy(|p| p.disabled_dxil_optimizations = 1); + + let other = ComputeBuildKey::from_parts(1, 2, 3, [4, 6].into(), 6, false, policy()); + assert_ne!(base, other, "shader"); + assert_ne!(hash(&base), hash(&other), "shader"); + } + + #[test] + fn equal_keys_have_equal_hashes() { + assert_eq!(hash(&key()), hash(&key())); } #[test] - fn shader_identity_compares_all_bytes_not_only_a_digest() { - let mut other = key(); - other.shader = [4, 5, 0].into(); - assert_ne!(key(), other); - assert_eq!(key(), key()); + fn shader_identity_compares_all_bytes_after_a_digest_collision() { + let base = key(); + let other = ComputeBuildKey::from_parts_with_digest( + 1, 2, 3, [5, 4].into(), base.shader_digest, 6, false, policy(), + ); + assert_eq!(hash(&base), hash(&other)); + assert_ne!(base, other); } #[test] From 54a08b74f23cac298369a12af4b240d80a2006f0 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:37:52 -0800 Subject: [PATCH 024/265] Shaders: attribute pipeline cache I/O stalls Measure individual filesystem reads, writes, publishes, and cleanup operations in the DXC, translated-shader, and driver-blob caches. Keep hashing, translation, driver compilation, and memory hits outside the cache I/O scope. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/dxc.rs | 35 +++++++++++++++++++++++--- crates/xcl/src/gpu/recomp/pso.rs | 41 +++++++++++++++++++++++++++---- crates/xcl/src/hle/d3d12x/real.rs | 19 +++++++++++--- 3 files changed, 83 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 269c4d3069..61e8397a85 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -863,7 +863,11 @@ fn process_cache_lock(file: &Path) -> Result { } fn cached_file(file: &Path) -> Option> { - if let Ok(b) = std::fs::read(&file) { + let read = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::read(file) + }; + if let Ok(b) = read { if valid_dxil_container(&b) { return Some(b); } @@ -929,7 +933,10 @@ fn is_cacheable_dxc_error(raw: &str) -> bool { } fn cached_error_file(file: &Path, key: u64, src_len: usize) -> Option { - let b = std::fs::read(file).ok()?; + let b = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::read(file) + }.ok()?; let rest = b.strip_prefix(ERR_MAGIC.as_slice())?; let (k_bytes, rest) = rest.split_first_chunk::<8>()?; let (len_bytes, rest) = rest.split_first_chunk::<8>()?; @@ -959,7 +966,16 @@ fn store_error_file(file: &Path, key: u64, src_len: usize, reason: &str) { b.extend_from_slice(&(reason.len() as u32).to_le_bytes()); b.extend_from_slice(reason.as_bytes()); let tmp = file.with_extension(format!("err.tmp{}", std::process::id())); - if std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, file).is_err() { + let written = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::write(&tmp, &b).is_ok() + }; + let renamed = written && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, file).is_ok() + }; + if written && !renamed { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&tmp); } } @@ -1008,6 +1024,7 @@ where // A corrupt target must be removed before the atomic rename on Windows; // rename does not replace an existing file there. if file.is_file() { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&file); } counters.compilations.fetch_add(1, Ordering::Relaxed); @@ -1037,12 +1054,22 @@ where } }; if err_file.is_file() { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&err_file); } if std::fs::create_dir_all(&dir).is_ok() { // write to a temporary name first: another thread / process may be reading let tmp = file.with_extension(format!("tmp{}", std::process::id())); - if std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, &file).is_err() { + let written = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::write(&tmp, &b).is_ok() + }; + let renamed = written && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, &file).is_ok() + }; + if written && !renamed { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&tmp); } } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 7f0217ce0d..0fb7ef6271 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -342,7 +342,10 @@ mod translated { } pub(super) fn load_in(path: &Path, ident: u64, blob: &[u8]) -> Option { - let b = std::fs::read(path).ok()?; + let b = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::read(path) + }.ok()?; let head = header(ident, blob); let mut r = b.strip_prefix(head.as_slice())?; let u32_ = |r: &mut &[u8]| -> Option { @@ -409,9 +412,23 @@ mod translated { let Some(dir) = path.parent() else { return }; let tmp = dir.join(format!("{}.{}.{:?}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id(), std::thread::current().id())); // written whole, then renamed: a reader never sees half a file - if std::fs::create_dir_all(dir).is_ok() && std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, path).is_err() { + let written = std::fs::create_dir_all(dir).is_ok() && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::write(&tmp, &b).is_ok() + }; + let renamed = written && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, path).is_ok() + }; + if written && !renamed { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(path); - if std::fs::rename(&tmp, path).is_err() { + let retried = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, path).is_ok() + }; + if !retried { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&tmp); } } @@ -447,7 +464,10 @@ mod translated { } pub(super) fn load_err_in(path: &Path, ident: u64, blob: &[u8]) -> Option { - let b = std::fs::read(path).ok()?; + let b = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::read(path) + }.ok()?; let head = err_header(ident, blob); let rest = b.strip_prefix(head.as_slice())?; let (len_bytes, msg_bytes) = rest.split_first_chunk::<4>()?; @@ -467,7 +487,16 @@ mod translated { b.extend_from_slice(reason.as_bytes()); let Some(dir) = path.parent() else { return }; let tmp = dir.join(format!("{}.{}.{:?}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id(), std::thread::current().id())); - if std::fs::create_dir_all(dir).is_ok() && std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, path).is_err() { + let written = std::fs::create_dir_all(dir).is_ok() && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::write(&tmp, &b).is_ok() + }; + let renamed = written && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, path).is_ok() + }; + if written && !renamed { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&tmp); } } @@ -502,6 +531,7 @@ mod translated { return Err("translated cache: translator returned an invalid DXIL container".into()); } if err_path.is_file() { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&err_path); } store_in(&path, ident, blob, &c); @@ -595,6 +625,7 @@ mod translated { match translate() { Ok((c, direct)) => { if err_path.is_file() { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&err_path); } let id = if direct { rerouted } else { ident }; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index d7f177bc3a..dea5701713 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4538,6 +4538,7 @@ pub(crate) mod driver_cache { } pub fn load(p: &Path) -> Option> { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); std::fs::read(p).ok().filter(|b| !b.is_empty()) } @@ -4550,6 +4551,7 @@ pub(crate) mod driver_cache { } } else { if let Some(p) = p { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(p); } if STALE.fetch_add(1, Ordering::Relaxed) == 0 { @@ -4566,7 +4568,11 @@ pub(crate) mod driver_cache { fn create_staging_file_with(p: &Path, next: &AtomicU64) -> std::io::Result<(PathBuf, std::fs::File)> { loop { let tmp = p.with_extension(format!("tmp{}-{}", std::process::id(), next.fetch_add(1, Ordering::Relaxed))); - match std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp) { + let opened = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp) + }; + match opened { Ok(file) => return Ok((tmp, file)), // A prior process with this PID may have left a file behind. It is not ours. Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, @@ -4585,10 +4591,17 @@ pub(crate) mod driver_cache { let _ = std::fs::create_dir_all(dir); } let Ok((tmp, mut file)) = create_staging_file(p) else { return false }; - let written = file.write_all(bytes).is_ok(); + let written = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + file.write_all(bytes).is_ok() + }; drop(file); - let ok = written && std::fs::rename(&tmp, p).is_ok(); + let ok = written && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, p).is_ok() + }; if !ok { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&tmp); } ok From 5f8e0038889a011122aafaa447d3acd7c0a08e03 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:39:30 -0800 Subject: [PATCH 025/265] D3D12.X: attribute synchronous GPU waits Measure caller-blocking fence and sparse upload-slot waits, plus interprocess DXC cache mutex contention. Keep fast completion, event setup, queued GPU dependencies, background workers, and timeout diagnostics outside those scopes. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/fence.rs | 2 ++ crates/xcl/src/gpu/recomp/dxc.rs | 2 ++ crates/xcl/src/hle/d3d12x/sparse.rs | 2 ++ 3 files changed, 6 insertions(+) diff --git a/crates/xcl/src/gpu/fence.rs b/crates/xcl/src/gpu/fence.rs index 4d702802c6..37595ffe8e 100644 --- a/crates/xcl/src/gpu/fence.rs +++ b/crates/xcl/src/gpu/fence.rs @@ -73,6 +73,7 @@ pub(crate) unsafe fn wait( } let start = Instant::now(); let mut remaining = timeout_ms; + let wait_stall = crate::stall::span(crate::stall::StallKind::GpuWait); loop { let status = WaitForSingleObject(event, remaining); let error = (status == WAIT_FAILED).then(Error::from_thread); @@ -88,6 +89,7 @@ pub(crate) unsafe fn wait( } let elapsed = start.elapsed().as_millis(); if status == WAIT_TIMEOUT || elapsed >= u128::from(timeout_ms) { + drop(wait_stall); return Err(dev.GetDeviceRemovedReason().err().map_or(FenceError::Timeout(timeout_ms), FenceError::Removed)); } remaining = timeout_ms - elapsed as u32; diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 61e8397a85..62fdce8fa3 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -854,7 +854,9 @@ fn process_cache_lock(file: &Path) -> Result { if handle.is_null() { return Err("DXIL cache: cannot create the cross-process mutex".into()); } + let wait_stall = crate::stall::span(crate::stall::StallKind::LockContention); let wait = unsafe { WaitForSingleObject(handle, INFINITE) }; + drop(wait_stall); if wait != WAIT_OBJECT_0 && wait != WAIT_ABANDONED { unsafe { CloseHandle(handle) }; return Err(format!("DXIL cache: waiting for the cross-process mutex failed ({wait:#x})")); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b7560f861e..abe90f579c 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -835,7 +835,9 @@ impl State { return; } let _ = self.fence.SetEventOnCompletion(target, self.event); + let wait_stall = crate::stall::span(crate::stall::StallKind::GpuWait); windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); + drop(wait_stall); if self.fence.GetCompletedValue() < target { crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {})", self.fence.GetCompletedValue()); } From 0a42845e9e3a881ca49aa910d6e53c6d3320aecc Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:41:57 -0800 Subject: [PATCH 026/265] D3D12.X: attribute DXGI present stalls Measure only the blocking IDXGISwapChain3::Present call so removal diagnostics and post-present bookkeeping are not charged to the driver stall.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/present.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d47e67841e..aabcd2a019 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -1209,7 +1209,11 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, crate::xlog_error!("present: submit copy: {e}"); return; } - if let Err(e) = sc.Present(0, DXGI_PRESENT(0)).ok() { + let presented = { + let _stall = crate::stall::span(crate::stall::StallKind::Present); + sc.Present(0, DXGI_PRESENT(0)).ok() + }; + if let Err(e) = presented { let e = fence::api_error(&p.dev, "Present", e); p.disabled = matches!(&e, FenceError::Removed(_)); crate::xlog_error!("present: {e}"); From 56cffc2b1a33eb31ceaa9dab45f5dccf4fec6c43 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:41:57 -0800 Subject: [PATCH 027/265] D3D12.X: rank pipeline preloads by prior first use Preserve first-use order from the previous-run pipeline inventory and use it only within the preload priority band. Ranked ties and unranked jobs remain FIFO, while promotions and cancellations invalidate their old heap tickets.\n\nThe standalone build-queue test suite passed 11 tests. The Windows-only XCL crate was not built in this Linux environment.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/build_queue.rs | 106 +++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/pso_async.rs | 65 +++++++++----- 2 files changed, 141 insertions(+), 30 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/build_queue.rs b/crates/xcl/src/hle/d3d12x/build_queue.rs index 1829d29514..a7bf6d5f0f 100644 --- a/crates/xcl/src/hle/d3d12x/build_queue.rs +++ b/crates/xcl/src/hle/d3d12x/build_queue.rs @@ -5,7 +5,8 @@ #![allow(dead_code)] // Some operations are seams for the following preparation changes. -use std::collections::{HashMap, VecDeque}; +use std::cmp::Reverse; +use std::collections::{BinaryHeap, HashMap, VecDeque}; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::sync::{Arc, Condvar, Mutex, Weak}; @@ -28,7 +29,7 @@ impl Priority { } } -#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub(super) struct JobId(u64); #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -104,14 +105,23 @@ impl JobHandle { } } -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] struct Ticket { id: JobId, generation: u64, } +#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] +struct PreloadTicket { + unranked: bool, + rank: usize, + sequence: u64, + ticket: Ticket, +} + struct Job { priority: Priority, + preload_rank: Option, generation: u64, work: Work, completion: Arc, @@ -119,9 +129,35 @@ struct Job { struct State { next_id: u64, + next_sequence: u64, stopped: bool, jobs: HashMap, ready: [VecDeque; Priority::COUNT], + preload_ready: BinaryHeap>, +} + +impl State { + fn push(&mut self, priority: Priority, ticket: Ticket, preload_rank: Option) { + if priority == Priority::Preload { + self.next_sequence = self.next_sequence.checked_add(1).expect("build queue sequence overflow"); + self.preload_ready.push(Reverse(PreloadTicket { + unranked: preload_rank.is_none(), + rank: preload_rank.unwrap_or(0), + sequence: self.next_sequence, + ticket, + })); + } else { + self.ready[priority.index()].push_back(ticket); + } + } + + fn pop(&mut self, priority: Priority) -> Option { + if priority == Priority::Preload { + self.preload_ready.pop().map(|ticket| ticket.0.ticket) + } else { + self.ready[priority.index()].pop_front() + } + } } struct Inner { @@ -160,7 +196,8 @@ impl Inner { job.priority = priority; job.generation += 1; let ticket = Ticket { id, generation: job.generation }; - state.ready[priority.index()].push_back(ticket); + let preload_rank = job.preload_rank; + state.push(priority, ticket, preload_rank); self.wake(priority); true } @@ -180,9 +217,15 @@ impl Inner { let changed = self.changed(low, high); loop { for priority in (low.index()..=high.index()).rev() { - while let Some(ticket) = state.ready[priority].pop_front() { + let priority = match priority { + 0 => Priority::Speculative, + 1 => Priority::Preload, + 2 => Priority::BoundSoon, + _ => Priority::Foreground, + }; + while let Some(ticket) = state.pop(priority) { let current = state.jobs.get(&ticket.id).is_some_and(|job| { - job.priority.index() == priority && job.generation == ticket.generation + job.priority == priority && job.generation == ticket.generation }); if current { let job = state.jobs.remove(&ticket.id).unwrap(); @@ -208,6 +251,7 @@ impl Inner { for ready in &mut state.ready { ready.clear(); } + state.preload_ready.clear(); std::mem::take(&mut state.jobs) }; for (_, job) in jobs { @@ -229,9 +273,11 @@ impl BuildQueue { inner: Arc::new(Inner { state: Mutex::new(State { next_id: 0, + next_sequence: 0, stopped: false, jobs: HashMap::new(), ready: std::array::from_fn(|_| VecDeque::new()), + preload_ready: BinaryHeap::new(), }), preload_changed: Condvar::new(), foreground_changed: Condvar::new(), @@ -242,6 +288,11 @@ impl BuildQueue { /// Add work to the queue. A stopped queue refuses it without running it. pub(super) fn submit(&self, priority: Priority, work: Work) -> Option { + self.submit_ranked(priority, None, work) + } + + /// Add work, optionally ordered by an earlier-run rank within the Preload band only. + pub(super) fn submit_ranked(&self, priority: Priority, preload_rank: Option, work: Work) -> Option { let completion = Arc::new(Completion::new()); let mut state = self.inner.state.lock().unwrap_or_else(|e| e.into_inner()); if state.stopped { @@ -250,8 +301,9 @@ impl BuildQueue { state.next_id = state.next_id.checked_add(1).expect("build queue job ID overflow"); let id = JobId(state.next_id); let generation = 0; - state.jobs.insert(id, Job { priority, generation, work, completion: completion.clone() }); - state.ready[priority.index()].push_back(Ticket { id, generation }); + let preload_rank = if priority == Priority::Preload { preload_rank } else { None }; + state.jobs.insert(id, Job { priority, preload_rank, generation, work, completion: completion.clone() }); + state.push(priority, Ticket { id, generation }, preload_rank); drop(state); self.inner.wake(priority); Some(JobHandle { id, queue: Arc::downgrade(&self.inner), completion }) @@ -330,6 +382,44 @@ mod tests { assert_eq!(*out.lock().unwrap(), [4, 2, 3, 5, 1]); } + #[test] + fn preload_jobs_run_in_earlier_first_use_order() { + let q = BuildQueue::new(); + let out = Arc::new(Mutex::new(Vec::new())); + q.submit_ranked(Priority::Preload, None, record(&out, 1)).unwrap(); + q.submit_ranked(Priority::Preload, Some(20), record(&out, 2)).unwrap(); + q.submit_ranked(Priority::Preload, Some(3), record(&out, 3)).unwrap(); + while q.try_run_one_between(Priority::Preload, Priority::Preload) {} + assert_eq!(*out.lock().unwrap(), [3, 2, 1]); + } + + #[test] + fn preload_rank_ties_and_unranked_jobs_are_fifo() { + let q = BuildQueue::new(); + let out = Arc::new(Mutex::new(Vec::new())); + q.submit_ranked(Priority::Preload, None, record(&out, 1)).unwrap(); + q.submit_ranked(Priority::Preload, Some(4), record(&out, 2)).unwrap(); + q.submit_ranked(Priority::Preload, Some(4), record(&out, 3)).unwrap(); + q.submit_ranked(Priority::Preload, None, record(&out, 4)).unwrap(); + while q.try_run_one_between(Priority::Preload, Priority::Preload) {} + assert_eq!(*out.lock().unwrap(), [2, 3, 1, 4]); + } + + #[test] + fn promoted_and_cancelled_ranked_tickets_go_stale() { + let q = BuildQueue::new(); + let out = Arc::new(Mutex::new(Vec::new())); + let promoted = q.submit_ranked(Priority::Preload, Some(0), record(&out, 1)).unwrap(); + let cancelled = q.submit_ranked(Priority::Preload, Some(1), record(&out, 2)).unwrap(); + q.submit_ranked(Priority::Preload, Some(2), record(&out, 3)).unwrap(); + assert!(promoted.promote(Priority::Foreground)); + assert!(cancelled.cancel()); + assert!(q.try_run_one_between(Priority::Preload, Priority::Preload)); + assert!(!q.try_run_one_between(Priority::Preload, Priority::Preload)); + assert!(q.try_run_one_between(Priority::Foreground, Priority::Foreground)); + assert_eq!(*out.lock().unwrap(), [3, 1]); + } + #[test] fn promotion_is_monotonic_and_joins_the_new_priority_fifo() { let q = BuildQueue::new(); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index dd7db587d6..8fdbca6f03 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -470,9 +470,9 @@ fn start_preload_workers() { }); } -fn submit_job(q: &BuildQueue, build: &Arc, priority: Priority, preload: bool) -> Option { +fn submit_job(q: &BuildQueue, build: &Arc, priority: Priority, preload: bool, preload_rank: Option) -> Option { let queued_build = build.clone(); - q.submit(priority, Box::new(move || { + q.submit_ranked(priority, preload_rank, Box::new(move || { let on_preload_worker = PRELOAD_WORKER.get(); let built = build_queued(&queued_build); if built && preload && on_preload_worker { @@ -488,10 +488,10 @@ fn submit_job(q: &BuildQueue, build: &Arc, priority: Priority, preload: b #[cfg(test)] fn enqueue_on(q: &BuildQueue, build: &Arc, priority: Priority, preload: bool) { - *build.queued.lock().unwrap() = submit_job(q, build, priority, preload); + *build.queued.lock().unwrap() = submit_job(q, build, priority, preload, None); } -fn schedule(build: &Arc, priority: Priority, preload: bool) { +fn schedule(build: &Arc, priority: Priority, preload: bool, preload_rank: Option) { if preload { start_preload_workers(); } else { @@ -507,7 +507,7 @@ fn schedule(build: &Arc, priority: Priority, preload: bool) { } else { priority }; - *queued = submit_job(queue(), build, priority, preload); + *queued = submit_job(queue(), build, priority, preload, preload_rank); } } @@ -652,9 +652,9 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, comp crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); }); if send { - schedule(&build, Priority::BoundSoon, false); - } else if used::known(key) && preload_enabled() { - schedule(&build, Priority::Preload, true); + schedule(&build, Priority::BoundSoon, false, None); + } else if let Some(rank) = used::rank(key).filter(|_| preload_enabled()) { + schedule(&build, Priority::Preload, true, Some(rank)); } } @@ -674,18 +674,28 @@ pub fn earlier_used_keys() -> std::collections::HashSet { /// instead of waiting for its pipeline, ~2 170 dispatches were skipped in those frames without /// this and 94 – 150 with it. mod used { - use std::collections::HashSet; + use std::collections::{HashMap, HashSet}; use std::io::Write; use std::sync::{Mutex, OnceLock, RwLock}; struct Used { - earlier: RwLock>, + earlier: RwLock>, now: Mutex<(HashSet, Option)>, } /// The keys in a `used-pipelines.txt` (lines that are not a hexadecimal key are passed over). pub fn parse(text: &str) -> HashSet { - text.lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).filter(|&k| k != 0).collect() + parse_ranked(text).into_keys().collect() + } + + /// First occurrence order of the valid, nonzero keys in a `used-pipelines.txt`. + pub fn parse_ranked(text: &str) -> HashMap { + let mut ranked = HashMap::new(); + for key in text.lines().filter_map(|line| u64::from_str_radix(line.trim(), 16).ok()).filter(|&key| key != 0) { + let rank = ranked.len(); + ranked.entry(key).or_insert(rank); + } + ranked } fn get() -> &'static Used { @@ -693,10 +703,10 @@ mod used { U.get_or_init(|| { // (a test neither reads nor writes the user's file) if cfg!(test) { - return Used { earlier: RwLock::new(HashSet::new()), now: Mutex::new((HashSet::new(), None)) }; + return Used { earlier: RwLock::new(HashMap::new()), now: Mutex::new((HashSet::new(), None)) }; } let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); - let earlier = parse(&std::fs::read_to_string(&path).unwrap_or_default()); + let earlier = parse_ranked(&std::fs::read_to_string(&path).unwrap_or_default()); if !earlier.is_empty() { crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); } @@ -704,13 +714,13 @@ mod used { let _ = std::fs::create_dir_all(dir); } let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok(); - Used { now: Mutex::new((earlier.clone(), file)), earlier: RwLock::new(earlier) } + Used { now: Mutex::new((earlier.keys().copied().collect(), file)), earlier: RwLock::new(earlier) } }) } - /// An earlier run used a pipeline of these shaders. - pub fn known(key: u64) -> bool { - key != 0 && get().earlier.read().unwrap().contains(&key) + /// First-use rank when an earlier run used a pipeline of these shaders. + pub fn rank(key: u64) -> Option { + (key != 0).then(|| get().earlier.read().unwrap().get(&key).copied()).flatten() } /// A pipeline of these shaders is used now: kept for the next run. @@ -734,7 +744,9 @@ mod used { #[cfg(test)] pub fn earlier_run_used(key: u64) { - get().earlier.write().unwrap().insert(key); + let mut earlier = get().earlier.write().unwrap(); + let rank = earlier.len(); + earlier.entry(key).or_insert(rank); } } @@ -1159,6 +1171,15 @@ mod used_tests { assert!(keys.contains(&0xff) && keys.contains(&0x1a2b)); } + #[test] + fn used_file_ranks_follow_unique_valid_first_occurrences() { + let ranks = used::parse_ranked("10\nnot a key\n10\n0\n 20 \ninvalid\n30\n20\n"); + assert_eq!(ranks.len(), 3); + assert_eq!(ranks.get(&0x10), Some(&0)); + assert_eq!(ranks.get(&0x20), Some(&1)); + assert_eq!(ranks.get(&0x30), Some(&2)); + } + /// A lazy pipeline of shaders an earlier run used is built without a bind; another one is /// built only at its first use, and that use is kept for the next run. #[test] @@ -1427,7 +1448,7 @@ pub fn resolve(pso: usize) -> usize { 0 => { // a lazy one is wanted now: to the workers let stand = p.stand(pso); - schedule(&p.build, Priority::BoundSoon, false); + schedule(&p.build, Priority::BoundSoon, false, None); p.build.promote(Priority::Foreground); stand } @@ -1491,7 +1512,7 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> if *p.build.done.lock().unwrap() { return built(p); } - schedule(&p.build, Priority::BoundSoon, false); + schedule(&p.build, Priority::BoundSoon, false, None); if p.late.load(Ordering::Acquire) { return p.stand(pso); } @@ -1537,7 +1558,7 @@ pub fn image_only(standin: usize) { fn resolve_spared(p: &Arc, pso: usize) -> usize { match p.build.real.load(Ordering::Acquire) { 0 => { - schedule(&p.build, Priority::BoundSoon, false); + schedule(&p.build, Priority::BoundSoon, false, None); if !*p.build.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); @@ -1602,7 +1623,7 @@ pub fn want(pso: usize) { pub fn need_by_submit(pso: usize) { let Some(p) = entry(pso) else { return }; if !std::mem::replace(&mut p.build.demand.lock().unwrap().by_submit, true) { - schedule(&p.build, Priority::BoundSoon, false); + schedule(&p.build, Priority::BoundSoon, false, None); p.build.promote(Priority::Foreground); } } From 617b493d83043c2833c133574436abd92ea9ca7e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:42:34 -0800 Subject: [PATCH 028/265] D3D12.X: make command-list splits fail closed Preflight a closed standby and all split bookkeeping before committing the producer. Close the producer before resetting the continuation onto its allocator, and route failures through a closed standby while permanently quarantining lists whose Close failed.\n\nThe Windows-only XCL crate was not built in this Linux environment.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 30 +++- crates/xcl/src/hle/d3d12x/list_x.rs | 228 ++++++++++++++++-------- crates/xcl/src/hle/d3d12x/title_list.rs | 136 +++++++++++++- 3 files changed, 312 insertions(+), 82 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3f31c48b43..20d541668e 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -100,14 +100,30 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { }); } -/// Carry bound pipeline and root-signature / root-argument state from `from` to `to` across a -/// deferred mid-list split (`to` records into `allocator` with its own fresh UMA arena while -/// `from` retains its previously allocated blocks until `allocator` resets). -pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { +/// Allocation-bearing root state captured before a mid-list split commits. +pub(super) struct PreparedSplit { + to: usize, + allocator: usize, + layout: Option>, + args: Vec, + layout_gfx: Option>, + args_gfx: Vec, + rs_gfx: usize, + pso: usize, +} + +pub(super) fn prepare_split(from: *mut c_void, to: *mut c_void, allocator: usize) -> PreparedSplit { let (layout, args, layout_gfx, args_gfx, rs_gfx, pso) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso) }); - let (old, blocks) = with(to, |s| { + with(to, |_| ()); + PreparedSplit { to: to as usize, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso } +} + +/// Install a preflighted split state without cloning or growing the state map. +pub(super) fn install_prepared_split(prepared: PreparedSplit) { + let PreparedSplit { to, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso } = prepared; + let (old, blocks) = with(to as *mut c_void, |s| { let old = std::mem::replace(&mut s.allocator, allocator); s.arena = Default::default(); s.layout = layout; @@ -121,6 +137,10 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u console_list::hold_until_reset(old, blocks); } +pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { + install_prepared_split(prepare_split(from, to, allocator)); +} + /// A submit is about to wait for the pipeline `this` has bound. pub(super) fn want_bound(this: *mut c_void) { super::pso_async::want(with(this, |s| s.pso)); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 09cfdf76fd..c59f3e7fd8 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -876,11 +876,13 @@ struct SplitCarry { } impl SplitCarry { - fn take(state: &mut ListState) -> Option { + fn capture(state: &ListState) -> Option { if state.allocator == 0 { return None; } - let active_query = state.occlusion.end_active_early(); + let active_query = state.occlusion.active.map(|(q, ty, _)| (q, ty)); + let mut ended_early = state.occlusion.ended_early.clone(); + ended_early.extend(active_query.map(|(q, _)| q)); Some(Self { allocator: state.allocator, last_queue: state.last_queue, @@ -890,9 +892,9 @@ impl SplitCarry { depth_bounds: state.depth_bounds, predication: state.predication, pred_buf: state.pred_buf.clone(), - pred_in_state: std::mem::replace(&mut state.pred_in_state, false), + pred_in_state: state.pred_in_state, active_query, - ended_early: std::mem::take(&mut state.occlusion.ended_early), + ended_early, written_ranges: state.written_ranges.clone(), bindings: state.bindings.clone(), }) @@ -919,6 +921,12 @@ impl SplitCarry { ..Default::default() } } + + fn commit_state(&self, state: &mut ListState) { + state.occlusion.end_active_early(); + state.pred_in_state = false; + } + } #[derive(Clone, Copy)] @@ -3069,28 +3077,25 @@ unsafe fn reset_own_alloc(list: *mut c_void) { /// Ends `list`'s segment and opens the next, carrying its recording state across the boundary. pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) -> Option<*mut c_void> { let wrapper = super::title_list::wrapper_of(list)?; - if !super::title_list::can_split(wrapper, reason.extra_segments()) { - return None; - } let ty = list_type(list); if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { return None; } - let deferred = match reason { + let extra_segments = reason.extra_segments(); + let deferred_what = match reason { SegmentReason::DeferredDispatch(what) => { // (a predicated call stays in its list) let plain = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.allocator != 0 && s.predication.is_none()); if !plain { return None; } - Some((what, deferred_segment(wrapper, list, ty)?)) + Some(what) } SegmentReason::WaitAfterWrite64 | SegmentReason::WaitAfterCpuWrite => None, }; let carry = { - let mut g = LISTS.lock().unwrap(); - let s = g.as_mut()?.get_mut(&(list as usize))?; - SplitCarry::take(s)? + let g = LISTS.lock().unwrap(); + SplitCarry::capture(g.as_ref()?.get(&(list as usize))?)? }; let alloc = carry.allocator; let bound_pso = carry.bound_pso; @@ -3101,6 +3106,49 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - let pred_buf = &carry.pred_buf; let bindings = &carry.bindings; + let init_pso = if ty == D3D12_COMMAND_LIST_TYPE_COPY { + 0 + } else { + super::pso_async::resolve(bound_pso) + }; + let dev = device_of(list)?; + let dev_raw = dev.as_raw() as usize; + if !super::title_list::prepare_split(wrapper, extra_segments) { + return None; + } + { + let mut g = LISTS.lock().unwrap(); + if g.get_or_insert_with(HashMap::new).try_reserve(extra_segments).is_err() { + return None; + } + } + let next_pc = reserve_closed_segment(wrapper, &dev, ty)?; + let deferred = if let Some(what) = deferred_what { + match prepare_deferred_segment(wrapper, list, ty) { + Some(seg) => Some((seg, ListState { + list_type: Some(ty), + bindings: Bindings { heaps: bindings.heaps.clone(), ..Default::default() }, + deferred: Some(what), + ..Default::default() + })), + None => { + super::title_list::put_spare(wrapper, next_pc); + return None; + } + } + } else { + None + }; + let continuation_state = carry.continuation_state(ty); + let next_bindings = super::bind::prepare_split(list, next_pc, alloc); + let deferred_bindings = deferred.as_ref().map(|(seg, _)| super::bind::prepare_split(list, *seg, alloc)); + + // Commit starts here: all allocation is complete and the continuation exists closed. + { + let mut g = LISTS.lock().unwrap(); + let s = g.as_mut()?.get_mut(&(list as usize))?; + carry.commit_state(s); + } if let Some(((h, i), qty)) = carry.active_query { pc::(list, PC_END_QUERY)(list, h, qty, i); } @@ -3114,42 +3162,23 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - let close_hr = pc:: i32>(list, PC_CLOSE)(list); real::preserve_vtable(list, ext); if close_hr < 0 { + super::title_list::fail_closed(wrapper, list, next_pc, true); + if let Some((seg, _)) = deferred { + super::title_list::put_spare(wrapper, seg); + } static CLOSE_ERR: AtomicU64 = AtomicU64::new(0); warn(&CLOSE_ERR, "mid-list split", format_args!("Close failed ({close_hr:#x})")); return None; } - - let init_pso = if ty == D3D12_COMMAND_LIST_TYPE_COPY { - 0 - } 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); + if !reset_reserved_segment(next_pc, alloc, ty, init_pso) { + super::title_list::fail_closed(wrapper, list, next_pc, false); + if let Some((seg, _)) = deferred { + super::title_list::put_spare(wrapper, seg); } + static RESET_ERR: AtomicU64 = AtomicU64::new(0); + warn(&RESET_ERR, "mid-list split", format_args!("continuation Reset failed")); + return None; } - 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) { - Some(p) => p, - None => { - static CREATE_ERR: AtomicU64 = AtomicU64::new(0); - warn(&CREATE_ERR, "mid-list split", format_args!("CreateCommandList failed")); - return None; - } - }, - }; // the next segment is a recording of its own (reset or made here, not through `cl_reset`) super::dred::reset(next_pc); @@ -3171,13 +3200,13 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - } m.insert( next_pc as usize, - carry.continuation_state(ty), + continuation_state, ); old }; drop(old_next); super::title_textures::list_reset(next_pc as usize); - super::bind::inherit_for_split(list, next_pc, alloc); + super::bind::install_prepared_split(next_bindings); restore_bindings(next_pc, bindings, ty); if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { @@ -3227,29 +3256,70 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - } } - if let Some((what, seg)) = deferred { + if let Some((seg, state)) = deferred { { let mut g = LISTS.lock().unwrap(); - let s = g.get_or_insert_with(HashMap::new).entry(seg as usize).or_default(); - s.list_type = Some(ty); - s.bindings.heaps = bindings.heaps.clone(); - s.deferred = Some(what); + g.get_or_insert_with(HashMap::new).insert(seg as usize, state); } - super::bind::inherit_for_split(list, seg, alloc); + super::bind::install_prepared_split(deferred_bindings.unwrap()); super::bind::pass_arena(list, next_pc); + super::title_list::push_segment(wrapper, seg); } super::title_list::activate_segment(wrapper, list, next_pc); Some(next_pc) } -/// A closed, empty segment of `wrapper`'s recording for a dispatch recorded at the submit, on the wrapper's own allocator. -unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { +/// Reserve a known-closed continuation without associating the producer's live allocator with a +/// second recording list. A new object is opened on a private allocator and immediately closed. +unsafe fn reserve_closed_segment( + wrapper: *mut c_void, + dev: &ID3D12Device, + ty: D3D12_COMMAND_LIST_TYPE, +) -> Option<*mut c_void> { + if let Some(spare) = super::title_list::pop_spare(wrapper) { + clear_segment_state(spare as usize); + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(spare as usize).or_default().list_type = Some(ty); + return Some(spare); + } + let temp: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).ok()?; + if !real::is_adopted(temp.as_raw()) { + real::adopt(temp.as_raw(), real::Kind::CommandAllocator); + } + let made = real::create_raw_pc_command_list(dev.as_raw(), ty, temp.as_raw() as usize, 0)?; + let ext = *(made as *const usize); + let hr = pc:: i32>(made, PC_CLOSE)(made); + real::preserve_vtable(made, ext); + if hr >= 0 { + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(made as usize).or_default().list_type = Some(ty); + Some(made) + } else { + pc:: u32>(made, 2)(made); + None + } +} + +unsafe fn reset_reserved_segment(list: *mut c_void, alloc: usize, ty: D3D12_COMMAND_LIST_TYPE, init_pso: usize) -> bool { + let ext = *(list as *const usize); + let hr = super::alloc_pool::reset_list(list as usize, alloc, ty.0, |pc_alloc| { + pc:: i32>(list, PC_RESET)(list, pc_alloc, init_pso) + }); + real::preserve_vtable(list, ext); + if hr >= 0 { + reset_copy_scratch(list); + true + } else { + false + } +} + +/// Prepare a closed, empty dispatch segment without publishing it into the recording. +unsafe fn prepare_deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { let dev = device_of(list)?; let mut segs = Vec::new(); super::title_list::push_segments(wrapper, &mut segs); let first = *segs.first()? as usize; let own = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&first)?.own_alloc.clone()); - let own = match own { + let _own = match own { Some(a) => a, None => { let a: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).ok()?; @@ -3260,23 +3330,7 @@ unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_CO a } }; - let own = own.as_raw() as usize; - let emptied = |p: &*mut c_void| { - let p = *p; - let ext = *(p as *const usize); - let hr = super::alloc_pool::reset_list(p as usize, own, ty.0, |pc_alloc| pc:: i32>(p, PC_RESET)(p, pc_alloc, 0)); - real::preserve_vtable(p, ext); - hr >= 0 - }; - let p = match super::title_list::pop_spare(wrapper).filter(emptied) { - Some(p) => p, - None => real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(own), 0)?, - }; - let ext = *(p as *const usize); - pc:: i32>(p, PC_CLOSE)(p); - real::preserve_vtable(p, ext); - super::title_list::push_segment(wrapper, p); - Some(p) + reserve_closed_segment(wrapper, &dev, ty) } /// Record a `Wait32BitValueX` or `Wait64BitValueX` memory wait on `list`. @@ -5563,6 +5617,32 @@ mod tests { assert_eq!(SegmentReason::DeferredDispatch(Deferred::Dispatch(1, 2, 3)).extra_segments(), 2); } + #[test] + fn failed_split_preflight_does_not_consume_recording_state() { + let query = (0x7000, 2); + let mut state = ListState { pred_in_state: true, ..Default::default() }; + assert!(state.occlusion.begin(query, D3D12_QUERY_TYPE_OCCLUSION).is_none()); + assert!(SplitCarry::capture(&state).is_none()); + assert!(state.pred_in_state); + assert!(state.occlusion.active.is_some()); + assert!(state.occlusion.ended_early.is_empty()); + } + + #[test] + fn close_failure_keeps_effects_and_query_bookkeeping_on_the_producer() { + let query = (0x7100, 3); + let wait = PendingWait { va: 0xd440, width: 8, comparison: 7, value: 5, mask: u64::MAX, after_write64: false }; + let mut state = ListState { allocator: 0xa110, pending_waits: vec![wait], ..Default::default() }; + state.written_ranges.insert(WriteProducer::CpuAfterSegment, 0x3000, 8); + assert!(state.occlusion.begin(query, D3D12_QUERY_TYPE_OCCLUSION).is_none()); + let carry = SplitCarry::capture(&state).unwrap(); + carry.commit_state(&mut state); + assert!(state.occlusion.active.is_none()); + assert_eq!(state.occlusion.ended_early, vec![query]); + assert_eq!(state.pending_waits.len(), 1); + assert!(state.written_ranges.overlaps(WriteProducer::CpuAfterSegment, 0x3000, 8)); + } + #[test] fn split_carry_recreates_the_continuation_state() { let query = (0x7100, 3); @@ -5590,13 +5670,17 @@ mod tests { state.occlusion.ended_early.push(earlier_query); assert!(state.occlusion.begin(query, D3D12_QUERY_TYPE_OCCLUSION).is_none()); - let carry = SplitCarry::take(&mut state).unwrap(); + let carry = SplitCarry::capture(&state).unwrap(); + assert!(state.pred_in_state && state.occlusion.active.is_some(), "preflight must not mutate the producer"); + assert_eq!(state.occlusion.ended_early, vec![earlier_query]); + carry.commit_state(&mut state); + assert!(!state.pred_in_state && state.occlusion.active.is_none()); + assert_eq!(state.occlusion.ended_early, vec![earlier_query, query]); state.bindings.heaps.clear(); state.written_ranges.clear(); let continued = carry.continuation_state(D3D12_COMMAND_LIST_TYPE_DIRECT); assert_eq!(carry.active_query, Some((query, D3D12_QUERY_TYPE_OCCLUSION))); - assert!(!state.pred_in_state && state.occlusion.active.is_none() && state.occlusion.ended_early.is_empty()); assert_eq!(continued.allocator, 0xa110); assert_eq!(continued.last_queue, Some(0x9000)); assert_eq!(continued.bound_pso, 0xb220); diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 10d6ba52f2..6182378aa7 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -50,6 +50,12 @@ struct SegmentBook { /// 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. first: Option, + /// Closed object that receives calls after an unrecoverable split failure, until Reset. + failed: Option, + /// The identity-bearing primary returned a failed Close and can never be Reset again. + primary_broken: bool, + /// Non-primary lists whose failed Close permanently forbids Reset/reuse. + unresettable: Vec, } /// Wrapper address -> split segment book (populated lazily only for lists that split). @@ -154,13 +160,28 @@ unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { 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 (failed, primary_broken, first) = SEGMENTS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(this as usize))) + .map_or((None, false, None), |b| (b.failed, b.primary_broken, b.first)); + let stand_in = if let Some(failed) = failed { + (super::list_x::reset_pc(failed as *mut c_void, alloc, pso) >= 0).then_some(failed) + } else if primary_broken { + match first.filter(|&p| !super::alloc_pool::in_flight(p)) { + Some(first) => (super::list_x::reset_pc(first as *mut c_void, alloc, pso) >= 0).then_some(first), + None => super::list_x::reset_stand_in(this, primary, alloc, pso), + } + } else if adopted && super::alloc_pool::in_flight(primary as usize) { super::list_x::reset_stand_in(this, primary, alloc, pso) } else { None }; let hr = if stand_in.is_some() { 0 + } else if failed.is_some() || primary_broken { + 0x8000_4005u32 as HRESULT } else if adopted { super::list_x::reset_pc(primary, alloc, pso) } else { @@ -176,7 +197,8 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: if stand_in.is_some() || m.contains_key(&(this as usize)) { 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)); + old.extend(std::mem::replace(&mut b.first, stand_in).filter(|first| Some(*first) != stand_in)); + old.extend(b.failed.take().filter(|failed| Some(*failed) != stand_in)); b.spares.extend(old.iter().copied()); old } else { @@ -252,6 +274,10 @@ 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))); + if let Some(failed) = book.and_then(|b| b.failed) { + out.push(failed as *mut c_void); + return true; + } 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 { @@ -274,7 +300,27 @@ pub(super) fn can_split(wrapper: *mut c_void, n: usize) -> bool { let sg = SEGMENTS.lock().unwrap(); sg.as_ref() .and_then(|m| m.get(&(wrapper as usize))) - .is_none_or(|b| b.extra_active.len() + n <= MAX_EXTRA_SEGMENTS) + .is_none_or(|b| b.failed.is_none() && b.extra_active.len() + n <= MAX_EXTRA_SEGMENTS) +} + +/// Reserve every bookkeeping slot a split will publish, before its producer is closed. +pub(super) fn prepare_split(wrapper: *mut c_void, n: usize) -> bool { + let mut sg = SEGMENTS.lock().unwrap(); + let m = sg.get_or_insert_with(HashMap::new); + if m.try_reserve(1).is_err() { + return false; + } + let b = m.entry(wrapper as usize).or_default(); + if b.failed.is_some() + || b.extra_active.len() + n > MAX_EXTRA_SEGMENTS + || b.extra_active.try_reserve(n).is_err() + || b.spares.try_reserve(n).is_err() + || b.unresettable.try_reserve(1).is_err() + { + return false; + } + let mut wg = WRAPPER_OF.lock().unwrap(); + wg.get_or_insert_with(HashMap::new).try_reserve(1).is_ok() } /// Pop a previously created closed extra PC command list from `wrapper`'s spare pool for reuse @@ -314,6 +360,30 @@ pub(super) unsafe fn activate_segment(wrapper: *mut c_void, old_pc: *mut c_void, m.insert(new_pc as usize, wrapper as usize); } +/// Route a terminally failed recording to a known-closed object until the title Resets it. +pub(super) unsafe fn fail_closed(wrapper: *mut c_void, old_pc: *mut c_void, closed_pc: *mut c_void, producer_broken: bool) { + *((wrapper as usize + F_BACKING) as *mut usize) = closed_pc as usize; + let mut sg = SEGMENTS.lock().unwrap(); + let b = sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default(); + b.failed = Some(closed_pc as usize); + if producer_broken { + if old_pc as usize == *((wrapper as usize + F_PRIMARY) as *const usize) { + b.primary_broken = true; + } else { + b.extra_active.retain(|&p| p != old_pc as usize); + if b.first == Some(old_pc as usize) { + b.first = None; + } + b.unresettable.push(old_pc as usize); + } + } + drop(sg); + let mut wg = WRAPPER_OF.lock().unwrap(); + let m = wg.get_or_insert_with(HashMap::new); + m.remove(&(old_pc as usize)); + m.insert(closed_pc as usize, wrapper as usize); +} + /// For `KickoffX` on an already-split list: returns `(primary, prior_closed_segments, extra_to_reclaim)` /// when `active_pc != primary`, switches `F_BACKING` back to `primary`, and moves all extra /// segments (including `active_pc`) into `spares` so recording resumes cleanly on `primary`. @@ -322,6 +392,9 @@ pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut let wrapper = wrapper_of(active_pc)?; let mut sg = SEGMENTS.lock().unwrap(); let book = sg.as_mut().and_then(|m| m.get_mut(&(wrapper as usize)))?; + if book.failed.is_some() { + return None; + } let primary = book.first.map_or_else(|| *((wrapper as usize + F_PRIMARY) as *const *mut c_void), |f| f as *mut c_void); if primary == active_pc { return None; @@ -405,14 +478,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.failed.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.failed).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)); @@ -465,12 +538,65 @@ mod tests { } assert!(can_split(wrapper, 1)); assert!(!can_split(wrapper, 2), "a deferred dispatch needs two physical segments"); + assert!(!prepare_split(wrapper, 2)); + assert_eq!(SEGMENTS.lock().unwrap().as_ref().unwrap()[&(wrapper as usize)].extra_active.len(), MAX_EXTRA_SEGMENTS - 1); + assert!(prepare_split(wrapper, 1)); push_segment(wrapper, 0x9000usize as *mut c_void); assert!(!can_split(wrapper, 1)); assert!(can_split(wrapper, 0)); SEGMENTS.lock().unwrap().as_mut().unwrap().remove(&(wrapper as usize)); } + #[test] + fn failed_primary_routes_submission_and_calls_to_closed_standby() { + 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 primary = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + let standby = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + unsafe { + let wrapper = wrap(primary as *mut c_void); + fail_closed(wrapper, primary as *mut c_void, standby as *mut c_void, true); + assert_eq!(*((wrapper as usize + F_BACKING) as *const usize), standby as usize); + assert!(!can_split(wrapper, 1)); + let mut submitted = Vec::new(); + assert!(push_segments(wrapper, &mut submitted)); + assert_eq!(submitted, vec![standby as *mut c_void]); + { + let books = SEGMENTS.lock().unwrap(); + let book = &books.as_ref().unwrap()[&(wrapper as usize)]; + assert!(book.primary_broken); + assert_eq!(book.failed, Some(standby as usize)); + } + + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrapper as *const *const usize)).add(2)); + assert_eq!(rel(wrapper), 0); + drop(Box::from_raw(primary)); + drop(Box::from_raw(standby)); + } + } + + #[test] + fn failed_continuation_reset_keeps_the_closed_producer_reusable() { + let producer = 0x7ffe_4002usize as *mut c_void; + let standby = 0x7ffe_4003usize as *mut c_void; + let mut object = vec![0usize; OBJECT_BYTES / std::mem::size_of::()]; + let wrapper = object.as_mut_ptr() as *mut c_void; + unsafe { + *((wrapper as usize + F_PRIMARY) as *mut usize) = producer as usize; + fail_closed(wrapper, producer, standby, false); + } + let books = SEGMENTS.lock().unwrap(); + let book = &books.as_ref().unwrap()[&(wrapper as usize)]; + assert_eq!(book.failed, Some(standby as usize)); + assert!(!book.primary_broken); + assert!(book.unresettable.is_empty()); + drop(books); + SEGMENTS.lock().unwrap().as_mut().unwrap().remove(&(wrapper as usize)); + WRAPPER_OF.lock().unwrap().as_mut().unwrap().remove(&(standby as usize)); + } + /// 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() { From 9b847915ca94499fe328f483854293a5906e8443 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:46:23 -0800 Subject: [PATCH 029/265] D3D12.X: prepare prior CPU-write dependencies Accumulate exact prior CPU-after-segment write intervals once while capturing an immutable submission plan. Execution consumes the prepared per-segment dependency instead of rescanning earlier segment effects, while same-segment writes and external Kickoff waits retain their ordering semantics.\n\nThe XCL tests could not run on Linux because retour uses unsupported stdcall and fastcall ABIs.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 83 ++++++++++++++++++++++++++--- 1 file changed, 77 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index c59f3e7fd8..a784f3f1e9 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -665,6 +665,12 @@ impl RecordedWrites { fn is_empty(&self) -> bool { self.ranges.is_empty() } + + fn extend(&mut self, other: &Self) { + for (&start, &end) in &other.ranges { + self.insert(start, end - start); + } + } } /// When a recorded write becomes visible to later work. @@ -967,13 +973,15 @@ impl SegmentEffects { pub(super) struct SubmissionPlan { lists: Vec<*mut c_void>, effects: Vec, + /// Per-segment dependency on an earlier CPU-after-segment producer; empty on the no-wait fast path. + waits_after_cpu_write: Vec, has_waits: bool, } impl SubmissionPlan { fn capture(lists: &[*mut c_void]) -> Self { if lists.is_empty() { - return Self { lists: Vec::new(), effects: Vec::new(), has_waits: false }; + return Self { lists: Vec::new(), effects: Vec::new(), waits_after_cpu_write: Vec::new(), has_waits: false }; } let g = LISTS.lock().unwrap(); let effects: Vec = lists @@ -991,8 +999,22 @@ impl SubmissionPlan { .unwrap_or_default() }) .collect(); + drop(g); let has_waits = effects.iter().any(|e| !e.waits.is_empty()); - Self { lists: lists.to_vec(), effects, has_waits } + let waits_after_cpu_write = if has_waits { + let mut prior_cpu_writes = RecordedWrites::default(); + effects + .iter() + .map(|effects| { + let depends = effects.waits.iter().any(|w| prior_cpu_writes.overlaps(w.va, w.width as u64)); + prior_cpu_writes.extend(effects.write_producers.ranges(WriteProducer::CpuAfterSegment)); + depends + }) + .collect() + } else { + Vec::new() + }; + Self { lists: lists.to_vec(), effects, waits_after_cpu_write, has_waits } } fn cpu_producer_overlaps(&self, waits: &[PendingWait], before: usize) -> bool { @@ -2418,8 +2440,11 @@ pub(super) unsafe fn execute_submission_plan_with_completions( let mut completions = Vec::new(); let mut start = 0usize; for (i, effects) in plan.effects.iter().enumerate() { - let after_cpu_write = plan.cpu_producer_overlaps(&effects.waits, i); - if effects.waits.is_empty() || (!after_cpu_write && effects.waits.iter().all(|w| w.is_satisfied())) { + if effects.waits.is_empty() { + continue; + } + let after_cpu_write = plan.waits_after_cpu_write[i]; + if !after_cpu_write && effects.waits.iter().all(|w| w.is_satisfied()) { continue; } if i > start { @@ -5525,12 +5550,37 @@ mod tests { LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); } + #[test] + fn submission_plan_prepares_prior_cpu_write_dependencies() { + let lists = [0x7ffe_2401usize as *mut c_void, 0x7ffe_2402usize as *mut c_void, 0x7ffe_2403usize as *mut c_void, 0x7ffe_2404usize as *mut c_void]; + let wait = |va| PendingWait { va, width: 8, comparison: 7, value: 1, mask: u64::MAX, after_write64: false }; + let mut states: Vec = (0..4).map(|_| ListState::default()).collect(); + states[0].note_write(WriteProducer::CpuAfterSegment, 0x1000, 8); + states[1].pending_waits.push(wait(0x1000)); + states[2].note_write(WriteProducer::CpuAfterSegment, 0x2000, 8); + states[2].pending_waits.push(wait(0x2000)); + states[3].pending_waits.push(wait(0x2000)); + { + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + for (&list, state) in lists.iter().zip(states) { + m.insert(list as usize, state); + } + } + let plan = SubmissionPlan::capture(&lists); + assert_eq!(plan.waits_after_cpu_write, vec![false, true, false, true], "same-segment producers must not satisfy their own wait"); + let mut g = LISTS.lock().unwrap(); + for list in lists { + g.as_mut().unwrap().remove(&(list as usize)); + } + } + #[test] fn empty_submission_plan_uses_the_lock_free_fast_path() { let lists_guard = LISTS.lock().unwrap(); let plan = SubmissionPlan::capture(&[]); drop(lists_guard); - assert!(plan.lists.is_empty() && plan.effects.is_empty() && !plan.has_waits); + assert!(plan.lists.is_empty() && plan.effects.is_empty() && plan.waits_after_cpu_write.is_empty() && !plan.has_waits); let mut submitted = 0; unsafe { @@ -5542,6 +5592,20 @@ mod tests { assert_eq!(submitted, 1); } + #[test] + fn nonempty_no_wait_plan_loop_does_not_index_empty_dependencies() { + let list = 0x7ffe_2601usize as *mut c_void; + let mut plan = SubmissionPlan::capture(&[list]); + assert!(plan.waits_after_cpu_write.is_empty()); + // Exercise the loop independently of capture's no-wait early-return flag. + plan.has_waits = true; + let mut submitted = Vec::new(); + unsafe { + execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| submitted.push(chunk.lists().to_vec())); + } + assert_eq!(submitted, vec![vec![list]]); + } + #[test] fn cpu_producer_completion_precedes_the_continuation_wait() { let producer = 0x7ffe_2801usize as *mut c_void; @@ -5578,10 +5642,17 @@ mod tests { } assert!(plan.effects[0].producer_overlaps(WriteProducer::CpuAfterSegment, va, 8)); assert!(!plan.effects[1].producer_overlaps(WriteProducer::CpuAfterSegment, va, 8)); + assert_eq!(plan.waits_after_cpu_write, vec![false, true]); assert!(plan.chunk_needs_cpu_completion(0, 1, &[])); assert!(!plan.chunk_needs_cpu_completion(1, 2, &[])); let unrelated = PendingWait { va: va + 8, width: 8, comparison: 7, value: 1, mask: u64::MAX, after_write64: false }; - assert!(!SubmissionPlan { lists: vec![producer], effects: vec![plan.effects[0].clone()], has_waits: false }.chunk_needs_cpu_completion(0, 1, &[unrelated])); + assert!(!SubmissionPlan { + lists: vec![producer], + effects: vec![plan.effects[0].clone()], + waits_after_cpu_write: Vec::new(), + has_waits: false, + } + .chunk_needs_cpu_completion(0, 1, &[unrelated])); let completed = Arc::new(AtomicBool::new(false)); let mut chunks = Vec::new(); From 11378584b2b4cf4052a93266e07661759ebb0aa3 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:46:23 -0800 Subject: [PATCH 030/265] D3D12.X: attribute submit preparation and CPU synchronization Measure immutable submission-plan construction separately from pipeline waits, execution synchronization, and driver submission. Attribute CPU-write completion waits at the blocking receive seam without overlapping worker GPU waits.\n\nThe Windows-only XCL crate was not built in this Linux environment.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/cpu_writes.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 15ec353308..d4adeed93a 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -165,6 +165,7 @@ pub(super) struct Completion(mpsc::Receiver<()>); impl Completion { pub(super) fn wait(self) -> bool { + let _stall = crate::stall::span(crate::stall::StallKind::MemorySynchronization); self.0.recv().is_ok() } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index dea5701713..30b731ed3a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7297,12 +7297,16 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::title_textures::refresh(this); // console-shaped lists run as the PC lists they were translated into (split title lists expand // into all of their recorded PC segments in exact chronological order) + let mut preparation_stall = crate::stall::span(crate::stall::StallKind::SubmitPreparation); let mut mapped: Vec<*mut c_void> = Vec::with_capacity(n as usize); for &l in std::slice::from_raw_parts(lists, n as usize) { if let Some(pc) = super::console_list::pc_list(l) { mapped.push(pc); } else { + // Deferred recording can wait for a pipeline. Keep that time solely in PipelineWait. + drop(preparation_stall); super::list_x::record_deferred(l); + preparation_stall = crate::stall::span(crate::stall::StallKind::SubmitPreparation); if !super::title_list::push_segments(l, &mut mapped) { mapped.push(l); } @@ -7310,6 +7314,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis } super::list_x::note_queue_for_lists(this as usize, &mapped); let plan = super::list_x::submission_plan(&mapped); + drop(preparation_stall); let _ = super::list_x::execute_submission_plan_with_completions(this, &plan, &[], |chunk| { let lists = chunk.lists(); let _ = super::alloc_pool::note_resubmits(this, lists); From 7500057a2fee40f5fecf204e3dd0caf4326bc77f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:46:49 -0800 Subject: [PATCH 031/265] D3D12.X: attribute CPU fallback memory waits Measure only fallback CPU polling after the satisfied fast path and GPU-side wait handling. End the span before timeout diagnostics so synchronization time remains separate from reporting work.\n\nThe Windows-only XCL crate was not built in this Linux environment.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index c59f3e7fd8..f18e438113 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2307,7 +2307,10 @@ unsafe fn wait_all_on(queue: *mut c_void, waits: &[PendingWait], list_writes: &[ GpuWaitOutcome::Handled | GpuWaitOutcome::CycleSkip => continue, GpuWaitOutcome::FallbackCpu => {} } - if !w.wait_until_satisfied(timeout) && once(&TIMEOUTS, 40) { + let memory_stall = crate::stall::span(crate::stall::StallKind::MemorySynchronization); + let satisfied = w.wait_until_satisfied(timeout); + drop(memory_stall); + if !satisfied && once(&TIMEOUTS, 40) { let cell_diag = { let g = SYNC_GRAPH.lock().unwrap(); g.as_ref().and_then(|gr| gr.cells.get(&w.va)).map(|c| (c.recorded_max, c.submitted_max, c.non_monotonic, c.recorded_list_type.map(|t| t.0))) From 29442e13cf89d03d76f61bdcc555b04437907295 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:48:15 -0800 Subject: [PATCH 032/265] D3D12.X: report ranked pipeline preload outcomes Count accepted ranked preloads, jobs started in the preload band, and jobs promoted before preload execution. Publish the privacy-safe counters in preparation schema v2 and teach the comparator to preserve v1 while validating and comparing v2.\n\nThe standalone build-queue suite passed 11 tests. PowerShell comparator tests could not run because PowerShell is unavailable in this Linux environment.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/build_queue.rs | 56 ++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/pso_async.rs | 18 ++++++++ crates/xcl/src/report.rs | 19 +++++++- scripts/perf-compare.ps1 | 40 ++++++++++++---- scripts/perf-compare.tests.ps1 | 59 +++++++++++++++++++++--- 5 files changed, 175 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/build_queue.rs b/crates/xcl/src/hle/d3d12x/build_queue.rs index a7bf6d5f0f..fec7b62dfe 100644 --- a/crates/xcl/src/hle/d3d12x/build_queue.rs +++ b/crates/xcl/src/hle/d3d12x/build_queue.rs @@ -8,6 +8,7 @@ use std::cmp::Reverse; use std::collections::{BinaryHeap, HashMap, VecDeque}; use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, Weak}; pub(super) type Work = Box; @@ -41,6 +42,37 @@ pub(super) enum JobStatus { Panicked, } +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(super) struct RankedPreloadSnapshot { + pub(super) submissions: u64, + pub(super) started: u64, + pub(super) promoted: u64, +} + +struct RankedPreloadCounters { + submissions: AtomicU64, + started: AtomicU64, + promoted: AtomicU64, +} + +impl RankedPreloadCounters { + const fn new() -> Self { + Self { + submissions: AtomicU64::new(0), + started: AtomicU64::new(0), + promoted: AtomicU64::new(0), + } + } + + fn snapshot(&self) -> RankedPreloadSnapshot { + RankedPreloadSnapshot { + submissions: self.submissions.load(Ordering::Relaxed), + started: self.started.load(Ordering::Relaxed), + promoted: self.promoted.load(Ordering::Relaxed), + } + } +} + impl JobStatus { fn terminal(self) -> bool { matches!(self, Self::Complete | Self::Cancelled | Self::Panicked) @@ -162,6 +194,7 @@ impl State { struct Inner { state: Mutex, + ranked_preloads: RankedPreloadCounters, preload_changed: Condvar, foreground_changed: Condvar, all_changed: Condvar, @@ -193,11 +226,15 @@ impl Inner { if priority <= job.priority { return true; } + let ranked_preload = job.priority == Priority::Preload && job.preload_rank.is_some(); job.priority = priority; job.generation += 1; let ticket = Ticket { id, generation: job.generation }; let preload_rank = job.preload_rank; state.push(priority, ticket, preload_rank); + if ranked_preload { + self.ranked_preloads.promoted.fetch_add(1, Ordering::Relaxed); + } self.wake(priority); true } @@ -229,6 +266,9 @@ impl Inner { }); if current { let job = state.jobs.remove(&ticket.id).unwrap(); + if priority == Priority::Preload && job.preload_rank.is_some() { + self.ranked_preloads.started.fetch_add(1, Ordering::Relaxed); + } job.completion.set(JobStatus::Running); return Some((job.work, job.completion)); } @@ -279,6 +319,7 @@ impl BuildQueue { ready: std::array::from_fn(|_| VecDeque::new()), preload_ready: BinaryHeap::new(), }), + ranked_preloads: RankedPreloadCounters::new(), preload_changed: Condvar::new(), foreground_changed: Condvar::new(), all_changed: Condvar::new(), @@ -304,6 +345,9 @@ impl BuildQueue { let preload_rank = if priority == Priority::Preload { preload_rank } else { None }; state.jobs.insert(id, Job { priority, preload_rank, generation, work, completion: completion.clone() }); state.push(priority, Ticket { id, generation }, preload_rank); + if preload_rank.is_some() { + self.inner.ranked_preloads.submissions.fetch_add(1, Ordering::Relaxed); + } drop(state); self.inner.wake(priority); Some(JobHandle { id, queue: Arc::downgrade(&self.inner), completion }) @@ -313,6 +357,10 @@ impl BuildQueue { self.worker_between(Priority::Speculative, Priority::Foreground) } + pub(super) fn ranked_preload_stats(&self) -> RankedPreloadSnapshot { + self.inner.ranked_preloads.snapshot() + } + pub(super) fn worker_between(&self, low: Priority, high: Priority) -> Worker { Worker { inner: self.inner.clone(), low, high } } @@ -403,6 +451,10 @@ mod tests { q.submit_ranked(Priority::Preload, None, record(&out, 4)).unwrap(); while q.try_run_one_between(Priority::Preload, Priority::Preload) {} assert_eq!(*out.lock().unwrap(), [2, 3, 1, 4]); + assert_eq!( + q.ranked_preload_stats(), + RankedPreloadSnapshot { submissions: 2, started: 2, promoted: 0 }, + ); } #[test] @@ -418,6 +470,10 @@ mod tests { assert!(!q.try_run_one_between(Priority::Preload, Priority::Preload)); assert!(q.try_run_one_between(Priority::Foreground, Priority::Foreground)); assert_eq!(*out.lock().unwrap(), [3, 1]); + assert_eq!( + q.ranked_preload_stats(), + RankedPreloadSnapshot { submissions: 3, started: 1, promoted: 1 }, + ); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 8fdbca6f03..bea0044edc 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -13,6 +13,15 @@ use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock, Weak}; use super::build_queue::{BuildQueue, JobHandle, Priority}; +/// Process-lifetime ranked-preload outcomes; `started` means dequeued in the Preload band. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(default)] +pub struct RankedPreloadStats { + pub submissions: u64, + pub started: u64, + pub promoted: u64, +} + struct Pending { build: Arc, /// the driver pipeline binds get till then (`shared`); 0: the stand-in is one itself @@ -438,6 +447,15 @@ fn queue() -> &'static BuildQueue { Q.get_or_init(BuildQueue::new) } +pub fn ranked_preload_stats() -> RankedPreloadStats { + let snapshot = queue().ranked_preload_stats(); + RankedPreloadStats { + submissions: snapshot.submissions, + started: snapshot.started, + promoted: snapshot.promoted, + } +} + fn start_normal_workers() { static STARTED: std::sync::Once = std::sync::Once::new(); STARTED.call_once(|| { diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index 9d38a4dd14..3505442056 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize}; use crate::resolver::{self, Source}; pub const STALL_SUMMARY_VERSION: u32 = 1; -pub const PREPARATION_SUMMARY_VERSION: u32 = 1; +pub const PREPARATION_SUMMARY_VERSION: u32 = 2; #[derive(Debug, Serialize, Deserialize, Default)] pub struct StubCall { @@ -138,6 +138,8 @@ pub struct PreparationSummary { pub version: u32, #[serde(default)] pub compute_build_coalescing: crate::hle::d3d12x::pso_async::ComputeCoalescingStats, + #[serde(default)] + pub ranked_preloads: crate::hle::d3d12x::pso_async::RankedPreloadStats, } #[derive(Debug, Serialize, Deserialize, Default)] @@ -252,6 +254,7 @@ pub fn build() -> Report { preparation: Some(PreparationSummary { version: PREPARATION_SUMMARY_VERSION, compute_build_coalescing: crate::hle::d3d12x::pso_async::compute_coalescing_stats(), + ranked_preloads: crate::hle::d3d12x::pso_async::ranked_preload_stats(), }), d3d12: crate::hle::d3d12x::real::stats(), audio: crate::hle::xaudio2::stats(), @@ -330,6 +333,11 @@ mod tests { current_in_flight: 3, peak_in_flight: 6, }, + ranked_preloads: crate::hle::d3d12x::pso_async::RankedPreloadStats { + submissions: 19, + started: 13, + promoted: 4, + }, }; let json = serde_json::to_value(summary).unwrap(); assert_eq!(json["version"], PREPARATION_SUMMARY_VERSION); @@ -338,6 +346,15 @@ mod tests { assert_eq!(json["compute_build_coalescing"]["unique_keyed_builds"], 7); assert_eq!(json["compute_build_coalescing"]["current_in_flight"], 3); assert_eq!(json["compute_build_coalescing"]["peak_in_flight"], 6); + assert_eq!(json["ranked_preloads"]["submissions"], 19); + assert_eq!(json["ranked_preloads"]["started"], 13); + assert_eq!(json["ranked_preloads"]["promoted"], 4); + + let mut version_one = json; + version_one["version"] = 1.into(); + version_one.as_object_mut().unwrap().remove("ranked_preloads"); + let loaded: PreparationSummary = serde_json::from_value(version_one).unwrap(); + assert_eq!(loaded.ranked_preloads, Default::default()); } #[test] diff --git a/scripts/perf-compare.ps1 b/scripts/perf-compare.ps1 index e71f8a909a..c3a0b3a06f 100644 --- a/scripts/perf-compare.ps1 +++ b/scripts/perf-compare.ps1 @@ -104,17 +104,17 @@ function Read-Preparation([string]$Root, [int]$Order, [string]$Label) { $mode = $Label.Substring(4) $report = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'report.json')) if (-not (Test-Path -LiteralPath $report -PathType Leaf)) { - return [ordered]@{ status = 'missing_report'; counters = $null } + return [ordered]@{ status = 'missing_report'; counters = $null; ranked_status = 'missing_report'; ranked = $null } } $json = Read-Json $report if (-not (Has-Property $json 'preparation') -or $null -eq $json.preparation) { - return [ordered]@{ status = 'missing_preparation'; counters = $null } + return [ordered]@{ status = 'missing_preparation'; counters = $null; ranked_status = 'missing_preparation'; ranked = $null } } $summary = $json.preparation $version = Read-Nonnegative-Integer $summary 'version' 'preparation version' if ($version -eq 0) { throw "malformed preparation version in $report" } - if ($version -ne 1) { - return [ordered]@{ status = 'unsupported_version'; counters = $null } + if ($version -ne 1 -and $version -ne 2) { + return [ordered]@{ status = 'unsupported_version'; counters = $null; ranked_status = 'unsupported_version'; ranked = $null } } if (-not (Has-Property $summary 'compute_build_coalescing') -or $null -eq $summary.compute_build_coalescing) { @@ -126,7 +126,17 @@ function Read-Preparation([string]$Root, [int]$Order, [string]$Label) { 'current_in_flight', 'peak_in_flight')) { $counters[$name] = Read-Nonnegative-Integer $raw $name "preparation in $report" } - return [ordered]@{ status = 'present'; counters = $counters } + if ($version -eq 1) { + return [ordered]@{ status = 'present'; counters = $counters; ranked_status = 'not_in_version'; ranked = $null } + } + if (-not (Has-Property $summary 'ranked_preloads') -or $null -eq $summary.ranked_preloads) { + throw "malformed ranked preload counters in $report" + } + $ranked = [ordered]@{} + foreach ($name in @('submissions', 'started', 'promoted')) { + $ranked[$name] = Read-Nonnegative-Integer $summary.ranked_preloads $name "ranked preloads in $report" + } + return [ordered]@{ status = 'present'; counters = $counters; ranked_status = 'present'; ranked = $ranked } } function Number-Or-Null($Object, [string]$Name) { @@ -144,10 +154,9 @@ function Counter-Delta-Or-Null($Before, $After) { return [decimal]$After - [decimal]$Before } -function Compare-Counters($Before, $After) { +function Compare-Counters($Before, $After, [string[]]$Names) { $delta = [ordered]@{} - foreach ($name in @('keyed_submissions', 'coalescing_hits', 'unique_keyed_builds', - 'current_in_flight', 'peak_in_flight')) { + foreach ($name in $Names) { $delta[$name] = Counter-Delta-Or-Null $Before.$name $After.$name } return [ordered]@{ baseline = $Before; candidate = $After; delta = $delta } @@ -236,7 +245,9 @@ for ($i = 0; $i -lt 2; $i++) { $stalls = @(Compare-Aggregates $beforeStalls.aggregates $afterStalls.aggregates) $beforePreparation = Read-Preparation $baselineRoot ($i + 1) $beforeRun.cache_state $afterPreparation = Read-Preparation $candidateRoot ($i + 1) $afterRun.cache_state - $coalescing = Compare-Counters $beforePreparation.counters $afterPreparation.counters + $coalescingNames = @('keyed_submissions', 'coalescing_hits', 'unique_keyed_builds', 'current_in_flight', 'peak_in_flight') + $coalescing = Compare-Counters $beforePreparation.counters $afterPreparation.counters $coalescingNames + $rankedPreloads = Compare-Counters $beforePreparation.ranked $afterPreparation.ranked @('submissions', 'started', 'promoted') $comparison = [ordered]@{ label = $beforeRun.cache_state @@ -260,6 +271,11 @@ for ($i = 0; $i -lt 2; $i++) { candidate = $afterPreparation.status } compute_build_coalescing = $coalescing + ranked_preloads_status = [ordered]@{ + baseline = $beforePreparation.ranked_status + candidate = $afterPreparation.ranked_status + } + ranked_preloads = $rankedPreloads } $comparisons += $comparison @@ -278,6 +294,12 @@ for ($i = 0; $i -lt 2; $i++) { Write-Host " $($name): $(Display-Value $coalescing.baseline.$name '') -> $(Display-Value $coalescing.candidate.$name ''); delta $(Display-Value $coalescing.delta.$name '')" } } + Write-Host " ranked preloads: $($beforePreparation.ranked_status) -> $($afterPreparation.ranked_status)" + if ($beforePreparation.ranked_status -eq 'present' -or $afterPreparation.ranked_status -eq 'present') { + foreach ($name in $rankedPreloads.delta.Keys) { + Write-Host " $($name): $(Display-Value $rankedPreloads.baseline.$name '') -> $(Display-Value $rankedPreloads.candidate.$name ''); delta $(Display-Value $rankedPreloads.delta.$name '')" + } + } } [ordered]@{ diff --git a/scripts/perf-compare.tests.ps1 b/scripts/perf-compare.tests.ps1 index 046f19c2ad..eedf659ee2 100644 --- a/scripts/perf-compare.tests.ps1 +++ b/scripts/perf-compare.tests.ps1 @@ -26,7 +26,7 @@ function Write-Fixture([string]$Root, [string]$Commit, [int]$ColdMs, $WarmMs) { } function Write-Report([string]$Path, [int]$Count, [long]$Total, [long]$Maximum, - $Preparation = $null, [int]$PreparationVersion = 1, [switch]$ExtraKind) { + $Preparation = $null, [int]$PreparationVersion = 1, $RankedPreloads = $null, [switch]$ExtraKind) { $aggregates = @( [ordered]@{ kind = 'dxc_compile'; count = $Count; total_ns = $Total; max_ns = $Maximum; histogram_log2_ns = @(0, $Count) } ) @@ -39,6 +39,9 @@ function Write-Report([string]$Path, [int]$Count, [long]$Total, [long]$Maximum, version = $PreparationVersion compute_build_coalescing = $Preparation } + if ($null -ne $RankedPreloads) { + $report['preparation']['ranked_preloads'] = $RankedPreloads + } } $report | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $Path -Encoding utf8 @@ -49,8 +52,10 @@ try { Write-Fixture $candidate 'candidate-commit' 850 0 $beforePreparation = [ordered]@{ keyed_submissions = 12; coalescing_hits = 5; unique_keyed_builds = 7; current_in_flight = 0; peak_in_flight = 3 } $afterPreparation = [ordered]@{ keyed_submissions = 10; coalescing_hits = 6; unique_keyed_builds = 4; current_in_flight = 1; peak_in_flight = 5 } - Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation - Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation -ExtraKind + $beforeRanked = [ordered]@{ submissions = 20; started = 15; promoted = 3 } + $afterRanked = [ordered]@{ submissions = 24; started = 20; promoted = 2 } + Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation 2 $beforeRanked + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind [ordered]@{ d3d12 = [ordered]@{} } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $baseline 'runs\02-warm\report.json') -Encoding utf8 $json = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json @@ -74,30 +79,70 @@ try { $preparation.delta.keyed_submissions -ne -2 -or $preparation.delta.coalescing_hits -ne 1 -or $preparation.delta.unique_keyed_builds -ne -3 -or $preparation.delta.current_in_flight -ne 1 -or $preparation.delta.peak_in_flight -ne 2) { throw 'preparation counters or deltas are wrong' } + $ranked = $json.runs[0].ranked_preloads + if ($json.runs[0].ranked_preloads_status.baseline -ne 'present' -or + $json.runs[0].ranked_preloads_status.candidate -ne 'present' -or + $ranked.baseline.submissions -ne 20 -or $ranked.candidate.submissions -ne 24 -or + $ranked.baseline.started -ne 15 -or $ranked.candidate.started -ne 20 -or + $ranked.baseline.promoted -ne 3 -or $ranked.candidate.promoted -ne 2 -or + $ranked.delta.submissions -ne 4 -or $ranked.delta.started -ne 5 -or + $ranked.delta.promoted -ne -1) { throw 'ranked preload counters, status, or deltas are wrong' } if ($json.runs[1].preparation_status.baseline -ne 'missing_preparation' -or $json.runs[1].preparation_status.candidate -ne 'missing_report' -or - $null -ne $json.runs[1].compute_build_coalescing.delta.keyed_submissions) { + $null -ne $json.runs[1].compute_build_coalescing.delta.keyed_submissions -or + $json.runs[1].ranked_preloads_status.baseline -ne 'missing_preparation' -or + $json.runs[1].ranked_preloads_status.candidate -ne 'missing_report' -or + $null -ne $json.runs[1].ranked_preloads.delta.submissions) { throw 'missing preparation data was treated as zero' } if (($json | ConvertTo-Json -Depth 12) -match '"(percent|percentage|ratio|significance|significant)"\s*:') { throw 'output invented a derived significance metric' } - Write-Report (Join-Path $candidate 'runs\02-warm\report.json') 1 1 1 $afterPreparation 2 + Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation -ExtraKind + $versionOne = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json + if ($versionOne.runs[0].preparation_status.baseline -ne 'present' -or + $versionOne.runs[0].compute_build_coalescing.candidate.coalescing_hits -ne 6 -or + $versionOne.runs[0].ranked_preloads_status.baseline -ne 'not_in_version' -or + $versionOne.runs[0].ranked_preloads_status.candidate -ne 'not_in_version' -or + $null -ne $versionOne.runs[0].ranked_preloads.delta.started) { + throw 'version 1 preparation support regressed' + } + Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation 2 $beforeRanked + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind + + Write-Report (Join-Path $candidate 'runs\02-warm\report.json') 1 1 1 $afterPreparation 3 $unsupported = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json if ($unsupported.runs[1].preparation_status.candidate -ne 'unsupported_version' -or - $null -ne $unsupported.runs[1].compute_build_coalescing.candidate) { + $unsupported.runs[1].ranked_preloads_status.candidate -ne 'unsupported_version' -or + $null -ne $unsupported.runs[1].compute_build_coalescing.candidate -or + $null -ne $unsupported.runs[1].ranked_preloads.candidate) { throw 'unsupported preparation version was not preserved as a state' } $badReportPath = Join-Path $candidate 'runs\01-cold\report.json' + Write-Report $badReportPath 3 80 40 $afterPreparation 2 -ExtraKind + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed ranked preload' } + if (-not $refused) { throw 'missing version 2 ranked preload counters were not refused' } + + Write-Report $badReportPath 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind + $badReport = Get-Content -LiteralPath $badReportPath -Raw -Encoding utf8 | ConvertFrom-Json + $badReport.preparation.ranked_preloads.promoted = -1 + $badReport | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $badReportPath -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed ranked preloads' } + if (-not $refused) { throw 'a malformed ranked preload counter was not refused' } + + Write-Report $badReportPath 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind $badReport = Get-Content -LiteralPath $badReportPath -Raw -Encoding utf8 | ConvertFrom-Json $badReport.preparation.compute_build_coalescing.coalescing_hits = -1 $badReport | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $badReportPath -Encoding utf8 $refused = $false try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed preparation' } if (-not $refused) { throw 'a malformed preparation counter was not refused' } - Write-Report $badReportPath 3 80 40 $afterPreparation -ExtraKind + Write-Report $badReportPath 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json $candidateManifest.workload_id = 'other-workload' From 03e4d27d3e191f1b9b1c20b93d4a1e823859a958 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:49:31 -0800 Subject: [PATCH 033/265] D3D12.X: harden fail-closed list recovery Normalize reserved closed standbys to allocator-unknown, effect-empty state so forwarded Kickoff calls cannot treat stale state as recordable. During Reset recovery, replace an in-flight failed standby instead of immediately reusing the same PC list object.\n\nFocused XCL tests could not run on Linux because retour uses unsupported stdcall and fastcall ABIs.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 38 +++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/title_list.rs | 32 ++++++++++++++++++++- 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index a784f3f1e9..03def4854b 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3302,8 +3302,7 @@ unsafe fn reserve_closed_segment( ty: D3D12_COMMAND_LIST_TYPE, ) -> Option<*mut c_void> { if let Some(spare) = super::title_list::pop_spare(wrapper) { - clear_segment_state(spare as usize); - LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(spare as usize).or_default().list_type = Some(ty); + note_reserved_closed(spare as usize, ty); return Some(spare); } let temp: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).ok()?; @@ -3315,7 +3314,7 @@ unsafe fn reserve_closed_segment( let hr = pc:: i32>(made, PC_CLOSE)(made); real::preserve_vtable(made, ext); if hr >= 0 { - LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(made as usize).or_default().list_type = Some(ty); + note_reserved_closed(made as usize, ty); Some(made) } else { pc:: u32>(made, 2)(made); @@ -3323,6 +3322,15 @@ unsafe fn reserve_closed_segment( } } +/// A closed standby must not look recordable if its Reset as the continuation later fails. +fn note_reserved_closed(list: usize, ty: D3D12_COMMAND_LIST_TYPE) { + clear_segment_state(list); + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(list).or_default(); + s.allocator = 0; + s.list_type = Some(ty); +} + unsafe fn reset_reserved_segment(list: *mut c_void, alloc: usize, ty: D3D12_COMMAND_LIST_TYPE, init_pso: usize) -> bool { let ext = *(list as *const usize); let hr = super::alloc_pool::reset_list(list as usize, alloc, ty.0, |pc_alloc| { @@ -5699,6 +5707,30 @@ mod tests { assert!(state.occlusion.ended_early.is_empty()); } + #[test] + fn reserved_closed_standby_cannot_kickoff_stale_recording_state() { + let list = 0x7ffe_2a01usize; + let wait = PendingWait { va: 0x4000, width: 8, comparison: 7, value: 1, mask: u64::MAX, after_write64: false }; + let mut state = ListState { + allocator: 0xa110, + list_type: Some(D3D12_COMMAND_LIST_TYPE_COMPUTE), + pending_waits: vec![wait], + cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x5000, vec![1])], + ..Default::default() + }; + state.segment_write_producers.insert(WriteProducer::CpuAfterSegment, 0x5000, 4); + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(list, state); + + note_reserved_closed(list, D3D12_COMMAND_LIST_TYPE_DIRECT); + + let mut g = LISTS.lock().unwrap(); + let state = &g.as_ref().unwrap()[&list]; + assert_eq!(state.allocator, 0, "KickoffX must take its allocator-unknown no-op path"); + assert_eq!(state.list_type, Some(D3D12_COMMAND_LIST_TYPE_DIRECT)); + assert!(state.pending_waits.is_empty() && state.cpu_writes.is_empty() && state.segment_write_producers.is_empty()); + g.as_mut().unwrap().remove(&list); + } + #[test] fn close_failure_keeps_effects_and_query_bookkeeping_on_the_producer() { let query = (0x7100, 3); diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 6182378aa7..0143f87caa 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -151,6 +151,10 @@ unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { hr } +fn recover_failed_with(failed: usize, in_flight: bool, reuse: impl FnOnce(usize) -> Option, replace: impl FnOnce() -> Option) -> Option { + if in_flight { replace() } else { reuse(failed) } +} + /// #10 Reset(allocator, initial_pso): resets the primary PC list (`F_PRIMARY`) via `list_x::reset_pc` /// (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 @@ -167,7 +171,12 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: .and_then(|m| m.get(&(this as usize))) .map_or((None, false, None), |b| (b.failed, b.primary_broken, b.first)); let stand_in = if let Some(failed) = failed { - (super::list_x::reset_pc(failed as *mut c_void, alloc, pso) >= 0).then_some(failed) + recover_failed_with( + failed, + super::alloc_pool::in_flight(failed), + |failed| (super::list_x::reset_pc(failed as *mut c_void, alloc, pso) >= 0).then_some(failed), + || super::list_x::reset_stand_in(this, primary, alloc, pso), + ) } else if primary_broken { match first.filter(|&p| !super::alloc_pool::in_flight(p)) { Some(first) => (super::list_x::reset_pc(first as *mut c_void, alloc, pso) >= 0).then_some(first), @@ -597,6 +606,27 @@ mod tests { WRAPPER_OF.lock().unwrap().as_mut().unwrap().remove(&(standby as usize)); } + #[test] + fn in_flight_failed_standby_is_replaced_instead_of_reused() { + use std::cell::Cell; + let reused = Cell::new(false); + let replaced = Cell::new(false); + let selected = recover_failed_with( + 0x7100, + true, + |_| { + reused.set(true); + Some(0x7100) + }, + || { + replaced.set(true); + Some(0x7200) + }, + ); + assert_eq!(selected, Some(0x7200)); + assert!(!reused.get() && replaced.get()); + } + /// 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() { From ab9f48cea818cd2ea3408f15f4a6107d784431de Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:49:40 -0800 Subject: [PATCH 034/265] D3D12.X: attribute residency driver calls Measure the exact original MakeResident, Evict, SetResidencyPriority, and EnqueueMakeResident calls. Fence waiting, submission preparation, and DirectStorage remain in their own attribution categories.\n\nThe Windows-target check stopped before XCL compilation because this Linux host lacks MSVC headers.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 39 +++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 30b731ed3a..49693bd907 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2852,6 +2852,41 @@ unsafe extern "system" fn dev_create_compute_pso_x(this: *mut c_void, desc: *con hr } +unsafe extern "system" fn dev_make_resident(this: *mut c_void, n: u32, objects: *const *mut c_void) -> HRESULT { + type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "MakeResident"))); + let _stall = crate::stall::span(crate::stall::StallKind::Residency); + f(this, n, objects) +} + +unsafe extern "system" fn dev_evict(this: *mut c_void, n: u32, objects: *const *mut c_void) -> HRESULT { + type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "Evict"))); + let _stall = crate::stall::span(crate::stall::StallKind::Residency); + f(this, n, objects) +} + +unsafe extern "system" fn dev_set_residency_priority(this: *mut c_void, n: u32, objects: *const *mut c_void, priorities: *const D3D12_RESIDENCY_PRIORITY) -> HRESULT { + type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void, *const D3D12_RESIDENCY_PRIORITY) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetResidencyPriority"))); + let _stall = crate::stall::span(crate::stall::StallKind::Residency); + f(this, n, objects, priorities) +} + +unsafe extern "system" fn dev_enqueue_make_resident( + this: *mut c_void, + flags: D3D12_RESIDENCY_FLAGS, + n: u32, + objects: *const *mut c_void, + fence: *mut c_void, + value: u64, +) -> HRESULT { + type F = unsafe extern "system" fn(*mut c_void, D3D12_RESIDENCY_FLAGS, u32, *const *mut c_void, *mut c_void, u64) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "EnqueueMakeResident"))); + let _stall = crate::stall::span(crate::stall::StallKind::Residency); + f(this, flags, n, objects, fence, value) +} + fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { let mut v: Vec<(&'static str, usize)> = vec![("QueryInterface", qi_override as usize)]; match kind { @@ -2869,11 +2904,15 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("CreateHeap", dev_create_heap as usize), ("CreatePlacedResource", dev_create_placed_resource as usize), ("CreateReservedResource", dev_create_reserved_resource as usize), + ("MakeResident", dev_make_resident as usize), + ("Evict", dev_evict as usize), ("CreateFence", dev_create_fence as usize), ("CreateQueryHeap", dev_create_query_heap as usize), ("CreateCommandSignature", dev_create_command_signature as usize), ("CreatePipelineLibrary", dev_create_pipeline_library as usize), + ("SetResidencyPriority", dev_set_residency_priority as usize), ("CreatePipelineState", dev_create_pipeline_state as usize), + ("EnqueueMakeResident", dev_enqueue_make_resident as usize), ("CreateCommandList1", dev_create_command_list1 as usize), ("CreateCommittedResource1", dev_create_committed_resource1 as usize), ("CreateHeap1", dev_create_heap1 as usize), From 4c71d15c3919c4a944adf6ec2329ab26a234e963 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:50:30 -0800 Subject: [PATCH 035/265] README: document performance attribution outputs Describe opt-in stall summaries and the ranked-preload counters emitted by the reproducible comparison tooling.\n\nAssisted-by: Codex (GPT-5.6-sol) --- README.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e8367c3af3..e094d7c564 100644 --- a/README.md +++ b/README.md @@ -297,6 +297,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder `null` if its format cannot be decoded. Intermediate render-target dumps do not update it. Sampling uses every fourth pixel in each direction (`XCL_FRAME_DUMP_FULL=1`: every pixel). A coarse sample can miss detail; a non-dark sample does not establish correct rendering or gameplay. + With `XCL_STALL_TRACE=1`, `report.json` also contains versioned aggregate counts, total/max time and + log2-nanosecond histograms for coarse runtime stalls, plus a bounded list of the newest spans of at + least 50 ms. The tracing is off by default. - **Diagnostics for a bug report** (all off by default; set them in the environment of `xcl run`): - `XCL_RUN_SECONDS=n`: the title ends itself after `n` seconds, with the GPU drained and `xcl.log` and `report.json` written, so a run of a fixed length can be attached. A value that @@ -360,10 +363,11 @@ Compare two completed artifact folders without modifying them: .\scripts\perf-compare.ps1 -Baseline 'D:\xcl-perf\main' -Candidate 'D:\xcl-perf\change' > comparison.json ``` -The console shows raw cold/warm duration, exit/timeout state, stall totals/counts/maxima, and the five -compute-build coalescing counters. The redirected JSON keeps those values, raw deltas, and stall log2 -histograms. Missing reports or preparation summaries and unsupported preparation versions remain -explicit states; they are not treated as zero. The tool +The console shows raw cold/warm duration, exit/timeout state, stall totals/counts/maxima, the five +compute-build coalescing counters, and ranked-preload submissions, starts and promotions. The +redirected JSON keeps those values, raw deltas, and stall log2 histograms. Missing reports or +preparation summaries and unsupported preparation versions remain explicit states; they are not +treated as zero. The tool refuses different workload fingerprints or identity algorithm/versions, run order, requested duration, runtime environment, system, GPU, or GPU driver. Missing reports and stall summaries are labelled as missing; it does not infer significance or percentages. From 83c323643c6c8b756ebb40b80182451142f8a62b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:51:39 -0800 Subject: [PATCH 036/265] Shaders: prioritize title-wanted DXC jobs Replace FIFO DXC admission with a queue that rechecks dynamic demand at dequeue. The oldest wanted compile runs before background work while FIFO is preserved within both classes; running work, memory admission, and worker counts remain unchanged.\n\nFocused XCL tests could not run on Linux because retour uses unsupported stdcall and fastcall ABIs.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/dxc.rs | 147 +++++++++++++++++++++++++------ 1 file changed, 121 insertions(+), 26 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 62fdce8fa3..ae9d017343 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -9,11 +9,11 @@ //! kept for `report.json` ([`toolchain`]). use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, OnceLock, Weak}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, Weak}; use windows::core::{Interface, GUID, HRESULT, PCWSTR}; use windows::Win32::Graphics::Direct3D::Dxc::{ @@ -395,9 +395,102 @@ struct Job { queue_stall: Option>, } +struct CompileQueue { + jobs: Mutex>, + changed: Condvar, + workers: AtomicUsize, +} + +impl CompileQueue { + fn new() -> Self { + Self { jobs: Mutex::new(VecDeque::new()), changed: Condvar::new(), workers: AtomicUsize::new(0) } + } + + fn push(&self, job: Job) -> Result<(), Job> { + let mut jobs = self.jobs.lock().unwrap_or_else(|e| e.into_inner()); + if self.workers.load(Ordering::Acquire) == 0 { + return Err(job); + } + jobs.push_back(job); + drop(jobs); + self.changed.notify_one(); + Ok(()) + } + + fn take(&self) -> Job { + let mut jobs = self.jobs.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(job) = take_next_job(&mut jobs) { + return job; + } + jobs = self.changed.wait(jobs).unwrap_or_else(|e| e.into_inner()); + } + } +} + +struct CompileWorker(Arc); + +impl Drop for CompileWorker { + fn drop(&mut self) { + if self.0.workers.fetch_sub(1, Ordering::AcqRel) == 1 { + self.0.jobs.lock().unwrap_or_else(|e| e.into_inner()).clear(); + } + } +} + +/// Wanted jobs overtake unwanted ones; both classes remain FIFO. +fn take_next_job(jobs: &mut VecDeque) -> Option { + let position = jobs.iter().position(|job| (job.wanted)()).unwrap_or(0); + jobs.remove(position) +} + /// Whether one of the title's threads waits for a compile (asked again while it is held back). pub type Wanted = Box bool + Send>; +#[cfg(test)] +mod queue_tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + + fn job(name: &str, wanted: Wanted) -> Job { + let (reply, _) = std::sync::mpsc::channel(); + Job { + src: name.into(), + entry: String::new(), + profile: String::new(), + extra: Vec::new(), + reply, + wanted, + queue_stall: None, + } + } + + #[test] + fn wanted_dxc_jobs_overtake_background_fifo() { + let mut jobs = VecDeque::from([ + job("background-1", Box::new(|| false)), + job("wanted-1", Box::new(|| true)), + job("wanted-2", Box::new(|| true)), + job("background-2", Box::new(|| false)), + ]); + let order: Vec<_> = (0..4).map(|_| take_next_job(&mut jobs).unwrap().src).collect(); + assert_eq!(order, ["wanted-1", "wanted-2", "background-1", "background-2"]); + } + + #[test] + fn queued_job_is_rechecked_after_foreground_promotion() { + let wanted = Arc::new(AtomicBool::new(false)); + let check = wanted.clone(); + let mut jobs = VecDeque::from([ + job("background", Box::new(|| false)), + job("promoted", Box::new(move || check.load(Ordering::Acquire))), + ]); + wanted.store(true, Ordering::Release); + assert_eq!(take_next_job(&mut jobs).unwrap().src, "promoted"); + assert_eq!(take_next_job(&mut jobs).unwrap().src, "background"); + } +} + /// Compiles the title waits for that go on at once however little commit is left (each takes /// 0.1 – 0.7 GB). const WANTED_AT_ONCE: usize = 6; @@ -467,31 +560,33 @@ pub fn wait_for_memory(wanted: &Wanted) -> MemorySlot { /// DXC workers (`compile_threads`, each with its own compiler and a `DXC_STACK` stack), started /// on first use; callers wait for their job. -fn pool() -> &'static std::sync::Mutex> { - static POOL: OnceLock>> = OnceLock::new(); +fn pool() -> &'static Arc { + static POOL: OnceLock> = OnceLock::new(); POOL.get_or_init(|| { - let (tx, rx) = std::sync::mpsc::channel::(); - let rx = std::sync::Arc::new(std::sync::Mutex::new(rx)); + let queue = Arc::new(CompileQueue::new()); for k in 0..compile_threads() { - let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || loop { - let job = match rx.lock().unwrap().recv() { - Ok(j) => j, - Err(_) => return, - }; - let Job { src, entry, profile, extra, reply, wanted, queue_stall } = job; - let _slot = wait_for_memory(&wanted); - drop(queue_stall); - let extra: Vec<&str> = extra.iter().map(|s| s.as_str()).collect(); - let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let _stall = crate::stall::span(crate::stall::StallKind::DxcCompile); - compile_here(&src, &entry, &profile, &extra) - })) - .unwrap_or_else(|_| Err("DXC: panic in the compile thread".into())); - let _ = reply.send(r); - }); + let worker_queue = queue.clone(); + queue.workers.fetch_add(1, Ordering::Release); + if std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || { + let _worker = CompileWorker(worker_queue.clone()); + loop { + let job = worker_queue.take(); + let Job { src, entry, profile, extra, reply, wanted, queue_stall } = job; + let _slot = wait_for_memory(&wanted); + drop(queue_stall); + let extra: Vec<&str> = extra.iter().map(|s| s.as_str()).collect(); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _stall = crate::stall::span(crate::stall::StallKind::DxcCompile); + compile_here(&src, &entry, &profile, &extra) + })) + .unwrap_or_else(|_| Err("DXC: panic in the compile thread".into())); + let _ = reply.send(r); + } + }).is_err() { + queue.workers.fetch_sub(1, Ordering::AcqRel); + } } - std::sync::Mutex::new(tx) + queue }) } @@ -507,7 +602,7 @@ pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result< wanted: crate::hle::d3d12x::pso_async::wanted_here(), queue_stall: crate::stall::span(crate::stall::StallKind::DxcQueue), }; - pool().lock().unwrap().send(job).map_err(|_| "DXC: no compile threads".to_string())?; + pool().push(job).map_err(|_| "DXC: no compile threads".to_string())?; rx.recv().map_err(|_| "DXC: the compile thread exited".to_string())? } From 522f761a16942e08f3bfb04103891dd0d6df4f72 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:51:49 -0800 Subject: [PATCH 037/265] DirectStorage: attribute synchronous queue stalls Measure non-empty batch handoff and only the Close path that actually waits for the queue worker. Asynchronous request lifetime, decompression, file I/O, and fence activity remain outside this category.\n\nThe Windows-target check stopped before XCL compilation because this Linux host lacks MSVC headers.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/dstorage.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 2ae4fe1b66..9972f2e538 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -1106,6 +1106,7 @@ impl QueueInner { if batch.is_empty() { return; } + let _stall = crate::stall::span(crate::stall::StallKind::DirectStorage); if w.is_none() { let (tx, rx) = mpsc::channel::>(); let q = Arc::clone(self); @@ -1492,6 +1493,7 @@ unsafe extern "system" fn queue_close(p: *mut c_void) { // after `Close()` returns (including for concurrent `Close()` callers). let (lock, cvar) = &q.worker_active; let mut active = lock.lock().unwrap(); + let _stall = if *active { crate::stall::span(crate::stall::StallKind::DirectStorage) } else { None }; while *active { active = cvar.wait(active).unwrap(); } From 166a3142d64373c84bd3167bfcb221e6ce784b57 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:52:21 -0800 Subject: [PATCH 038/265] D3D12.X: transfer split UMA ownership before Close Detach a reserved destination's old UMA blocks during split preflight and hold them under their original allocator before the producer commit. Installing prepared bind state after Close now performs only lookup, moves, assignments, and drops.\n\nFocused XCL tests could not run on Linux because retour uses unsupported stdcall and fastcall ABIs.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 70 ++++++++++++++++++++++++------- 1 file changed, 56 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 20d541668e..5c6619cde3 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -100,7 +100,8 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { }); } -/// Allocation-bearing root state captured before a mid-list split commits. +/// Allocation-bearing root state captured before a mid-list split commits. Preparation also +/// transfers the reserved destination's old UMA ownership, so installation cannot allocate. pub(super) struct PreparedSplit { to: usize, allocator: usize, @@ -116,25 +117,29 @@ pub(super) fn prepare_split(from: *mut c_void, to: *mut c_void, allocator: usize let (layout, args, layout_gfx, args_gfx, rs_gfx, pso) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso) }); - with(to, |_| ()); + let (old, blocks) = with(to, |s| { + let old = std::mem::replace(&mut s.allocator, 0); + s.arena = Default::default(); + (old, std::mem::take(&mut s.uma)) + }); + console_list::hold_until_reset(old, blocks); PreparedSplit { to: to as usize, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso } } /// Install a preflighted split state without cloning or growing the state map. pub(super) fn install_prepared_split(prepared: PreparedSplit) { let PreparedSplit { to, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso } = prepared; - let (old, blocks) = with(to as *mut c_void, |s| { - let old = std::mem::replace(&mut s.allocator, allocator); - s.arena = Default::default(); - s.layout = layout; - s.args = args; - s.layout_gfx = layout_gfx; - s.args_gfx = args_gfx; - s.rs_gfx = rs_gfx; - s.pso = pso; - (old, std::mem::take(&mut s.uma)) - }); - console_list::hold_until_reset(old, blocks); + let mut states = STATES.lock().unwrap(); + let s = states.as_mut().and_then(|m| m.get_mut(&to)).expect("prepared split destination state"); + debug_assert_eq!(s.allocator, 0); + debug_assert!(s.uma.is_empty()); + s.allocator = allocator; + s.layout = layout; + s.args = args; + s.layout_gfx = layout_gfx; + s.args_gfx = args_gfx; + s.rs_gfx = rs_gfx; + s.pso = pso; } pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { @@ -1376,6 +1381,43 @@ void main(uint t : SV_GroupIndex) { forget(list); } + #[test] + fn split_preflight_transfers_destination_uma_before_install() { + let from = 0x7101_0001usize as *mut c_void; + let to = 0x7101_0002usize as *mut c_void; + let (old_alloc, new_alloc) = (0x7101_0100usize, 0x7101_0200usize); + let _ = console_list::take_pending_for_test(old_alloc); + seed_reset_state_for_test(from, 0x7101_0300, 0x7101_1000, vec![0x7101_4000]); + seed_reset_state_for_test(to, old_alloc, 0x7101_2000, vec![0x7101_5000, 0x7101_6000]); + + let prepared = prepare_split(from, to, new_alloc); + assert_eq!(reset_state_for_test(from), (0x7101_0300, 0x7101_1000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], vec![0x7101_4000])); + assert_eq!(reset_state_for_test(to), (0, 0x7101_2000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], Vec::new())); + + install_prepared_split(prepared); + assert_eq!(reset_state_for_test(to), (new_alloc, 0x7101_1000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], Vec::new())); + assert_eq!(console_list::take_pending_for_test(old_alloc), vec![0x7101_5000, 0x7101_6000]); + remove_state_for_test(from); + remove_state_for_test(to); + } + + #[test] + fn abandoned_split_preflight_keeps_old_uma_under_its_allocator() { + let from = 0x7102_0001usize as *mut c_void; + let to = 0x7102_0002usize as *mut c_void; + let old_alloc = 0x7102_0100usize; + let _ = console_list::take_pending_for_test(old_alloc); + seed_reset_state_for_test(from, 0x7102_0200, 0x7102_1000, Vec::new()); + seed_reset_state_for_test(to, old_alloc, 0x7102_2000, vec![0x7102_5000]); + + drop(prepare_split(from, to, 0x7102_0300)); + forget(to); + + assert_eq!(console_list::take_pending_for_test(old_alloc), vec![0x7102_5000]); + assert_eq!(reset_state_for_test(from).0, 0x7102_0200, "the active producer must remain untouched"); + remove_state_for_test(from); + } + #[repr(C)] struct FakeAdoptedList { vt: *const usize, From abebd9f049347753638ebc1e1bb1c388de2deadb Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:54:21 -0800 Subject: [PATCH 039/265] D3D12.X: make title pipeline demand lock-free Expose the monotonic title-wait signal to DXC admission through an atomic instead of taking each Build demand mutex while the shared compile queue is locked. Keep submit demand and preload worker priority coordination under the existing mutex.\n\nFocused XCL tests could not run on Linux because retour uses unsupported stdcall and fastcall ABIs.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 48 +++++++++++++++++++------- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index bea0044edc..aef496504f 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -8,7 +8,7 @@ //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; -use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock, Weak}; use super::build_queue::{BuildQueue, JobHandle, Priority}; @@ -53,14 +53,15 @@ struct Build { orphan: std::sync::atomic::AtomicBool, /// Title-visible `Pending`s sharing this build. Changed while holding `done`. owners: AtomicUsize, + /// One of the title's threads waits for this build. Polled by DXC admission. + wanted: AtomicBool, demand: Mutex, queued: Mutex>, } -/// Whether one of the title's threads waits for the pipeline, and the preload worker building it. +/// Submit demand and the preload worker building this pipeline. #[derive(Default)] struct Demand { - wanted: bool, /// a call put off to the submit needs it (`need_by_submit`) by_submit: bool, /// thread id of the preload worker (lowest priority) building it, 0 = none @@ -77,7 +78,7 @@ thread_local! { /// This thread is a worker and one of the title's threads waits for what it is building: the /// build must not stand back for the title's sake (`real::big_compile_turn`). pub(super) fn build_is_wanted() -> bool { - BUILDING.with(|b| b.borrow().as_ref().is_some_and(|build| build.demand.lock().unwrap().wanted)) + BUILDING.with(|b| b.borrow().as_ref().is_some_and(|build| build.wanted.load(Ordering::Acquire))) } /// Whether one of the title's threads waits for what this thread is doing, to be asked later and @@ -85,7 +86,7 @@ pub(super) fn build_is_wanted() -> bool { /// title's own. pub fn wanted_here() -> crate::gpu::recomp::dxc::Wanted { if let Some(build) = BUILDING.with(|b| b.borrow().clone()) { - return Box::new(move || build.demand.lock().unwrap().wanted); + return Box::new(move || build.wanted.load(Ordering::Acquire)); } let own = crate::state::boot().is_some() && !std::thread::current().name().is_some_and(|n| n.starts_with("xcl-")); Box::new(move || own) @@ -102,7 +103,7 @@ impl Drop for RunningBuild<'_> { // (under the lock: `want` does not raise this thread after it) let mut demand = self.build.demand.lock().unwrap(); demand.preload_thread = 0; - if demand.wanted { + if self.build.wanted.load(Ordering::Acquire) { unsafe { use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); @@ -129,7 +130,7 @@ fn run_build(build: &Arc, job: Job) { if preload { let mut d = build.demand.lock().unwrap(); d.preload_thread = unsafe { GetCurrentThreadId() }; - if d.wanted { + if build.wanted.load(Ordering::Acquire) { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } @@ -152,6 +153,7 @@ impl Build { cv: Condvar::new(), orphan: Default::default(), owners: AtomicUsize::new(1), + wanted: AtomicBool::new(false), demand: Default::default(), queued: Mutex::new(None), } @@ -176,8 +178,11 @@ impl Build { use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_PRIORITY_NORMAL, THREAD_SET_LIMITED_INFORMATION}; start_normal_workers(); self.promote(Priority::Foreground); - let mut d = self.demand.lock().unwrap(); - if !std::mem::replace(&mut d.wanted, true) && d.preload_thread != 0 { + if !self.wanted.swap(true, Ordering::AcqRel) { + let d = self.demand.lock().unwrap(); + if d.preload_thread == 0 { + return; + } unsafe { let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread); if !h.is_null() { @@ -517,10 +522,7 @@ fn schedule(build: &Arc, priority: Priority, preload: bool, preload_rank: } let mut queued = build.queued.lock().unwrap(); if !build.sent.swap(true, Ordering::AcqRel) { - let priority = if { - let demand = build.demand.lock().unwrap(); - demand.wanted || demand.by_submit - } { + let priority = if build.wanted.load(Ordering::Acquire) || build.demand.lock().unwrap().by_submit { Priority::Foreground } else { priority @@ -1139,6 +1141,26 @@ mod used_tests { let _ = released(standin); } + /// DXC admission probes demand while holding its own queue lock: the probe cannot take this + /// build's demand lock, and submit demand is intentionally not a title-thread wait. + #[test] + fn wanted_probe_is_lock_free_and_excludes_submit_demand() { + let build = Arc::new(Build::new(Box::new(|| 0), false)); + let before = BUILDING.with(|building| building.replace(Some(build.clone()))); + let _restore = RestoreBuilding(before); + let wanted = wanted_here(); + build.demand.lock().unwrap().by_submit = true; + assert!(!wanted(), "submit demand does not mean a title thread is waiting"); + + let demand = build.demand.lock().unwrap(); + build.wanted.store(true, Ordering::Release); + let (tx, rx) = mpsc::channel(); + let thread = std::thread::spawn(move || tx.send(wanted()).unwrap()); + assert!(rx.recv_timeout(std::time::Duration::from_secs(2)).expect("wanted probe took the demand lock")); + drop(demand); + thread.join().unwrap(); + } + /// A compile a worker's build starts is wanted once a bind waits for the build – asked from /// another thread, as the DXC workers do; a thread that builds nothing (no title runs here) /// wants nothing. From 73898793979b9db93e4f5b06f6c83e7358705003 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:55:40 -0800 Subject: [PATCH 040/265] D3D12.X: fail closed when Kickoff Close fails Preflight a known-closed standby and failure bookkeeping before a wrapped Kickoff mutates recording state. Defer effect consumption until Close succeeds; on failure route the wrapper to the standby and quarantine the producer without issuing later list calls.\n\nFocused XCL tests could not run on Linux because retour uses unsupported stdcall and fastcall ABIs.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 103 +++++++++++++++++++++--- crates/xcl/src/hle/d3d12x/title_list.rs | 19 +++++ 2 files changed, 110 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 8f5397f2d3..1f4a284501 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -864,6 +864,29 @@ impl ListState { } } +struct KickoffEffects { + waits: Vec, + sparse_writes: Vec<(usize, usize)>, + write64_signals: Vec<(u64, u64)>, + cpu_writes: Vec, +} + +fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { + let effects = KickoffEffects { + waits: std::mem::take(&mut state.pending_waits), + sparse_writes: state.clear_sparse_writes(), + write64_signals: state.clear_write64_signals(), + cpu_writes: std::mem::take(&mut state.cpu_writes), + }; + state.written_ranges.clear(); + state.segment_write_producers.clear(); + effects +} + +fn take_kickoff_effects_before_close(state: &mut ListState, has_fail_closed_standby: bool) -> Option { + (!has_fail_closed_standby).then(|| take_kickoff_effects(state)) +} + /// Recording state that a PC Reset loses and the continuation segment must inherit. struct SplitCarry { allocator: usize, @@ -3666,10 +3689,11 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { 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, 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 { + let dev = device_of(this); + let dev_raw = dev.as_ref().map_or(0, |d| d.as_raw() as usize); + let (alloc, queue) = { + let g = LISTS.lock().unwrap(); + let Some(s) = g.as_ref().and_then(|m| m.get(&(this as usize))) else { if once(&NO_QUEUE, 4) { crate::xlog_info!("D3D12.X: KickoffX – list allocator unknown, deferring to Close + ExecuteCommandLists"); } @@ -3687,18 +3711,37 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } return; }; + (s.allocator, q) + }; + let wrapper = super::title_list::wrapper_of(this); + let standby = if let Some(wrapper) = wrapper { + let Some(dev) = dev.as_ref() else { + return warn(&ERR, "KickoffX", format_args!("could not get the command-list device for fail-closed preflight")); + }; + if !super::title_list::prepare_fail_closed(wrapper) { + return warn(&ERR, "KickoffX", format_args!("could not reserve fail-closed bookkeeping")); + } + let Some(standby) = reserve_closed_segment(wrapper, dev, ty) else { + return warn(&ERR, "KickoffX", format_args!("could not reserve a closed standby")); + }; + Some((wrapper, standby)) + } else { + None + }; + let (bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, preclose_effects) = { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { + if let Some((wrapper, standby)) = standby { + super::title_list::put_spare(wrapper, standby); + } + return; + }; let active_query = s.occlusion.end_active_early(); - let waits = std::mem::take(&mut s.pending_waits); - let sparse_writes = s.clear_sparse_writes(); - let write64_signals = s.clear_write64_signals(); - s.written_ranges.clear(); - s.segment_write_producers.clear(); - let cpu_writes = std::mem::take(&mut s.cpu_writes); + let preclose_effects = take_kickoff_effects_before_close(s, standby.is_some()); 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, write64_signals, cpu_writes)) + (s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, preclose_effects) }; - let (sparse_writes, write64_signals, cpu_writes) = sparse_writes; // End any active occlusion query before Close (PC forbids closing with an open query). if let Some(((h, i), qty)) = active_query { @@ -3714,8 +3757,21 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let close_hr = pc:: i32>(this, PC_CLOSE)(this); real::preserve_vtable(this, ext); if close_hr < 0 { + if let Some((wrapper, standby)) = standby { + super::title_list::fail_closed(wrapper, this, standby, true); + } return warn(&ERR, "KickoffX", format_args!("Close failed ({close_hr:#x})")); } + let effects = match preclose_effects { + Some(effects) => effects, + None => LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).map(take_kickoff_effects).unwrap_or(KickoffEffects { + waits: Vec::new(), sparse_writes: Vec::new(), write64_signals: Vec::new(), cpu_writes: Vec::new(), + }), + }; + let KickoffEffects { waits, sparse_writes, write64_signals, cpu_writes } = effects; + if let Some((wrapper, standby)) = standby { + super::title_list::put_spare(wrapper, standby); + } if let Some(wrapper) = super::title_list::wrapper_of(this) { record_deferred(wrapper); } @@ -5749,6 +5805,29 @@ mod tests { assert!(state.written_ranges.overlaps(WriteProducer::CpuAfterSegment, 0x3000, 8)); } + #[test] + fn wrapper_kickoff_defers_effect_consumption_until_close_succeeds() { + let wait = PendingWait { va: 0x4000, width: 8, comparison: 7, value: 1, mask: u64::MAX, after_write64: false }; + let mut state = ListState { + pending_waits: vec![wait], + cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x5000, vec![1])], + ..Default::default() + }; + state.note_write(WriteProducer::CpuAfterSegment, 0x5000, 4); + + assert!(take_kickoff_effects_before_close(&mut state, true).is_none()); + assert_eq!(state.pending_waits, vec![wait]); + assert_eq!(state.cpu_writes.len(), 1); + assert!(state.written_ranges.overlaps(WriteProducer::CpuAfterSegment, 0x5000, 4)); + assert!(state.segment_write_producers.overlaps(WriteProducer::CpuAfterSegment, 0x5000, 4)); + + let effects = take_kickoff_effects_before_close(&mut state, false).unwrap(); + assert_eq!(effects.waits, vec![wait]); + assert_eq!(effects.cpu_writes.len(), 1); + assert!(state.pending_waits.is_empty() && state.cpu_writes.is_empty()); + assert!(state.written_ranges.is_empty() && state.segment_write_producers.is_empty()); + } + #[test] fn split_carry_recreates_the_continuation_state() { let query = (0x7100, 3); diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 0143f87caa..fa57110563 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -332,6 +332,22 @@ pub(super) fn prepare_split(wrapper: *mut c_void, n: usize) -> bool { wg.get_or_insert_with(HashMap::new).try_reserve(1).is_ok() } +/// Reserve only the bookkeeping a fail-closed transition or successful standby return needs. +/// Unlike a recording split, this does not consume physical-segment capacity. +pub(super) fn prepare_fail_closed(wrapper: *mut c_void) -> bool { + let mut sg = SEGMENTS.lock().unwrap(); + let m = sg.get_or_insert_with(HashMap::new); + if m.try_reserve(1).is_err() { + return false; + } + let b = m.entry(wrapper as usize).or_default(); + if b.failed.is_some() || b.spares.try_reserve(1).is_err() || b.unresettable.try_reserve(1).is_err() { + return false; + } + let mut wg = WRAPPER_OF.lock().unwrap(); + wg.get_or_insert_with(HashMap::new).try_reserve(1).is_ok() +} + /// Pop a previously created closed extra PC command list from `wrapper`'s spare pool for reuse /// (the last one whose submits the GPU has finished). pub(super) fn pop_spare(wrapper: *mut c_void) -> Option<*mut c_void> { @@ -553,6 +569,9 @@ mod tests { push_segment(wrapper, 0x9000usize as *mut c_void); assert!(!can_split(wrapper, 1)); assert!(can_split(wrapper, 0)); + assert!(prepare_fail_closed(wrapper), "Kickoff standby does not consume segment capacity"); + SEGMENTS.lock().unwrap().as_mut().unwrap().get_mut(&(wrapper as usize)).unwrap().failed = Some(0x9100); + assert!(!prepare_fail_closed(wrapper), "an already failed recording cannot preflight again"); SEGMENTS.lock().unwrap().as_mut().unwrap().remove(&(wrapper as usize)); } From 974e33958cdfa3f221462371b01c2def2a514661 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:58:50 -0800 Subject: [PATCH 041/265] D3D12.X: fail closed when Kickoff Reset fails Keep the preflighted closed standby through submission and target Reset. Return it only after Reset succeeds; on failure route the wrapper through it without marking the successfully closed and submitted target permanently unresettable.\n\nFocused XCL tests could not run on Linux because retour uses unsupported stdcall and fastcall ABIs.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 59 +++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 1f4a284501..a28471d488 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -887,6 +887,21 @@ fn take_kickoff_effects_before_close(state: &mut ListState, has_fail_closed_stan (!has_fail_closed_standby).then(|| take_kickoff_effects(state)) } +fn settle_kickoff_standby( + standby: Option<(T, U)>, + reset_succeeded: bool, + return_spare: impl FnOnce(T, U), + fail_closed: impl FnOnce(T, U, bool), +) { + if let Some((wrapper, standby)) = standby { + if reset_succeeded { + return_spare(wrapper, standby); + } else { + fail_closed(wrapper, standby, false); + } + } +} + /// Recording state that a PC Reset loses and the continuation segment must inherit. struct SplitCarry { allocator: usize, @@ -3769,9 +3784,6 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { }), }; let KickoffEffects { waits, sparse_writes, write64_signals, cpu_writes } = effects; - if let Some((wrapper, standby)) = standby { - super::title_list::put_spare(wrapper, standby); - } if let Some(wrapper) = super::title_list::wrapper_of(this) { record_deferred(wrapper); } @@ -3871,6 +3883,12 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { pc:: i32>(target, PC_RESET)(target, pc_alloc, init_pso) }); real::preserve_vtable(target, ext_closed); + settle_kickoff_standby( + standby, + reset_hr >= 0, + |wrapper, standby| super::title_list::put_spare(wrapper, standby), + |wrapper, standby, producer_broken| super::title_list::fail_closed(wrapper, target, standby, producer_broken), + ); if reset_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); } @@ -5828,6 +5846,41 @@ mod tests { assert!(state.written_ranges.is_empty() && state.segment_write_producers.is_empty()); } + #[test] + fn kickoff_standby_ownership_settles_only_after_target_reset() { + use std::cell::Cell; + let returned = Cell::new(None); + let failed = Cell::new(None); + settle_kickoff_standby( + Some((0x7100usize, 0x7200usize)), + true, + |w, s| returned.set(Some((w, s))), + |w, s, producer_broken| failed.set(Some((w, s, producer_broken))), + ); + assert_eq!(returned.get(), Some((0x7100, 0x7200))); + assert_eq!(failed.get(), None); + + returned.set(None); + settle_kickoff_standby( + Some((0x7300usize, 0x7400usize)), + false, + |w, s| returned.set(Some((w, s))), + |w, s, producer_broken| failed.set(Some((w, s, producer_broken))), + ); + assert_eq!(returned.get(), None); + assert_eq!(failed.get(), Some((0x7300, 0x7400, false))); + + failed.set(None); + settle_kickoff_standby( + None::<(usize, usize)>, + false, + |w, s| returned.set(Some((w, s))), + |w, s, producer_broken| failed.set(Some((w, s, producer_broken))), + ); + assert_eq!(returned.get(), None); + assert_eq!(failed.get(), None); + } + #[test] fn split_carry_recreates_the_continuation_state() { let query = (0x7100, 3); From 01c0835a5b7f691dd75b1d1ecd6245ac3673beb6 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:01:06 -0800 Subject: [PATCH 042/265] D3D12.X: order texture uploads on the GPU Retain upload allocators, command lists, fences, and mapped staging in a bounded three-slot ring. Enqueue a title-queue wait for each upload completion instead of blocking the submit thread, with oldest-slot backpressure and a CPU fallback only if the driver rejects the queue wait.\n\nThe Windows-target check stopped before XCL compilation because this Linux host lacks MSVC headers and tools.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/texture.rs | 137 +++++++++++++++++--- crates/xcl/src/hle/d3d12x/title_textures.rs | 28 +++- 2 files changed, 144 insertions(+), 21 deletions(-) diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index cde3561492..72c75caf8f 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -221,6 +221,11 @@ unsafe impl Send for Uploader {} /// queue (raw pointer) → its uploader, while no batch uses it static UPLOADERS: std::sync::Mutex>> = std::sync::Mutex::new(None); +/// Bounded uploaders whose resources stay alive while a title queue waits on their copy fence. +static QUEUED_UPLOADERS: std::sync::Mutex>>> = + std::sync::Mutex::new(None); +const QUEUED_UPLOADER_SLOTS: usize = 3; + /// the smallest upload buffer made, and the placement alignment of texture data in it const STAGING_MIN: u64 = 4 << 20; const PLACEMENT: u64 = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64; @@ -263,20 +268,29 @@ impl Uploader { } } -/// Several uploads on one list, one wait: (resource, subresources, states) each – the states -/// the texture is in and is left in: one for every subresource, or one per subresource (D3D12 -/// order). A failure of one is returned with its index; the others still run. The texels go -/// through the queue's kept upload buffer (`Uploader`). -pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { - if items.is_empty() { - return Ok(Vec::new()); +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum SlotChoice { + Reuse(usize), + Grow, + WaitOldest, +} + +fn choose_slot(len: usize, mut completed: impl FnMut(usize) -> bool) -> SlotChoice { + if let Some(index) = (0..len).find(|&index| completed(index)) { + SlotChoice::Reuse(index) + } else if len < QUEUED_UPLOADER_SLOTS { + SlotChoice::Grow + } else { + SlotChoice::WaitOldest } - let key = windows::core::Interface::as_raw(queue) as usize; - let taken = UPLOADERS.lock().unwrap().as_mut().and_then(|m| m.remove(&key)); - let mut up = match taken { - Some(u) => u, - None => Uploader::new(dev)?, - }; +} + +unsafe fn submit_batch( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + items: &[(ID3D12Resource, Vec, Vec)], + up: &mut Uploader, +) -> Result<(Vec<(usize, String)>, bool), String> { // where each texture's texels go in the upload buffer let mut failed = Vec::new(); let mut planned = Vec::with_capacity(items.len()); @@ -292,8 +306,7 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items } } if planned.is_empty() { - put_back(key, up); - return Ok(failed); + return Ok((failed, false)); } let (staging, mapped) = up.staging(dev, total)?; up.alloc.Reset().map_err(err)?; @@ -307,6 +320,40 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items up.value += 1; let copy_error = |e| format!("texture copy: {e}"); queue.Signal(&up.fence, up.value).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?; + Ok((failed, true)) +} + +/// Several uploads on one list, one wait: (resource, subresources, states) each – the states +/// the texture is in and is left in: one for every subresource, or one per subresource (D3D12 +/// order). A failure of one is returned with its index; the others still run. The texels go +/// through the queue's kept upload buffer (`Uploader`). +pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { + if items.is_empty() { + return Ok(Vec::new()); + } + let key = windows::core::Interface::as_raw(queue) as usize; + let taken = UPLOADERS.lock().unwrap().as_mut().and_then(|m| m.remove(&key)); + let mut up = match taken { + Some(u) => u, + None => Uploader::new(dev)?, + }; + let before = up.value; + let (failed, submitted) = match submit_batch(dev, queue, items, &mut up) { + Ok(result) => result, + Err(e) => { + if up.value == before { + put_back(key, up); + } else { + std::mem::forget(up); + } + return Err(e); + } + }; + if !submitted { + put_back(key, up); + return Ok(failed); + } + let copy_error = |e| format!("texture copy: {e}"); if let Err(e) = fence::wait(&up.fence, up.value, dev, None, 10_000) { // the GPU may still read the upload buffer and run the list: they stay alive (a fresh // uploader next time) – freeing them under the GPU removed the device @@ -317,6 +364,54 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items Ok(failed) } +pub(crate) struct UploadCompletion { + pub(crate) fence: ID3D12Fence, + pub(crate) value: u64, +} + +/// Submit an upload while retaining its resources in a bounded ring. The caller must enqueue a +/// wait for the returned fence value before work that consumes the uploaded textures. +pub unsafe fn upload_batch_queued( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + items: &[(ID3D12Resource, Vec, Vec)], +) -> Result<(Vec<(usize, String)>, Option), String> { + if items.is_empty() { + return Ok((Vec::new(), None)); + } + let key = windows::core::Interface::as_raw(queue) as usize; + let mut pools = QUEUED_UPLOADERS.lock().unwrap(); + let slots = pools.get_or_insert_with(Default::default).entry(key).or_default(); + let choice = choose_slot(slots.len(), |index| { + fence::completed_value(&slots[index].fence, dev).is_ok_and(|value| value >= slots[index].value) + }); + let mut up = match choice { + SlotChoice::Reuse(index) => slots.remove(index).unwrap(), + SlotChoice::Grow => Uploader::new(dev)?, + SlotChoice::WaitOldest => { + let up = slots.pop_front().unwrap(); + if let Err(e) = fence::wait(&up.fence, up.value, dev, None, 10_000) { + slots.push_front(up); + return Err(format!("texture copy: {e}")); + } + up + } + }; + let result = submit_batch(dev, queue, items, &mut up); + match result { + Ok((failed, submitted)) => { + let completion = submitted.then(|| UploadCompletion { fence: up.fence.clone(), value: up.value }); + slots.push_back(up); + Ok((failed, completion)) + } + Err(e) => { + // The slot retains its allocator/list/staging even when submission or signaling failed. + slots.push_back(up); + Err(e) + } + } +} + fn put_back(key: usize, up: Uploader) { UPLOADERS.lock().unwrap().get_or_insert_with(Default::default).insert(key, up); } @@ -482,6 +577,18 @@ mod tests { use std::collections::HashMap; use windows::Win32::Graphics::Dxgi::Common::*; + #[test] + fn queued_upload_ring_reuses_completed_slots_before_growing() { + assert_eq!(choose_slot(0, |_| false), SlotChoice::Grow); + assert_eq!(choose_slot(2, |index| index == 1), SlotChoice::Reuse(1)); + assert_eq!(choose_slot(2, |_| false), SlotChoice::Grow); + } + + #[test] + fn queued_upload_ring_waits_for_the_oldest_slot_at_its_bound() { + assert_eq!(choose_slot(QUEUED_UPLOADER_SLOTS, |_| false), SlotChoice::WaitOldest); + } + fn image(format: u32, ty: ImageType, w: u32, h: u32, slices: u32, mips: u32, mode: u32, address: u64) -> Image { Image { address, diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6d97bc6e4e..eb2de46ddc 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -827,7 +827,7 @@ unsafe fn refresh_once(queue: *mut c_void) { .collect() }); seed_stream_recheck(&todo, &ranges, recheck_frame); - upload_all(todo); + upload_all(queue, todo); } /// texture → `content_hash` of its memory at its last upload @@ -1088,7 +1088,7 @@ fn batch_fits(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_d } /// The uploads `todo`, in batches of up to `BATCH_BYTES` and `BATCH_ITEMS` (one list and one wait each). -unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { +unsafe fn upload_all(title_queue: *mut c_void, todo: Vec<(ID3D12Resource, Upload)>) { static N: AtomicU64 = AtomicU64::new(0); let warn = |e: &str| { if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -1140,7 +1140,7 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { } let d = device as *mut c_void; let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; - let queue = match upload_queue(dev, device) { + let upload_queue = match upload_queue(dev, device) { Ok(q) => q, Err(e) => { warn(&e); @@ -1148,13 +1148,29 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { } }; match own_work(|| { - super::vram::before_execute(&queue); - texture::upload_batch(dev, &queue, &batch) + super::vram::before_execute(&upload_queue); + texture::upload_batch_queued(dev, &upload_queue, &batch) }) { - Ok(failed) => { + Ok((failed, completion)) => { for (_, e) in failed { warn(&e); } + if let Some(done) = completion { + let dependency = match ID3D12CommandQueue::from_raw_borrowed(&title_queue) { + Some(title_queue) => title_queue.Wait(&done.fence, done.value).map(|()| { + super::list_x::note_internal_wait(title_queue.as_raw() as usize, "title texture uploads", &done.fence, done.value); + }).map_err(|e| format!("{e}")), + None => Err("title queue pointer is null".into()), + }; + if let Err(dependency) = dependency { + // An exceptional driver rejection still preserves visibility before the + // title submit; normal backpressure waits only when the ring is exhausted. + if let Err(wait) = crate::gpu::fence::wait(&done.fence, done.value, dev, None, 10_000) { + warn(&format!("title queue upload Wait failed ({dependency}); CPU fallback failed: {wait}")); + continue; + } + } + } UPLOADS.fetch_add(batch.len() as u64, Ordering::Relaxed); } Err(e) => warn(&e), From 187b41167574853f5368efea87856d6930269af7 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:05:55 -0800 Subject: [PATCH 043/265] D3D12.X: keep submission wait details private Expose an ordinary-submission wrapper that supplies the empty external-wait set inside list_x. Sibling modules no longer need to name the private PendingWait type, restoring Windows-target type checking.\n\n passed with warnings.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 11 ++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index a28471d488..6de60f9285 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2464,7 +2464,7 @@ unsafe fn submit_segment_effects(queue: *mut c_void, effects: &[SegmentEffects], } /// Execute a plan and retain completion receipts for its deferred CPU writes. -pub(super) unsafe fn execute_submission_plan_with_completions( +unsafe fn execute_submission_plan_with_completions( queue: *mut c_void, plan: &SubmissionPlan, external_waits: &[PendingWait], @@ -2505,6 +2505,15 @@ pub(super) unsafe fn execute_submission_plan_with_completions( completions } +/// Execute a plan for an ordinary queue submission, retaining deferred CPU-write receipts. +pub(super) unsafe fn execute_submission_plan_with_completions_on( + queue: *mut c_void, + plan: &SubmissionPlan, + submit: impl FnMut(SubmissionChunk<'_>) -> Option, +) -> Vec { + execute_submission_plan_with_completions(queue, plan, &[], submit) +} + /// Execute an immutable submission plan, splitting before an unsatisfied memory wait. pub(super) unsafe fn execute_submission_plan_on(queue: *mut c_void, plan: &SubmissionPlan, mut submit: impl FnMut(SubmissionChunk<'_>)) { let _ = execute_submission_plan_with_completions(queue, plan, &[], |chunk| { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 49693bd907..0043da3aad 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7354,7 +7354,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::list_x::note_queue_for_lists(this as usize, &mapped); let plan = super::list_x::submission_plan(&mapped); drop(preparation_stall); - let _ = super::list_x::execute_submission_plan_with_completions(this, &plan, &[], |chunk| { + let _ = super::list_x::execute_submission_plan_with_completions_on(this, &plan, |chunk| { let lists = chunk.lists(); let _ = super::alloc_pool::note_resubmits(this, lists); f(this, lists.len() as u32, lists.as_ptr()); From ba09a90beada1117a0a268d089bdbc26704beea4 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:06:04 -0800 Subject: [PATCH 044/265] D3D12.X: scope queued texture uploads to the crate Match the queued upload helper's visibility to its completion type and actual XCL-only consumers, removing the private-interface warning.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/texture.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index 72c75caf8f..af833c7595 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -371,7 +371,7 @@ pub(crate) struct UploadCompletion { /// Submit an upload while retaining its resources in a bounded ring. The caller must enqueue a /// wait for the returned fence value before work that consumes the uploaded textures. -pub unsafe fn upload_batch_queued( +pub(crate) unsafe fn upload_batch_queued( dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)], From 440c2c309ae747c82487d781265edfe3fbd2873a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:06:37 -0800 Subject: [PATCH 045/265] Revert "D3D12.X: scope queued texture uploads to the crate" This reverts commit c83cb0f2d6f64f45aed19f25c00814c0d2ba341b. --- crates/xcl/src/gpu/texture.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index af833c7595..72c75caf8f 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -371,7 +371,7 @@ pub(crate) struct UploadCompletion { /// Submit an upload while retaining its resources in a bounded ring. The caller must enqueue a /// wait for the returned fence value before work that consumes the uploaded textures. -pub(crate) unsafe fn upload_batch_queued( +pub unsafe fn upload_batch_queued( dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)], From c1a07e8867a4766066aba56955796bd50310b3f1 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:06:37 -0800 Subject: [PATCH 046/265] Revert "Merge GPU-ordered texture uploads" This reverts commit 7da8e4128bbb25ce765c269e5d8b4d3d5de6cb0e, reversing changes made to 2731878fe8a3b10250992e40cb8a807efa092f71. --- crates/xcl/src/gpu/texture.rs | 137 +++----------------- crates/xcl/src/hle/d3d12x/title_textures.rs | 28 +--- 2 files changed, 21 insertions(+), 144 deletions(-) diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index 72c75caf8f..cde3561492 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -221,11 +221,6 @@ unsafe impl Send for Uploader {} /// queue (raw pointer) → its uploader, while no batch uses it static UPLOADERS: std::sync::Mutex>> = std::sync::Mutex::new(None); -/// Bounded uploaders whose resources stay alive while a title queue waits on their copy fence. -static QUEUED_UPLOADERS: std::sync::Mutex>>> = - std::sync::Mutex::new(None); -const QUEUED_UPLOADER_SLOTS: usize = 3; - /// the smallest upload buffer made, and the placement alignment of texture data in it const STAGING_MIN: u64 = 4 << 20; const PLACEMENT: u64 = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64; @@ -268,29 +263,20 @@ impl Uploader { } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum SlotChoice { - Reuse(usize), - Grow, - WaitOldest, -} - -fn choose_slot(len: usize, mut completed: impl FnMut(usize) -> bool) -> SlotChoice { - if let Some(index) = (0..len).find(|&index| completed(index)) { - SlotChoice::Reuse(index) - } else if len < QUEUED_UPLOADER_SLOTS { - SlotChoice::Grow - } else { - SlotChoice::WaitOldest +/// Several uploads on one list, one wait: (resource, subresources, states) each – the states +/// the texture is in and is left in: one for every subresource, or one per subresource (D3D12 +/// order). A failure of one is returned with its index; the others still run. The texels go +/// through the queue's kept upload buffer (`Uploader`). +pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { + if items.is_empty() { + return Ok(Vec::new()); } -} - -unsafe fn submit_batch( - dev: &ID3D12Device, - queue: &ID3D12CommandQueue, - items: &[(ID3D12Resource, Vec, Vec)], - up: &mut Uploader, -) -> Result<(Vec<(usize, String)>, bool), String> { + let key = windows::core::Interface::as_raw(queue) as usize; + let taken = UPLOADERS.lock().unwrap().as_mut().and_then(|m| m.remove(&key)); + let mut up = match taken { + Some(u) => u, + None => Uploader::new(dev)?, + }; // where each texture's texels go in the upload buffer let mut failed = Vec::new(); let mut planned = Vec::with_capacity(items.len()); @@ -306,7 +292,8 @@ unsafe fn submit_batch( } } if planned.is_empty() { - return Ok((failed, false)); + put_back(key, up); + return Ok(failed); } let (staging, mapped) = up.staging(dev, total)?; up.alloc.Reset().map_err(err)?; @@ -320,40 +307,6 @@ unsafe fn submit_batch( up.value += 1; let copy_error = |e| format!("texture copy: {e}"); queue.Signal(&up.fence, up.value).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?; - Ok((failed, true)) -} - -/// Several uploads on one list, one wait: (resource, subresources, states) each – the states -/// the texture is in and is left in: one for every subresource, or one per subresource (D3D12 -/// order). A failure of one is returned with its index; the others still run. The texels go -/// through the queue's kept upload buffer (`Uploader`). -pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { - if items.is_empty() { - return Ok(Vec::new()); - } - let key = windows::core::Interface::as_raw(queue) as usize; - let taken = UPLOADERS.lock().unwrap().as_mut().and_then(|m| m.remove(&key)); - let mut up = match taken { - Some(u) => u, - None => Uploader::new(dev)?, - }; - let before = up.value; - let (failed, submitted) = match submit_batch(dev, queue, items, &mut up) { - Ok(result) => result, - Err(e) => { - if up.value == before { - put_back(key, up); - } else { - std::mem::forget(up); - } - return Err(e); - } - }; - if !submitted { - put_back(key, up); - return Ok(failed); - } - let copy_error = |e| format!("texture copy: {e}"); if let Err(e) = fence::wait(&up.fence, up.value, dev, None, 10_000) { // the GPU may still read the upload buffer and run the list: they stay alive (a fresh // uploader next time) – freeing them under the GPU removed the device @@ -364,54 +317,6 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items Ok(failed) } -pub(crate) struct UploadCompletion { - pub(crate) fence: ID3D12Fence, - pub(crate) value: u64, -} - -/// Submit an upload while retaining its resources in a bounded ring. The caller must enqueue a -/// wait for the returned fence value before work that consumes the uploaded textures. -pub unsafe fn upload_batch_queued( - dev: &ID3D12Device, - queue: &ID3D12CommandQueue, - items: &[(ID3D12Resource, Vec, Vec)], -) -> Result<(Vec<(usize, String)>, Option), String> { - if items.is_empty() { - return Ok((Vec::new(), None)); - } - let key = windows::core::Interface::as_raw(queue) as usize; - let mut pools = QUEUED_UPLOADERS.lock().unwrap(); - let slots = pools.get_or_insert_with(Default::default).entry(key).or_default(); - let choice = choose_slot(slots.len(), |index| { - fence::completed_value(&slots[index].fence, dev).is_ok_and(|value| value >= slots[index].value) - }); - let mut up = match choice { - SlotChoice::Reuse(index) => slots.remove(index).unwrap(), - SlotChoice::Grow => Uploader::new(dev)?, - SlotChoice::WaitOldest => { - let up = slots.pop_front().unwrap(); - if let Err(e) = fence::wait(&up.fence, up.value, dev, None, 10_000) { - slots.push_front(up); - return Err(format!("texture copy: {e}")); - } - up - } - }; - let result = submit_batch(dev, queue, items, &mut up); - match result { - Ok((failed, submitted)) => { - let completion = submitted.then(|| UploadCompletion { fence: up.fence.clone(), value: up.value }); - slots.push_back(up); - Ok((failed, completion)) - } - Err(e) => { - // The slot retains its allocator/list/staging even when submission or signaling failed. - slots.push_back(up); - Err(e) - } - } -} - fn put_back(key: usize, up: Uploader) { UPLOADERS.lock().unwrap().get_or_insert_with(Default::default).insert(key, up); } @@ -577,18 +482,6 @@ mod tests { use std::collections::HashMap; use windows::Win32::Graphics::Dxgi::Common::*; - #[test] - fn queued_upload_ring_reuses_completed_slots_before_growing() { - assert_eq!(choose_slot(0, |_| false), SlotChoice::Grow); - assert_eq!(choose_slot(2, |index| index == 1), SlotChoice::Reuse(1)); - assert_eq!(choose_slot(2, |_| false), SlotChoice::Grow); - } - - #[test] - fn queued_upload_ring_waits_for_the_oldest_slot_at_its_bound() { - assert_eq!(choose_slot(QUEUED_UPLOADER_SLOTS, |_| false), SlotChoice::WaitOldest); - } - fn image(format: u32, ty: ImageType, w: u32, h: u32, slices: u32, mips: u32, mode: u32, address: u64) -> Image { Image { address, diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index eb2de46ddc..6d97bc6e4e 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -827,7 +827,7 @@ unsafe fn refresh_once(queue: *mut c_void) { .collect() }); seed_stream_recheck(&todo, &ranges, recheck_frame); - upload_all(queue, todo); + upload_all(todo); } /// texture → `content_hash` of its memory at its last upload @@ -1088,7 +1088,7 @@ fn batch_fits(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_d } /// The uploads `todo`, in batches of up to `BATCH_BYTES` and `BATCH_ITEMS` (one list and one wait each). -unsafe fn upload_all(title_queue: *mut c_void, todo: Vec<(ID3D12Resource, Upload)>) { +unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { static N: AtomicU64 = AtomicU64::new(0); let warn = |e: &str| { if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -1140,7 +1140,7 @@ unsafe fn upload_all(title_queue: *mut c_void, todo: Vec<(ID3D12Resource, Upload } let d = device as *mut c_void; let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; - let upload_queue = match upload_queue(dev, device) { + let queue = match upload_queue(dev, device) { Ok(q) => q, Err(e) => { warn(&e); @@ -1148,29 +1148,13 @@ unsafe fn upload_all(title_queue: *mut c_void, todo: Vec<(ID3D12Resource, Upload } }; match own_work(|| { - super::vram::before_execute(&upload_queue); - texture::upload_batch_queued(dev, &upload_queue, &batch) + super::vram::before_execute(&queue); + texture::upload_batch(dev, &queue, &batch) }) { - Ok((failed, completion)) => { + Ok(failed) => { for (_, e) in failed { warn(&e); } - if let Some(done) = completion { - let dependency = match ID3D12CommandQueue::from_raw_borrowed(&title_queue) { - Some(title_queue) => title_queue.Wait(&done.fence, done.value).map(|()| { - super::list_x::note_internal_wait(title_queue.as_raw() as usize, "title texture uploads", &done.fence, done.value); - }).map_err(|e| format!("{e}")), - None => Err("title queue pointer is null".into()), - }; - if let Err(dependency) = dependency { - // An exceptional driver rejection still preserves visibility before the - // title submit; normal backpressure waits only when the ring is exhausted. - if let Err(wait) = crate::gpu::fence::wait(&done.fence, done.value, dev, None, 10_000) { - warn(&format!("title queue upload Wait failed ({dependency}); CPU fallback failed: {wait}")); - continue; - } - } - } UPLOADS.fetch_add(batch.len() as u64, Ordering::Relaxed); } Err(e) => warn(&e), From 68baa44afd86a0eeaf21b9acc5325987427d5799 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:08:36 -0800 Subject: [PATCH 047/265] D3D12.X: report allocator submission topology Measure outer executes, wait-split chunks, list and backing-mark writes, retirement Signal outcomes, and allocator-state lock wait/hold time without changing submission order or cadence. Publish the raw counters in preparation schema v3 and preserve v1/v2 comparison support.\n\nThe Windows-GNU probe reached XCL; this branch's base stopped on the since-corrected private PendingWait API. PowerShell tests could not run because PowerShell is unavailable.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 108 +++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/mod.rs | 5 ++ crates/xcl/src/hle/d3d12x/real.rs | 3 + crates/xcl/src/report.rs | 27 +++++- scripts/perf-compare.ps1 | 39 +++++++-- scripts/perf-compare.tests.ps1 | 42 +++++++-- 6 files changed, 206 insertions(+), 18 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..7a027a58bf 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -15,7 +15,9 @@ //! one recording, so no more allocators are put aside than there are lists. use std::collections::{HashMap, HashSet}; use std::ffi::c_void; -use std::sync::Mutex; +use std::ops::{Deref, DerefMut}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, MutexGuard}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -67,6 +69,94 @@ unsafe impl Send for State {} static STATE: Mutex> = Mutex::new(None); +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(default)] +pub struct AllocatorSubmitStats { + pub outer_execute_calls: u64, + pub chunks: u64, + pub multi_chunk_calls: u64, + pub forced_wait_boundaries: u64, + pub lists_marked: u64, + /// Backing mark-map insertions, including overwrites when lists share a backing. + pub backing_mark_writes: u64, + pub signal_attempts: u64, + pub signal_failures: u64, + pub state_lock_wait_ns: u64, + pub state_lock_hold_ns: u64, +} + +struct SubmitCounters { + outer_execute_calls: AtomicU64, + chunks: AtomicU64, + multi_chunk_calls: AtomicU64, + forced_wait_boundaries: AtomicU64, + lists_marked: AtomicU64, + backing_mark_writes: AtomicU64, + signal_attempts: AtomicU64, + signal_failures: AtomicU64, + state_lock_wait_ns: AtomicU64, + state_lock_hold_ns: AtomicU64, +} + +macro_rules! submit_counters { + ($($name:ident),+ $(,)?) => { + static SUBMIT: SubmitCounters = SubmitCounters { $($name: AtomicU64::new(0)),+ }; + + pub fn submit_stats() -> AllocatorSubmitStats { + AllocatorSubmitStats { $($name: SUBMIT.$name.load(Ordering::Relaxed)),+ } + } + }; +} + +submit_counters!( + outer_execute_calls, chunks, multi_chunk_calls, forced_wait_boundaries, + lists_marked, backing_mark_writes, signal_attempts, signal_failures, + state_lock_wait_ns, state_lock_hold_ns, +); + +fn add_duration(counter: &AtomicU64, elapsed: std::time::Duration) { + counter.fetch_add(elapsed.as_nanos().min(u64::MAX as u128) as u64, Ordering::Relaxed); +} + +struct SubmitStateGuard<'a> { + guard: MutexGuard<'a, Option>, + held: std::time::Instant, +} + +impl Deref for SubmitStateGuard<'_> { + type Target = Option; + fn deref(&self) -> &Self::Target { &self.guard } +} + +impl DerefMut for SubmitStateGuard<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { &mut self.guard } +} + +impl Drop for SubmitStateGuard<'_> { + fn drop(&mut self) { + add_duration(&SUBMIT.state_lock_hold_ns, self.held.elapsed()); + } +} + +fn lock_for_submit() -> SubmitStateGuard<'static> { + let waiting = std::time::Instant::now(); + let guard = STATE.lock().unwrap(); + add_duration(&SUBMIT.state_lock_wait_ns, waiting.elapsed()); + SubmitStateGuard { guard, held: std::time::Instant::now() } +} + +pub fn note_execute_call(chunks: usize) { + let (multi_chunk, boundaries) = execute_topology(chunks); + SUBMIT.outer_execute_calls.fetch_add(1, Ordering::Relaxed); + SUBMIT.chunks.fetch_add(chunks as u64, Ordering::Relaxed); + SUBMIT.multi_chunk_calls.fetch_add(multi_chunk, Ordering::Relaxed); + SUBMIT.forced_wait_boundaries.fetch_add(boundaries, Ordering::Relaxed); +} + +fn execute_topology(chunks: usize) -> (u64, u64) { + ((chunks > 1) as u64, chunks.saturating_sub(1) as u64) +} + /// `XCL_ALLOC_SWAP=0` turns it off. pub fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -153,7 +243,7 @@ pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize if !enabled() { return 0; } - let mut g = STATE.lock().unwrap(); + let mut g = lock_for_submit(); let Some(s) = g.as_mut() else { return 0 }; let mut found = 0; for &l in lists { @@ -192,7 +282,7 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { } // (every submit is marked, also of lists this module does not track – the PC lists behind // console lists – so note_resubmits sees them all) - let mut g = STATE.lock().unwrap(); + let mut g = lock_for_submit(); let s = g.get_or_insert_with(State::default); let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; let key = queue as usize; @@ -203,19 +293,25 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { } let (fence, value) = { let (f, v) = s.fences.get_mut(&key).unwrap(); + SUBMIT.signal_attempts.fetch_add(1, Ordering::Relaxed); if q.Signal(&*f, *v + 1).is_err() { + SUBMIT.signal_failures.fetch_add(1, Ordering::Relaxed); return; } *v += 1; (f.clone(), *v) }; + let mut backing_mark_writes = 0u64; for &l in lists { if let Some(&b) = s.of_list.get(&(l as usize)) { + backing_mark_writes += 1; s.backings.entry(b).or_default().marks.insert(key, (fence.clone(), value)); } let recording = s.recordings.get(&(l as usize)).copied().unwrap_or(0); s.last_submit.insert(l as usize, LastSubmit { queue: key, fence: fence.clone(), value, recording }); } + SUBMIT.lists_marked.fetch_add(lists.len() as u64, Ordering::Relaxed); + SUBMIT.backing_mark_writes.fetch_add(backing_mark_writes, Ordering::Relaxed); } /// Whether the GPU may still run a recording made on the title's allocator `alloc`. @@ -331,6 +427,12 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu mod tests { use super::*; + #[test] + fn execute_topology_counts_only_split_boundaries() { + assert_eq!(execute_topology(1), (0, 0)); + assert_eq!(execute_topology(4), (1, 3)); + } + #[test] fn a_spare_whose_reset_fails_stays_available_for_retry() { let (alloc, spare, list) = (0x1000usize, 0x2000usize, 0x3000usize); diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index c4553b9395..6c24260e3c 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -10,6 +10,7 @@ #![allow(non_snake_case)] mod alloc_pool; +pub use alloc_pool::AllocatorSubmitStats; mod build_queue; pub mod bind; pub mod console_heap; @@ -38,6 +39,10 @@ pub mod vram; use std::ffi::c_void; use std::sync::OnceLock; +pub fn allocator_submit_stats() -> AllocatorSubmitStats { + alloc_pool::submit_stats() +} + use crate::util::{HRESULT, S_OK}; /// data export: titles pass `&IID_ID3D12Device` to D3D12XboxCreateDevice / QueryInterface diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 49693bd907..b67fc53bab 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7354,7 +7354,9 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::list_x::note_queue_for_lists(this as usize, &mapped); let plan = super::list_x::submission_plan(&mapped); drop(preparation_stall); + let mut chunks = 0usize; let _ = super::list_x::execute_submission_plan_with_completions(this, &plan, &[], |chunk| { + chunks += 1; let lists = chunk.lists(); let _ = super::alloc_pool::note_resubmits(this, lists); f(this, lists.len() as u32, lists.as_ptr()); @@ -7362,6 +7364,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::alloc_pool::executed(this, lists); chunk.submit_effects(this) }); + super::alloc_pool::note_execute_call(chunks); // the next uploads into textures kept in step start from the states these lists leave super::title_textures::submitted(&mapped); super::present::note_execute(this, &mapped); diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index 3505442056..60612b592d 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize}; use crate::resolver::{self, Source}; pub const STALL_SUMMARY_VERSION: u32 = 1; -pub const PREPARATION_SUMMARY_VERSION: u32 = 2; +pub const PREPARATION_SUMMARY_VERSION: u32 = 3; #[derive(Debug, Serialize, Deserialize, Default)] pub struct StubCall { @@ -140,6 +140,8 @@ pub struct PreparationSummary { pub compute_build_coalescing: crate::hle::d3d12x::pso_async::ComputeCoalescingStats, #[serde(default)] pub ranked_preloads: crate::hle::d3d12x::pso_async::RankedPreloadStats, + #[serde(default)] + pub allocator_submits: crate::hle::d3d12x::AllocatorSubmitStats, } #[derive(Debug, Serialize, Deserialize, Default)] @@ -255,6 +257,7 @@ pub fn build() -> Report { version: PREPARATION_SUMMARY_VERSION, compute_build_coalescing: crate::hle::d3d12x::pso_async::compute_coalescing_stats(), ranked_preloads: crate::hle::d3d12x::pso_async::ranked_preload_stats(), + allocator_submits: crate::hle::d3d12x::allocator_submit_stats(), }), d3d12: crate::hle::d3d12x::real::stats(), audio: crate::hle::xaudio2::stats(), @@ -338,6 +341,18 @@ mod tests { started: 13, promoted: 4, }, + allocator_submits: crate::hle::d3d12x::AllocatorSubmitStats { + outer_execute_calls: 11, + chunks: 14, + multi_chunk_calls: 2, + forced_wait_boundaries: 3, + lists_marked: 37, + backing_mark_writes: 23, + signal_attempts: 14, + signal_failures: 1, + state_lock_wait_ns: 101, + state_lock_hold_ns: 202, + }, }; let json = serde_json::to_value(summary).unwrap(); assert_eq!(json["version"], PREPARATION_SUMMARY_VERSION); @@ -349,8 +364,16 @@ mod tests { assert_eq!(json["ranked_preloads"]["submissions"], 19); assert_eq!(json["ranked_preloads"]["started"], 13); assert_eq!(json["ranked_preloads"]["promoted"], 4); + assert_eq!(json["allocator_submits"]["outer_execute_calls"], 11); + assert_eq!(json["allocator_submits"]["state_lock_hold_ns"], 202); + + let mut version_two = json; + version_two["version"] = 2.into(); + version_two.as_object_mut().unwrap().remove("allocator_submits"); + let loaded: PreparationSummary = serde_json::from_value(version_two.clone()).unwrap(); + assert_eq!(loaded.allocator_submits, Default::default()); - let mut version_one = json; + let mut version_one = version_two; version_one["version"] = 1.into(); version_one.as_object_mut().unwrap().remove("ranked_preloads"); let loaded: PreparationSummary = serde_json::from_value(version_one).unwrap(); diff --git a/scripts/perf-compare.ps1 b/scripts/perf-compare.ps1 index c3a0b3a06f..99923a22f8 100644 --- a/scripts/perf-compare.ps1 +++ b/scripts/perf-compare.ps1 @@ -104,17 +104,17 @@ function Read-Preparation([string]$Root, [int]$Order, [string]$Label) { $mode = $Label.Substring(4) $report = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'report.json')) if (-not (Test-Path -LiteralPath $report -PathType Leaf)) { - return [ordered]@{ status = 'missing_report'; counters = $null; ranked_status = 'missing_report'; ranked = $null } + return [ordered]@{ status = 'missing_report'; counters = $null; ranked_status = 'missing_report'; ranked = $null; allocator_status = 'missing_report'; allocator = $null } } $json = Read-Json $report if (-not (Has-Property $json 'preparation') -or $null -eq $json.preparation) { - return [ordered]@{ status = 'missing_preparation'; counters = $null; ranked_status = 'missing_preparation'; ranked = $null } + return [ordered]@{ status = 'missing_preparation'; counters = $null; ranked_status = 'missing_preparation'; ranked = $null; allocator_status = 'missing_preparation'; allocator = $null } } $summary = $json.preparation $version = Read-Nonnegative-Integer $summary 'version' 'preparation version' if ($version -eq 0) { throw "malformed preparation version in $report" } - if ($version -ne 1 -and $version -ne 2) { - return [ordered]@{ status = 'unsupported_version'; counters = $null; ranked_status = 'unsupported_version'; ranked = $null } + if ($version -ne 1 -and $version -ne 2 -and $version -ne 3) { + return [ordered]@{ status = 'unsupported_version'; counters = $null; ranked_status = 'unsupported_version'; ranked = $null; allocator_status = 'unsupported_version'; allocator = $null } } if (-not (Has-Property $summary 'compute_build_coalescing') -or $null -eq $summary.compute_build_coalescing) { @@ -127,7 +127,7 @@ function Read-Preparation([string]$Root, [int]$Order, [string]$Label) { $counters[$name] = Read-Nonnegative-Integer $raw $name "preparation in $report" } if ($version -eq 1) { - return [ordered]@{ status = 'present'; counters = $counters; ranked_status = 'not_in_version'; ranked = $null } + return [ordered]@{ status = 'present'; counters = $counters; ranked_status = 'not_in_version'; ranked = $null; allocator_status = 'not_in_version'; allocator = $null } } if (-not (Has-Property $summary 'ranked_preloads') -or $null -eq $summary.ranked_preloads) { throw "malformed ranked preload counters in $report" @@ -136,7 +136,19 @@ function Read-Preparation([string]$Root, [int]$Order, [string]$Label) { foreach ($name in @('submissions', 'started', 'promoted')) { $ranked[$name] = Read-Nonnegative-Integer $summary.ranked_preloads $name "ranked preloads in $report" } - return [ordered]@{ status = 'present'; counters = $counters; ranked_status = 'present'; ranked = $ranked } + if ($version -eq 2) { + return [ordered]@{ status = 'present'; counters = $counters; ranked_status = 'present'; ranked = $ranked; allocator_status = 'not_in_version'; allocator = $null } + } + if (-not (Has-Property $summary 'allocator_submits') -or $null -eq $summary.allocator_submits) { + throw "malformed allocator submit counters in $report" + } + $allocator = [ordered]@{} + foreach ($name in @('outer_execute_calls', 'chunks', 'multi_chunk_calls', 'forced_wait_boundaries', + 'lists_marked', 'backing_mark_writes', 'signal_attempts', 'signal_failures', + 'state_lock_wait_ns', 'state_lock_hold_ns')) { + $allocator[$name] = Read-Nonnegative-Integer $summary.allocator_submits $name "allocator submits in $report" + } + return [ordered]@{ status = 'present'; counters = $counters; ranked_status = 'present'; ranked = $ranked; allocator_status = 'present'; allocator = $allocator } } function Number-Or-Null($Object, [string]$Name) { @@ -248,6 +260,10 @@ for ($i = 0; $i -lt 2; $i++) { $coalescingNames = @('keyed_submissions', 'coalescing_hits', 'unique_keyed_builds', 'current_in_flight', 'peak_in_flight') $coalescing = Compare-Counters $beforePreparation.counters $afterPreparation.counters $coalescingNames $rankedPreloads = Compare-Counters $beforePreparation.ranked $afterPreparation.ranked @('submissions', 'started', 'promoted') + $allocatorNames = @('outer_execute_calls', 'chunks', 'multi_chunk_calls', 'forced_wait_boundaries', + 'lists_marked', 'backing_mark_writes', 'signal_attempts', 'signal_failures', + 'state_lock_wait_ns', 'state_lock_hold_ns') + $allocatorSubmits = Compare-Counters $beforePreparation.allocator $afterPreparation.allocator $allocatorNames $comparison = [ordered]@{ label = $beforeRun.cache_state @@ -276,6 +292,11 @@ for ($i = 0; $i -lt 2; $i++) { candidate = $afterPreparation.ranked_status } ranked_preloads = $rankedPreloads + allocator_submits_status = [ordered]@{ + baseline = $beforePreparation.allocator_status + candidate = $afterPreparation.allocator_status + } + allocator_submits = $allocatorSubmits } $comparisons += $comparison @@ -300,6 +321,12 @@ for ($i = 0; $i -lt 2; $i++) { Write-Host " $($name): $(Display-Value $rankedPreloads.baseline.$name '') -> $(Display-Value $rankedPreloads.candidate.$name ''); delta $(Display-Value $rankedPreloads.delta.$name '')" } } + Write-Host " allocator submits: $($beforePreparation.allocator_status) -> $($afterPreparation.allocator_status)" + if ($beforePreparation.allocator_status -eq 'present' -or $afterPreparation.allocator_status -eq 'present') { + foreach ($name in $allocatorSubmits.delta.Keys) { + Write-Host " $($name): $(Display-Value $allocatorSubmits.baseline.$name '') -> $(Display-Value $allocatorSubmits.candidate.$name ''); delta $(Display-Value $allocatorSubmits.delta.$name '')" + } + } } [ordered]@{ diff --git a/scripts/perf-compare.tests.ps1 b/scripts/perf-compare.tests.ps1 index eedf659ee2..aa6d0093dd 100644 --- a/scripts/perf-compare.tests.ps1 +++ b/scripts/perf-compare.tests.ps1 @@ -26,7 +26,8 @@ function Write-Fixture([string]$Root, [string]$Commit, [int]$ColdMs, $WarmMs) { } function Write-Report([string]$Path, [int]$Count, [long]$Total, [long]$Maximum, - $Preparation = $null, [int]$PreparationVersion = 1, $RankedPreloads = $null, [switch]$ExtraKind) { + $Preparation = $null, [int]$PreparationVersion = 1, $RankedPreloads = $null, + $AllocatorSubmits = $null, [switch]$ExtraKind) { $aggregates = @( [ordered]@{ kind = 'dxc_compile'; count = $Count; total_ns = $Total; max_ns = $Maximum; histogram_log2_ns = @(0, $Count) } ) @@ -42,6 +43,9 @@ function Write-Report([string]$Path, [int]$Count, [long]$Total, [long]$Maximum, if ($null -ne $RankedPreloads) { $report['preparation']['ranked_preloads'] = $RankedPreloads } + if ($null -ne $AllocatorSubmits) { + $report['preparation']['allocator_submits'] = $AllocatorSubmits + } } $report | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $Path -Encoding utf8 @@ -54,8 +58,10 @@ try { $afterPreparation = [ordered]@{ keyed_submissions = 10; coalescing_hits = 6; unique_keyed_builds = 4; current_in_flight = 1; peak_in_flight = 5 } $beforeRanked = [ordered]@{ submissions = 20; started = 15; promoted = 3 } $afterRanked = [ordered]@{ submissions = 24; started = 20; promoted = 2 } - Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation 2 $beforeRanked - Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind + $beforeAllocator = [ordered]@{ outer_execute_calls = 10; chunks = 13; multi_chunk_calls = 2; forced_wait_boundaries = 3; lists_marked = 40; backing_mark_writes = 20; signal_attempts = 13; signal_failures = 1; state_lock_wait_ns = 100; state_lock_hold_ns = 500 } + $afterAllocator = [ordered]@{ outer_execute_calls = 12; chunks = 14; multi_chunk_calls = 1; forced_wait_boundaries = 2; lists_marked = 44; backing_mark_writes = 22; signal_attempts = 14; signal_failures = 0; state_lock_wait_ns = 80; state_lock_hold_ns = 450 } + Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation 3 $beforeRanked $beforeAllocator + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator -ExtraKind [ordered]@{ d3d12 = [ordered]@{} } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $baseline 'runs\02-warm\report.json') -Encoding utf8 $json = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json @@ -87,12 +93,24 @@ try { $ranked.baseline.promoted -ne 3 -or $ranked.candidate.promoted -ne 2 -or $ranked.delta.submissions -ne 4 -or $ranked.delta.started -ne 5 -or $ranked.delta.promoted -ne -1) { throw 'ranked preload counters, status, or deltas are wrong' } + $allocator = $json.runs[0].allocator_submits + if ($json.runs[0].allocator_submits_status.baseline -ne 'present' -or + $json.runs[0].allocator_submits_status.candidate -ne 'present' -or + $allocator.baseline.outer_execute_calls -ne 10 -or $allocator.candidate.outer_execute_calls -ne 12 -or + $allocator.delta.chunks -ne 1 -or $allocator.delta.multi_chunk_calls -ne -1 -or + $allocator.delta.lists_marked -ne 4 -or $allocator.delta.backing_mark_writes -ne 2 -or + $allocator.delta.state_lock_hold_ns -ne -50) { + throw 'allocator submit counters, status, or deltas are wrong' + } if ($json.runs[1].preparation_status.baseline -ne 'missing_preparation' -or $json.runs[1].preparation_status.candidate -ne 'missing_report' -or $null -ne $json.runs[1].compute_build_coalescing.delta.keyed_submissions -or $json.runs[1].ranked_preloads_status.baseline -ne 'missing_preparation' -or $json.runs[1].ranked_preloads_status.candidate -ne 'missing_report' -or - $null -ne $json.runs[1].ranked_preloads.delta.submissions) { + $null -ne $json.runs[1].ranked_preloads.delta.submissions -or + $json.runs[1].allocator_submits_status.baseline -ne 'missing_preparation' -or + $json.runs[1].allocator_submits_status.candidate -ne 'missing_report' -or + $null -ne $json.runs[1].allocator_submits.delta.chunks) { throw 'missing preparation data was treated as zero' } if (($json | ConvertTo-Json -Depth 12) -match '"(percent|percentage|ratio|significance|significant)"\s*:') { @@ -106,18 +124,24 @@ try { $versionOne.runs[0].compute_build_coalescing.candidate.coalescing_hits -ne 6 -or $versionOne.runs[0].ranked_preloads_status.baseline -ne 'not_in_version' -or $versionOne.runs[0].ranked_preloads_status.candidate -ne 'not_in_version' -or + $versionOne.runs[0].allocator_submits_status.baseline -ne 'not_in_version' -or + $versionOne.runs[0].allocator_submits_status.candidate -ne 'not_in_version' -or $null -ne $versionOne.runs[0].ranked_preloads.delta.started) { throw 'version 1 preparation support regressed' } Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation 2 $beforeRanked Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind - Write-Report (Join-Path $candidate 'runs\02-warm\report.json') 1 1 1 $afterPreparation 3 + Write-Report (Join-Path $candidate 'runs\02-warm\report.json') 1 1 1 $afterPreparation 4 $unsupported = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json - if ($unsupported.runs[1].preparation_status.candidate -ne 'unsupported_version' -or + if ($unsupported.runs[0].allocator_submits_status.baseline -ne 'not_in_version' -or + $unsupported.runs[0].allocator_submits_status.candidate -ne 'not_in_version' -or + $unsupported.runs[1].preparation_status.candidate -ne 'unsupported_version' -or $unsupported.runs[1].ranked_preloads_status.candidate -ne 'unsupported_version' -or + $unsupported.runs[1].allocator_submits_status.candidate -ne 'unsupported_version' -or $null -ne $unsupported.runs[1].compute_build_coalescing.candidate -or - $null -ne $unsupported.runs[1].ranked_preloads.candidate) { + $null -ne $unsupported.runs[1].ranked_preloads.candidate -or + $null -ne $unsupported.runs[1].allocator_submits.candidate) { throw 'unsupported preparation version was not preserved as a state' } @@ -142,6 +166,10 @@ try { $refused = $false try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed preparation' } if (-not $refused) { throw 'a malformed preparation counter was not refused' } + Write-Report $badReportPath 3 80 40 $afterPreparation 3 $afterRanked -ExtraKind + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed allocator submit' } + if (-not $refused) { throw 'missing version 3 allocator submit counters were not refused' } Write-Report $badReportPath 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json From 88ea49677f9b100fcd529ed583af04a107bf4d68 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:09:06 -0800 Subject: [PATCH 048/265] D3D12.X: reduce unrelated write-watch scanning Use an 8 MiB merge gap derived from measured GetWriteWatch call and committed-page scan costs. This preserves merging of 1 MiB-spaced sparse ranges while avoiding scans across as much as 64 MiB of irrelevant pages; boundary and coverage invariants are tested.\n\nThe Windows-target test build stopped before XCL compilation because this Linux host lacks MSVC headers.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 53 ++++++++++++++++++--- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 25a71253ea..d03b409b89 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1397,11 +1397,11 @@ unsafe fn upload_queue(dev: &ID3D12Device, device: usize) -> Result 0 && regions.iter().any(|&(rbase, rsize)| rbase <= base && end <= rbase + rsize), "range {base:#x}..{end:#x} is outside one allocation"); + } + for &(start, end) in &wanted { + for &(rbase, rsize) in ®ions { + let (lo, hi) = (start.max(rbase), end.min(rbase + rsize)); + if lo < hi { + assert!(ranges.iter().any(|&(base, size)| base <= lo && hi <= base + size), "wanted part {lo:#x}..{hi:#x} is not covered"); + } + } + } + } + /// The textures of a batch detiled on several threads come back as on one: complete and in /// order (2D with mips and slices, 3D, BC7, a tiny one; more textures than threads). #[test] From cf40395a13d72c18c4f6936b2cffc27b4bafe590 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:10:06 -0800 Subject: [PATCH 049/265] D3D12.X: reserve allocator state before submission Add a BeginSubmit-to-PendingSubmit typestate that captures and pins exact list lifetime, recording, and allocator backing before native execution. Safe pre-execute abandonment unpins; once armed, drop or marker failure deliberately remains fail-closed, while successful finish converts pins into existing per-queue marks.\n\nThe Windows-GNU check reached and type-checked this code; the branch base then stopped on the since-corrected private PendingWait API.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 312 +++++++++++++++++++++++- 1 file changed, 310 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..0b7acf84be 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -28,11 +28,13 @@ struct Backing { users: HashSet, /// queue → (fence, value after the last submit of one of them) marks: HashMap, + /// Submits reserved before ExecuteCommandLists whose completion is not marked yet. + submit_pins: usize, } impl Backing { unsafe fn free(&self) -> bool { - self.users.is_empty() && self.marks.values().all(|(f, v)| f.GetCompletedValue() >= *v) + self.users.is_empty() && self.submit_pins == 0 && self.marks.values().all(|(f, v)| f.GetCompletedValue() >= *v) } } @@ -53,7 +55,12 @@ struct State { last_submit: HashMap, /// PC list → recordings so far (a Reset or creation starts the next one) recordings: HashMap, + /// PC list → object lifetime, so a late reservation cannot mark a reused address. + list_lifetimes: HashMap, + next_list_lifetime: u64, resubmits: u64, + /// (PC list, object lifetime) → reserved submits not yet associated with a queue fence. + submit_pins: HashMap<(usize, u64), usize>, } struct LastSubmit { @@ -67,6 +74,157 @@ unsafe impl Send for State {} static STATE: Mutex> = Mutex::new(None); +#[derive(Clone, Copy)] +struct SubmitEntry { + list: usize, + backing: Option, + recording: u64, + lifetime: u64, +} + +/// A fail-closed reservation made before native ExecuteCommandLists. Dropping it before +/// `execution_possible` releases the reservation because no GPU work can refer to it yet. +#[must_use] +pub(super) struct BeginSubmit { + entries: Vec, +} + +/// A reservation armed immediately before native execution. Once armed, execution may begin at +/// any point, so dropping it before `finish` deliberately leaves its allocator and lists pinned. +#[must_use] +pub(super) struct PendingSubmit { + entries: Vec, +} + +fn release_submit_pins(s: &mut State, entries: &[SubmitEntry]) { + for entry in entries { + let key = (entry.list, entry.lifetime); + if let Some(n) = s.submit_pins.get_mut(&key) { + *n -= 1; + if *n == 0 { + s.submit_pins.remove(&key); + } + } + if let Some(backing) = entry.backing.and_then(|b| s.backings.get_mut(&b)) { + backing.submit_pins = backing.submit_pins.saturating_sub(1); + } + } +} + +fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &ID3D12Fence, value: u64) { + for entry in entries { + if let Some(backing) = entry.backing { + s.backings.entry(backing).or_default().marks.insert(queue, (fence.clone(), value)); + } + if s.list_lifetimes.get(&entry.list) == Some(&entry.lifetime) { + s.last_submit.insert( + entry.list, + LastSubmit { queue, fence: fence.clone(), value, recording: entry.recording }, + ); + } + } + release_submit_pins(s, entries); +} + +/// Capture and pin the exact backing and recording that a native submit will execute. The caller +/// must keep this token until it knows ExecuteCommandLists cannot have run, or convert it with +/// `execution_possible` immediately before making the native call. +pub(super) fn begin_submit(lists: &[*mut c_void]) -> Option { + if !enabled() { + return Some(BeginSubmit { entries: Vec::new() }); + } + let mut entries = Vec::new(); + entries.try_reserve(lists.len()).ok()?; + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.list_lifetimes.try_reserve(lists.len()).ok()?; + s.submit_pins.try_reserve(lists.len()).ok()?; + for &list in lists { + let list = list as usize; + if entries.iter().any(|entry: &SubmitEntry| entry.list == list) { + continue; + } + let lifetime = match s.list_lifetimes.get(&list) { + Some(&lifetime) => lifetime, + None => { + s.next_list_lifetime = s.next_list_lifetime.wrapping_add(1).max(1); + s.list_lifetimes.insert(list, s.next_list_lifetime); + s.next_list_lifetime + } + }; + entries.push(SubmitEntry { + list, + backing: s.of_list.get(&list).copied(), + recording: s.recordings.get(&list).copied().unwrap_or(0), + lifetime, + }); + } + for entry in &entries { + *s.submit_pins.entry((entry.list, entry.lifetime)).or_default() += 1; + if let Some(backing) = entry.backing { + s.backings.get_mut(&backing).unwrap().submit_pins += 1; + } + } + Some(BeginSubmit { entries }) +} + +impl BeginSubmit { + /// Arm immediately before calling native ExecuteCommandLists. From this point onward, any + /// unwind, drop, or completion-mark failure must retain the reservation permanently. + pub(super) fn execution_possible(mut self) -> PendingSubmit { + PendingSubmit { entries: std::mem::take(&mut self.entries) } + } +} + +impl Drop for BeginSubmit { + fn drop(&mut self) { + if !self.entries.is_empty() { + if let Some(s) = STATE.lock().unwrap().as_mut() { + release_submit_pins(s, &self.entries); + } + } + } +} + +impl PendingSubmit { + /// Associate the captured submit with the queue's existing retirement fence. `false` leaves + /// all reservations permanently pinned: execution may have happened but cannot be retired. + pub(super) unsafe fn finish(mut self, queue: *mut c_void) -> bool { + if self.entries.is_empty() { + return true; + } + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return false }; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return false }; + let key = queue as usize; + if !s.fences.contains_key(&key) { + let mut dev: Option = None; + let Some(fence) = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()) else { + return false; + }; + s.fences.insert(key, (fence, 0)); + } + let (fence, value) = { + let (fence, value) = s.fences.get_mut(&key).unwrap(); + if q.Signal(&*fence, *value + 1).is_err() { + return false; + } + *value += 1; + (fence.clone(), *value) + }; + record_submit(s, &self.entries, key, &fence, value); + self.entries.clear(); + true + } + + #[cfg(test)] + fn finish_with_mark(mut self, queue: usize, fence: &ID3D12Fence, value: u64) { + let mut g = STATE.lock().unwrap(); + record_submit(g.as_mut().unwrap(), &self.entries, queue, fence, value); + self.entries.clear(); + } +} + /// `XCL_ALLOC_SWAP=0` turns it off. pub fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -91,6 +249,9 @@ pub(super) fn forget_list(list: usize) { let Some(s) = g.as_mut() else { return }; s.last_submit.remove(&list); s.recordings.remove(&list); + if let Some(lifetime) = s.list_lifetimes.remove(&list) { + s.submit_pins.remove(&(list, lifetime)); + } if let Some(backing) = s.of_list.remove(&list) { if let Some(b) = s.backings.get_mut(&backing) { b.users.remove(&list); @@ -182,7 +343,14 @@ pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize /// submitted again before that; `title_list` records the title's next recording elsewhere). pub fn in_flight(list: usize) -> bool { let g = STATE.lock().unwrap(); - g.as_ref().and_then(|s| s.last_submit.get(&list)).is_some_and(|l| unsafe { l.fence.GetCompletedValue() } < l.value) + let Some(s) = g.as_ref() else { return false }; + s.list_lifetimes + .get(&list) + .and_then(|&lifetime| s.submit_pins.get(&(list, lifetime))) + .copied() + .unwrap_or(0) + != 0 + || s.last_submit.get(&list).is_some_and(|l| unsafe { l.fence.GetCompletedValue() } < l.value) } /// `lists` were just submitted to `queue`. @@ -331,6 +499,146 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu mod tests { use super::*; + #[test] + fn submit_reservation_keeps_pre_reset_attribution_across_queues() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + + #[repr(C)] + struct Fence { + vtable: *const usize, + value: Cell, + refs: Cell, + } + unsafe extern "system" fn completed(this: *mut c_void) -> u64 { + (*this.cast::()).value.get() + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let fence = &*this.cast::(); + fence.refs.set(fence.refs.get() + 1); + fence.refs.get() + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let fence = &*this.cast::(); + fence.refs.set(fence.refs.get() - 1); + fence.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + + const SLOT: usize = size_of::(); + let mut vtable = [unexpected_call as usize; size_of::() / SLOT]; + vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + let mut fence_object = Fence { vtable: vtable.as_ptr(), value: Cell::new(0), refs: Cell::new(1) }; + let fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut fence_object).cast()) }; + + let (alloc, next, list) = (0x7ffe_5100usize, 0x7ffe_5200usize, 0x7ffe_5300usize); + created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let first = begin_submit(&[list as *mut c_void, list as *mut c_void]).unwrap().execution_possible(); + let cross_queue = begin_submit(&[list as *mut c_void]).unwrap().execution_possible(); + assert!(in_flight(list)); + let reset = std::thread::spawn(move || { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.aside.insert(alloc, vec![next]); + s.backings.insert(next, Backing::default()); + unsafe { + title_reset_in(s, alloc as *mut c_void, |candidate| { + assert_eq!(candidate as usize, next); + 0 + }) + } + }) + .join() + .unwrap(); + assert_eq!(reset, Some(0), "the reserved backing is put aside instead of Reset"); + assert_eq!(reset_list(list, alloc, -1, |backing| { + assert_eq!(backing, next); + 0 + }), 0); + let second = begin_submit(&[list as *mut c_void]).unwrap().execution_possible(); + + first.finish_with_mark(0x71, &fence, 3); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.backings[&alloc].marks.get(&0x71).unwrap().1, 3); + assert!(!s.backings[&next].marks.contains_key(&0x71)); + assert_eq!(s.submit_pins.get(&(list, s.list_lifetimes[&list])), Some(&2)); + assert_eq!(s.last_submit[&list].recording, 1); + } + cross_queue.finish_with_mark(0x72, &fence, 4); + second.finish_with_mark(0x73, &fence, 5); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.backings[&alloc].marks.get(&0x71).unwrap().1, 3); + assert_eq!(s.backings[&alloc].marks.get(&0x72).unwrap().1, 4); + assert_eq!(s.backings[&next].marks.get(&0x73).unwrap().1, 5); + assert!(!s.submit_pins.contains_key(&(list, s.list_lifetimes[&list]))); + assert_eq!(s.last_submit[&list].recording, 2); + } + let released = begin_submit(&[list as *mut c_void]).unwrap().execution_possible(); + forget_list(list); + created_on(list, next, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let reused_address = begin_submit(&[list as *mut c_void]).unwrap(); + released.finish_with_mark(0x74, &fence, 6); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.backings[&next].marks.get(&0x74).unwrap().1, 6); + assert!(!s.last_submit.contains_key(&list), "a late mark cannot resurrect a released list address"); + assert_eq!(s.submit_pins.get(&(list, s.list_lifetimes[&list])), Some(&1)); + } + drop(reused_address); + forget_list(list); + unsafe { forget(alloc) }; + drop(fence); + assert_eq!(fence_object.refs.get(), 0); + } + + #[test] + fn submit_reservation_drop_and_failure_are_fail_closed() { + let (alloc, list) = (0x7ffe_5400usize, 0x7ffe_5500usize); + created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + + let before_execute = begin_submit(&[list as *mut c_void, list as *mut c_void]).unwrap(); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.submit_pins.get(&(list, s.list_lifetimes[&list])), Some(&1), "duplicates reserve once"); + assert_eq!(s.backings[&alloc].submit_pins, 1); + } + drop(before_execute); + assert!(!in_flight(list), "a reservation abandoned before Execute is released"); + + let armed_for_execute = begin_submit(&[list as *mut c_void]).unwrap().execution_possible(); + drop(armed_for_execute); + assert!(in_flight(list), "an armed execution stays pinned without a completion mark"); + let failed_finish = begin_submit(&[list as *mut c_void]).unwrap().execution_possible(); + assert!(!unsafe { failed_finish.finish(std::ptr::null_mut()) }); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.submit_pins.get(&(list, s.list_lifetimes[&list])), Some(&2)); + assert_eq!(s.backings[&alloc].submit_pins, 2); + } + + // Final list cleanup removes its recording hold but cannot make the backing reusable + // after execution became possible without a completion mark. + forget_list(list); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(!s.backings[&alloc].users.contains(&list)); + assert!(!s.submit_pins.keys().any(|&(p, _)| p == list), "a released address is not pinned against a later object"); + assert!(!unsafe { s.backings[&alloc].free() }); + s.backings.get_mut(&alloc).unwrap().submit_pins = 0; + } + unsafe { forget(alloc) }; + } + #[test] fn a_spare_whose_reset_fails_stays_available_for_retry() { let (alloc, spare, list) = (0x1000usize, 0x2000usize, 0x3000usize); From b7cf80703d2deadfe0f5d3bfd652c2462754b10b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:11:13 -0800 Subject: [PATCH 050/265] README: document allocator submission diagnostics Describe the raw allocator execute topology, retirement Signal, mark-write, and lock timing counters emitted by performance comparisons.\n\nAssisted-by: Codex (GPT-5.6-sol) --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e094d7c564..55d08b3c56 100644 --- a/README.md +++ b/README.md @@ -365,9 +365,10 @@ Compare two completed artifact folders without modifying them: The console shows raw cold/warm duration, exit/timeout state, stall totals/counts/maxima, the five compute-build coalescing counters, and ranked-preload submissions, starts and promotions. The -redirected JSON keeps those values, raw deltas, and stall log2 histograms. Missing reports or -preparation summaries and unsupported preparation versions remain explicit states; they are not -treated as zero. The tool +allocator section also reports execute/chunk topology, retirement-signal outcomes, mark writes and +allocator-state lock timing. The redirected JSON keeps those values, raw deltas, and stall log2 +histograms. Missing reports or preparation summaries and unsupported preparation versions remain +explicit states; they are not treated as zero. The tool refuses different workload fingerprints or identity algorithm/versions, run order, requested duration, runtime environment, system, GPU, or GPU driver. Missing reports and stall summaries are labelled as missing; it does not infer significance or percentages. From 396a4144ff312f102fd0efe2d3a1b19d8bbaa35a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:23:54 -0800 Subject: [PATCH 051/265] D3D12.X: share zero-mip upload staging Zero-filled lazy mip uploads previously reserved and populated a separate staging footprint for every texture in a batch. Reuse one fully cleared, maximally pitched span for verified-zero subresources while preserving every copy, title-queue mapping order, and nonzero footprint alignment. Adapted from xcl-dev/xcl PR #2573 commit 1bfa05d9214cf5f68e602233072d8786fd3c529a by razormontana. Cross-target cargo check passed; Windows GPU execution was not available on this host. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 2 + crates/xcl/src/gpu/texture.rs | 250 +++++++++++++++++--- crates/xcl/src/hle/d3d12x/title_textures.rs | 60 +++-- 3 files changed, 267 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 55d08b3c56..557265dfb7 100644 --- a/README.md +++ b/README.md @@ -285,6 +285,8 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder those on which the GPU completed at least one operation. For each, it names the translated pipeline bound at the last operation DRED saw complete and those bound after it, by their console shaders' hashes (`cs`, `vs` / `ps`, `ms` / `ps`, `vs` / `gs` / `ps`). +- `XCL_TEXTURE_LEVEL_PAGES=1` gives sampled title textures backing as their mip levels stream in. + Zero-filled mip uploads in a batch share one staging span and still clear any mapped tiles. - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget (`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order. diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index e3fa9fa1a4..4a6159ea1d 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -263,11 +263,24 @@ impl Uploader { } } +pub(crate) type UploadBatchItem = (ID3D12Resource, Vec, Vec); + /// Several uploads on one list, one wait: (resource, subresources, states) each – the states /// the texture is in and is left in: one for every subresource, or one per subresource (D3D12 /// order). A failure of one is returned with its index; the others still run. The texels go /// through the queue's kept upload buffer (`Uploader`). pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { + upload_batch_with_zero_mips(dev, queue, items, &[]) +} + +/// As `upload_batch`, with an optional mask per item for subresources already verified to be all +/// zero. The copies still run, but these subresources all source the same zeroed staging span. +pub(crate) unsafe fn upload_batch_with_zero_mips( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + items: &[UploadBatchItem], + zero_mips: &[Vec], +) -> Result, String> { if items.is_empty() { return Ok(Vec::new()); } @@ -278,17 +291,18 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items None => Uploader::new(dev)?, }; // where each texture's texels go in the upload buffer - let (failed, planned, total) = plan_batch(dev, items); + let (failed, planned, zero) = plan_batch(dev, items, zero_mips)?; if planned.is_empty() { put_back(key, up); return Ok(failed); } - let (staging, mapped) = up.staging(dev, total)?; + let (staging, mapped) = up.staging(dev, zero.end)?; + clear_staging_span(mapped, &zero); up.alloc.Reset().map_err(err)?; up.list.Reset(&up.alloc, None).map_err(err)?; - for (k, l, base) in &planned { - let (res, subs, states) = &items[*k]; - record_into(&up.list, res, subs, l, states, states, &staging, mapped, *base); + for (k, l, offsets) in planned { + let (res, subs, states) = &items[k]; + record_into(&up.list, res, subs, &l, states, states, &staging, mapped, offsets); } up.list.Close().map_err(err)?; queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&up.list).map_err(err)?)]); @@ -305,21 +319,38 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items Ok(failed) } -unsafe fn plan_batch(dev: &ID3D12Device, items: &[(ID3D12Resource, Vec, Vec)]) -> (Vec<(usize, String)>, Vec<(usize, Layout, u64)>, u64) { +unsafe fn plan_batch<'a>( + dev: &ID3D12Device, + items: &[UploadBatchItem], + zero_mips: &'a [Vec], +) -> Result<(Vec<(usize, String)>, Vec<(usize, Layout, StagingOffsets<'a>)>, std::ops::Range), String> { let mut failed = Vec::new(); - let mut planned = Vec::with_capacity(items.len()); - let mut total = 0u64; + let mut laid_out = Vec::with_capacity(items.len()); for (k, (res, subs, states)) in items.iter().enumerate() { + let zeros = zero_mips.get(k).map(Vec::as_slice).unwrap_or_default(); match layout(dev, res, subs, states, states) { - Ok(l) => { - let base = total.div_ceil(PLACEMENT) * PLACEMENT; - total = base + l.total; - planned.push((k, l, base)); - } + Ok(l) if zeros.is_empty() || zeros.len() == l.fps.len() => laid_out.push((k, l, zeros)), + Ok(_) => failed.push((k, "texture upload zero mask does not match its subresources".into())), + Err(e) => failed.push((k, e)), + } + } + // A lone valid zero source cannot share and reserving its last row's padding could grow + // staging. Count after validation so a failed item cannot enable that padded path. + let share_zeros = laid_out.iter().flat_map(|(_, _, zeros)| *zeros).filter(|&&zero| zero).nth(1).is_some(); + let mut planned = Vec::with_capacity(laid_out.len()); + let mut storage = BatchStaging::default(); + for (k, mut l, zeros) in laid_out { + let zeros = if share_zeros { zeros } else { &[] }; + match storage.add(&mut l, zeros) { + Ok(base) => planned.push((k, l, StagingOffsets { base, zero: 0, zero_mips: zeros })), Err(e) => failed.push((k, e)), } } - (failed, planned, total) + let zero = storage.zero_span()?; + for (_, _, offsets) in &mut planned { + offsets.zero = zero.start; + } + Ok((failed, planned, zero)) } pub struct InFlight { @@ -330,23 +361,33 @@ pub struct InFlight { } pub unsafe fn submit_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result<(Vec<(usize, String)>, Option), String> { - let (failed, planned, bytes) = plan_batch(dev, items); + submit_batch_with_zero_mips(dev, queue, items, &[]) +} + +pub(crate) unsafe fn submit_batch_with_zero_mips( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + items: &[UploadBatchItem], + zero_mips: &[Vec], +) -> Result<(Vec<(usize, String)>, Option), String> { + let (failed, planned, zero) = plan_batch(dev, items, zero_mips)?; if planned.is_empty() { return Ok((failed, None)); } let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(err)?; let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; - let staging = buffer(dev, bytes)?; + let staging = buffer(dev, zero.end)?; let mut mapped = std::ptr::null_mut(); staging.Map(0, None, Some(&mut mapped)).map_err(err)?; - for (k, layout, base) in &planned { - let (res, subs, states) = &items[*k]; - record_into(&list, res, subs, layout, states, states, &staging, mapped as *mut u8, *base); + clear_staging_span(mapped as *mut u8, &zero); + for (k, layout, offsets) in planned { + let (res, subs, states) = &items[k]; + record_into(&list, res, subs, &layout, states, states, &staging, mapped as *mut u8, offsets); } staging.Unmap(0, None); list.Close().map_err(err)?; queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]); - Ok((failed, Some(InFlight { _alloc: alloc, _list: list, _staging: staging, bytes }))) + Ok((failed, Some(InFlight { _alloc: alloc, _list: list, _staging: staging, bytes: zero.end }))) } fn put_back(key: usize, up: Uploader) { @@ -374,7 +415,7 @@ pub unsafe fn record_upload_states( let up = buffer(dev, l.total)?; let mut p = std::ptr::null_mut(); up.Map(0, None, Some(&mut p)).map_err(err)?; - record_into(list, res, subs, &l, before, after, &up, p as *mut u8, 0); + record_into(list, res, subs, &l, before, after, &up, p as *mut u8, StagingOffsets::default()); up.Unmap(0, None); Ok(up) } @@ -387,6 +428,83 @@ struct Layout { total: u64, } +#[derive(Default)] +struct BatchStaging { + data_bytes: u64, + zero_bytes: u64, +} + +impl BatchStaging { + /// Keep the driver's dimensions and pitches. Only repack offsets when an item can share the + /// zero span. Each ordinary footprint keeps at least the byte range supplied by the driver. + fn add(&mut self, l: &mut Layout, zeros: &[bool]) -> Result { + let overflow = || "texture upload staging size overflow".to_string(); + if !zeros.is_empty() && zeros.len() != l.fps.len() { + return Err("texture upload zero mask does not match its subresources".into()); + } + let base = self.data_bytes.checked_next_multiple_of(PLACEMENT).ok_or_else(overflow)?; + let mut next = l.total; + let mut zero_bytes = self.zero_bytes; + if zeros.contains(&true) { + next = 0; + for (k, &zero) in zeros.iter().enumerate() { + let fp = l.fps[k]; + let end = l.fps.get(k + 1).map_or(l.total, |next| next.Offset); + let bytes = end.checked_sub(fp.Offset).ok_or_else(overflow)?; + if zero { + // Zero full pitched rows, including padding on the last row of each slice. + let pitched_bytes = u64::from(fp.Footprint.RowPitch) + .checked_mul(u64::from(l.rows[k])) + .and_then(|bytes| bytes.checked_mul(u64::from(fp.Footprint.Depth))) + .ok_or_else(overflow)?; + zero_bytes = zero_bytes.max(pitched_bytes.max(bytes)); + } else { + let at = next.checked_next_multiple_of(PLACEMENT).ok_or_else(overflow)?; + next = at.checked_add(bytes).ok_or_else(overflow)?; + l.fps[k].Offset = at; + } + } + } + self.data_bytes = base.checked_add(next).ok_or_else(overflow)?; + self.zero_bytes = zero_bytes; + Ok(base) + } + + fn zero_span(&self) -> Result, String> { + if self.zero_bytes == 0 { + return Ok(self.data_bytes..self.data_bytes); + } + let overflow = || "texture upload staging size overflow".to_string(); + let start = self.data_bytes.checked_next_multiple_of(PLACEMENT).ok_or_else(overflow)?; + let end = start.checked_add(self.zero_bytes).ok_or_else(overflow)?; + Ok(start..end) + } +} + +/// The mapped staging buffer covers `span`, which can contain data from an earlier batch. +unsafe fn clear_staging_span(mapped: *mut u8, span: &std::ops::Range) { + if !span.is_empty() { + mapped.add(span.start as usize).write_bytes(0, (span.end - span.start) as usize); + } +} + +#[derive(Default)] +struct StagingOffsets<'a> { + base: u64, + zero: u64, + zero_mips: &'a [bool], +} + +impl StagingOffsets<'_> { + fn is_zero(&self, sub: usize) -> bool { + self.zero_mips.get(sub) == Some(&true) + } + + fn at(&self, sub: usize, offset: u64) -> u64 { + if self.is_zero(sub) { self.zero } else { self.base + offset } + } +} + /// The `Layout` of uploading `subs` into `res`, checked against the resource. unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES]) -> Result { validate_subresources(subs)?; @@ -403,6 +521,9 @@ unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], let mut row_bytes = vec![0u64; n]; let mut total = 0u64; dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); + if total == u64::MAX { + return Err("invalid texture copy footprints".into()); + } for (i, ((s, fp), (&nrows, &nbytes))) in subs.iter().zip(&fps).zip(rows.iter().zip(&row_bytes)).enumerate() { if s.rows != nrows as usize || s.depth != fp.Footprint.Depth as usize || s.row_bytes != nbytes as usize { return Err(format!( @@ -414,20 +535,23 @@ unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], Ok(Layout { fps, rows, total }) } -/// Write `subs` into the mapped upload buffer `up` (`mapped`) from `base` (a multiple of -/// D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT) as `l` places them, and record their copies into -/// `res` on `list` (barriers from `before` and back to `after`). +/// Write `subs` into the mapped upload buffer `up` (`mapped`) where `l` and `offsets` place them, +/// and record every copy into `res` on `list` (barriers from `before` and back to `after`). #[allow(clippy::too_many_arguments)] -unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], l: &Layout, before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], up: &ID3D12Resource, mapped: *mut u8, base: u64) { +unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], l: &Layout, before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], up: &ID3D12Resource, mapped: *mut u8, offsets: StagingOffsets<'_>) { let n = subs.len(); - for ((s, fp), &nrows) in subs.iter().zip(&l.fps).zip(&l.rows) { + for (k, ((s, fp), &nrows)) in subs.iter().zip(&l.fps).zip(&l.rows).enumerate() { + if offsets.is_zero(k) { + continue; + } + let start = offsets.at(k, fp.Offset) as usize; let pitch = fp.Footprint.RowPitch as usize; let row = s.row_bytes.min(pitch); // depth slices are NumRows rows apart (rows of 4×4 blocks for BCn) let slice_pitch = pitch * nrows as usize; for z in 0..(fp.Footprint.Depth as usize).min(s.depth) { for y in 0..(nrows as usize).min(s.rows) { - let at = base as usize + fp.Offset as usize + z * slice_pitch + y * pitch; + let at = start + z * slice_pitch + y * pitch; std::ptr::copy_nonoverlapping(s.data[(z * s.rows + y) * s.row_bytes..].as_ptr(), mapped.add(at), row); } } @@ -442,7 +566,7 @@ unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, su Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 }, }; - let placed = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: base + fp.Offset, Footprint: fp.Footprint }; + let placed = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: offsets.at(k, fp.Offset), Footprint: fp.Footprint }; let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(up), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: placed } }; list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); } @@ -514,6 +638,76 @@ mod tests { use std::collections::HashMap; use windows::Win32::Graphics::Dxgi::Common::*; + #[test] + fn shared_zero_mip_staging_compacts_and_clears_the_full_span() { + // A 1024² R8 texture with five mips, including the driver's row and placement alignment. + let layout = || Layout { + fps: [0, 1_048_576, 1_310_720, 1_376_256, 1_409_024].into_iter() + .zip([1024, 512, 256, 128, 64]) + .map(|(offset, width)| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8_UNORM, + Width: width, + Height: width, + Depth: 1, + RowPitch: width.max(256), + }, + }).collect(), + rows: vec![1024, 512, 256, 128, 64], + total: 1_425_216, + }; + let zeros = [true, false, false, false, false]; + let mut original = BatchStaging::default(); + let mut shared = BatchStaging::default(); + let mut items = Vec::new(); + for _ in 0..8 { + original.add(&mut layout(), &[]).unwrap(); + let mut l = layout(); + let base = shared.add(&mut l, &zeros).unwrap(); + items.push((l, base)); + } + let old = original.zero_span().unwrap(); + let zero = shared.zero_span().unwrap(); + assert!(old.is_empty()); + assert_eq!(old.end, 11_403_072); + assert_eq!(zero.end, 4_063_232); + assert_eq!(staging_capacity(old.end), Some(16 << 20)); + assert_eq!(staging_capacity(zero.end), Some(4 << 20)); + for (l, base) in items { + let offsets = StagingOffsets { base, zero: zero.start, zero_mips: &zeros }; + assert_eq!(offsets.at(0, l.fps[0].Offset), zero.start); + for (k, fp) in l.fps.iter().enumerate().skip(1) { + let at = offsets.at(k, fp.Offset); + assert_eq!(at % PLACEMENT, 0); + assert!(at + u64::from(fp.Footprint.RowPitch * l.rows[k]) <= zero.start); + assert_eq!(fp.Footprint, layout().fps[k].Footprint); + } + } + + // A fully zero footprint uses whole pitched rows, including the last row of the + // last slice, even when GetCopyableFootprints reports a shorter last row. + let mut volume = Layout { + fps: vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8_UNORM, Width: 13, Height: 2, Depth: 3, RowPitch: 256, + }, + }], + rows: vec![2], + total: 5 * 256 + 13, + }; + let mut volume_batch = BatchStaging { data_bytes: 268, zero_bytes: 0 }; + volume_batch.add(&mut volume, &[true]).unwrap(); + let zero = volume_batch.zero_span().unwrap(); + assert_eq!(zero, 512..2048); + let mut bytes = vec![0x72; 2049]; + unsafe { clear_staging_span(bytes.as_mut_ptr(), &zero); } + assert!(bytes[..512].iter().all(|&b| b == 0x72)); + assert!(bytes[512..2048].iter().all(|&b| b == 0)); + assert_eq!(bytes[2048], 0x72); + } + fn image(format: u32, ty: ImageType, w: u32, h: u32, slices: u32, mips: u32, mode: u32, address: u64) -> Image { Image { address, diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d03b409b89..d44a31152d 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1126,13 +1126,18 @@ unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u } } -unsafe fn submit_on_title_queue(dev: &ID3D12Device, queue: &ID3D12CommandQueue, batch: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { +unsafe fn submit_on_title_queue( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + batch: &[texture::UploadBatchItem], + zero_mips: &[Vec], +) -> Result, String> { // The textures' tile mappings made since the title queue last waited for them (a texture // made on another thread after `refresh_once`'s wait, or its levels mapped just now by // `map_levels_with_texels`): a copy into a tile still unmapped is a copy-engine page fault // on NVIDIA (`DmaPageFaultWrite`), as the upload queue's own path already waits for. super::vram::before_execute(queue); - let (failed, f) = texture::submit_batch(dev, queue, batch)?; + let (failed, f) = texture::submit_batch_with_zero_mips(dev, queue, batch, zero_mips)?; let Some(f) = f else { return Ok(failed) }; let mut g = ON_QUEUE.lock().unwrap(); let key = queue.as_raw() as usize; @@ -1204,20 +1209,22 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12C } let subs = subresources_of_all(&picked, bytes); let mut batch = Vec::with_capacity(picked.len()); + let mut zero_mips = Vec::new(); + let level_pages = super::vram::level_pages(); for ((r, va, _, states), subs) in picked.into_iter().zip(subs) { if super::present::trace_frame() { note_content(va, &r, &subs); } - if super::vram::level_pages() { + if level_pages { // (the queue waits for these mappings before the copies: `vram::before_execute` below) - map_levels_with_texels(&r, &subs); + zero_mips.push(map_levels_with_texels(&r, &subs)); } batch.push((r, subs, states)); } let d = device as *mut c_void; let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; if let Some(tq) = title_queue_for(dev, title) { - match own_work(|| submit_on_title_queue(dev, &tq, &batch)) { + match own_work(|| submit_on_title_queue(dev, &tq, &batch, &zero_mips)) { Ok(failed) => { for (_, e) in failed { warn(&e); @@ -1237,7 +1244,7 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12C }; match own_work(|| { super::vram::before_execute(&queue); - texture::upload_batch(dev, &queue, &batch) + texture::upload_batch_with_zero_mips(dev, &queue, &batch, &zero_mips) }) { Ok(failed) => { for (_, e) in failed { @@ -1252,17 +1259,18 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12C /// (`vram::level_pages`) Before an upload of title texture `r`: its levels with texels in `subs` /// (its subresources as they go up) get their video memory pages if they have none - a texture -/// placed with lazy levels; any other: nothing to do. A level of zeros has no texels: a streamed -/// texture's larger levels before the title has memory behind them (read as zeros, -/// `read_committed`). It keeps no pages, reads as zeros as it would with them, and its copy goes -/// to tiles that are not mapped, which drops it (tiled resources tier 2). -unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) { +/// placed with lazy levels. Return a mask of zero levels so their copies can share staging. +/// A level of zeros needs no new pages. Its copy still clears any existing tiles, including a +/// previously streamed level or tiles mapped for other levels in the same packed tail. +unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) -> Vec { if !super::vram::has_lazy_levels(r.as_raw() as usize) { - return; + return Vec::new(); } // (one slice: its subresources are its levels) - let present: Vec = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); + let zero: Vec = subs.iter().map(|s| all_zero(&s.data)).collect(); + let present: Vec = zero.iter().enumerate().filter_map(|(i, &zero)| (!zero).then_some(i as u32)).collect(); super::vram::map_levels(r, Some(&present)); + zero } /// Whether every byte of `b` is zero (eight at a time: gigabytes a second where it is). @@ -1673,7 +1681,7 @@ mod tests { let key = queue.as_raw() as usize; let upload = |value: u8| { let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![value; 64 * 64] }]; - own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); }; for value in [0x21, 0xC4] { upload(value); @@ -1724,7 +1732,7 @@ mod tests { ).unwrap(); let texture: ID3D12Resource = texture.unwrap(); let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x3C; 64 * 64] }]; - own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); assert_eq!( super::super::vram::waited_for_test(raw_device as usize, key), mapped, @@ -1760,7 +1768,7 @@ mod tests { let texture: ID3D12Resource = texture.unwrap(); let key = queue.as_raw() as usize; let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x77; 64 * 64] }]; - own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); { let mut g = ON_QUEUE.lock().unwrap(); let q = g.get_mut(&key).unwrap(); @@ -2669,7 +2677,8 @@ mod tests { /// first upload, then pages for those levels only and their texels right, zeros where there /// are none. With memory under the largest level too, a texture placed there again (as a /// title does) takes that level's pages - the others are shared - and holds all of it. A - /// texture the GPU writes gets the pages of all its levels. + /// texture the GPU writes gets the pages of all its levels. A mapped level also clears when + /// the CPU's next upload sources zeros from shared staging. #[test] fn a_placed_texture_gets_the_pages_of_a_level_with_its_texels() { let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); @@ -2795,6 +2804,23 @@ mod tests { note_gpu_write(small.as_raw() as usize); assert_eq!(dev_pages() - p0, (all as usize) << 16, "the same pages"); assert!(read_sub(&small, 0) == want[0].data, "a GPU-written texture has pages under all its levels"); + std::ptr::write_bytes((at + top) as *mut u8, 0, size - top); + let cpu = std::slice::from_raw_parts_mut(at as *mut u8, chain.slice_bytes); + chain.tile_level(cpu, 10, 0, &vec![0u8; want[10].data.len()]); + // The synthetic allocation here is not write-watched. Queue the normal batch update. + { + let mut t = TEXTURES.lock().unwrap(); + let e = t.by_res.get_mut(&(full.as_raw() as usize)).unwrap(); + assert!(!e.pending, "the preceding refresh uploaded this texture"); + e.pending = true; + adjust_pending(1); + } + refresh(queue.as_raw()); + assert_eq!(dev_pages() - p0, (all as usize) << 16, "clearing a level keeps its backing"); + assert!(read_sub(&full, 0).iter().all(|&b| b == 0), "the previously streamed level was cleared"); + assert!(read_sub(&full, 10).iter().all(|&b| b == 0), "a small level sharing the zero span was cleared"); + assert!(read_sub(&full, 1) == want[1].data, "a nonzero mip kept its texels"); + assert!(read_sub(&full, 9) == want[9].data, "the small level's neighbour kept its texels"); super::super::vram::LEVEL_PAGES_FOR_TEST.store(false, Ordering::Relaxed); drop((small, full)); VirtualFree(at as *mut c_void, 0, MEM_RELEASE); From 2e45718bf16517f2ecf503da14c2cf055686a432 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 07:59:57 +0300 Subject: [PATCH 052/265] Recompiler: serialize dxc::wait_for_memory slot admission wait_for_memory previously checked WORKING against commit headroom and WANTED_AT_ONCE with an unlocked load before calling fetch_add(1), allowing concurrent worker wakeups to admit an unbounded burst past both limits. Wrap the admission check and working-slot increment in a MemoryGate mutex while keeping MemorySlot::drop lock-free and sleeping outside the mutex, and add multi-threaded unit tests verifying tight-headroom, WANTED_AT_ONCE, low-commit single-slot, and timeout behavior. Part of #2463 Part of #1566 Part of #1269 Assisted-by: Antigravity (Gemini 4 Hydrogen) --- crates/xcl/src/gpu/recomp/dxc.rs | 187 +++++++++++++++++++++++++++---- 1 file changed, 168 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index ae9d017343..dbf8fb24d7 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -519,17 +519,62 @@ pub fn set_memory_reserve(gb: u64) { } /// Compiles running on the DXC workers (`wait_for_memory` lets them in). -static WORKING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +struct MemoryGate { + gate: Mutex<()>, + working: std::sync::atomic::AtomicUsize, +} + +impl MemoryGate { + const fn new() -> Self { + Self { gate: Mutex::new(()), working: std::sync::atomic::AtomicUsize::new(0) } + } + + /// Evaluates commit headroom and `WANTED_AT_ONCE` atomically with `working` admission so + /// concurrent worker wakeups cannot admit a burst past either cap. + fn try_admit(&self, reserve_bytes: u64, avail: impl FnOnce() -> Option, timed_out: bool, wanted: &Wanted) -> bool { + let _guard = self.gate.lock().unwrap_or_else(|e| e.into_inner()); + let cur = self.working.load(Ordering::Acquire); + let need = reserve_bytes.saturating_add((cur as u64) << 30); + let plenty = avail().is_none_or(|a| a >= need); + if plenty || timed_out || cur == 0 || (cur < WANTED_AT_ONCE && wanted()) { + self.working.fetch_add(1, Ordering::AcqRel); + return true; + } + false + } + + /// Waits until [`Self::try_admit`] grants a slot, sleeping outside the gate mutex. + fn wait_with(&self, reserve_bytes: u64, mut avail: impl FnMut() -> Option, timeout: std::time::Duration, wanted: &Wanted) { + let start = std::time::Instant::now(); + while !self.try_admit(reserve_bytes, &mut avail, start.elapsed() >= timeout, wanted) { + std::thread::sleep(std::time::Duration::from_millis(50)); + } + } + + fn release(&self) { + self.working.fetch_sub(1, Ordering::AcqRel); + } +} + +static MEMORY_GATE: MemoryGate = MemoryGate::new(); /// A compile let in by `wait_for_memory`, until it is dropped. pub struct MemorySlot; impl Drop for MemorySlot { fn drop(&mut self) { - WORKING.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + MEMORY_GATE.release(); } } +/// Available page-file commit bytes from Windows, or `None` if the query fails. +fn avail_page_file() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPageFile) +} + /// Before a compile: with 6 GB of commit left or more, plus 1 GB for every compile already /// running (each can still grow to ~0.7 GB), at once; with less, one compile at a /// time – it goes when no other is running (and after a minute in any case). Each compile used @@ -539,23 +584,8 @@ impl Drop for MemorySlot { /// of its threads waited for cold compiles, four of which stood in this queue, until its watchdog /// ended it. pub fn wait_for_memory(wanted: &Wanted) -> MemorySlot { - use std::sync::atomic::Ordering; - use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; - let start = std::time::Instant::now(); - loop { - let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; - m.dwLength = std::mem::size_of::() as u32; - let need = (RESERVE_GB.load(Ordering::Relaxed) << 30) + ((WORKING.load(Ordering::Acquire) as u64) << 30); - let plenty = unsafe { GlobalMemoryStatusEx(&mut m) } == 0 || m.ullAvailPageFile >= need; - if plenty || start.elapsed().as_secs() >= 60 || (WORKING.load(Ordering::Acquire) < WANTED_AT_ONCE && wanted()) { - WORKING.fetch_add(1, Ordering::AcqRel); - return MemorySlot; - } - if WORKING.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire).is_ok() { - return MemorySlot; - } - std::thread::sleep(std::time::Duration::from_millis(50)); - } + MEMORY_GATE.wait_with(RESERVE_GB.load(Ordering::Relaxed) << 30, avail_page_file, std::time::Duration::from_secs(60), wanted); + MemorySlot } /// DXC workers (`compile_threads`, each with its own compiler and a `DXC_STACK` stack), started @@ -1759,3 +1789,122 @@ mod accessor_library_tests { assert!(!gate.close()); } } + +#[cfg(test)] +mod memory_gate_tests { + use super::*; + use std::sync::atomic::AtomicUsize; + use std::sync::Barrier; + use std::time::Duration; + + #[test] + fn tight_commit_headroom_bounds_concurrent_admissions() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let avail_gb = 7u64 << 30; // fits working == 0 (6 GiB) and working == 1 (7 GiB), not 2 (8 GiB) + let threads = 16; + let barrier = Barrier::new(threads); + let admitted = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| false); + barrier.wait(); + if gate.try_admit( + reserve, + || { + std::thread::sleep(Duration::from_millis(2)); + Some(avail_gb) + }, + false, + &wanted, + ) { + admitted.fetch_add(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(admitted.load(Ordering::SeqCst), 2, "burst admitted more compiles than commit headroom allows"); + assert_eq!(gate.working.load(Ordering::SeqCst), 2); + } + + #[test] + fn wanted_burst_never_exceeds_wanted_at_once() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let low_avail = 1u64 << 30; + let threads = 16; + let barrier = Barrier::new(threads); + let admitted = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| { + std::thread::sleep(Duration::from_millis(2)); + true + }); + barrier.wait(); + if gate.try_admit(reserve, || Some(low_avail), false, &wanted) { + admitted.fetch_add(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(admitted.load(Ordering::SeqCst), WANTED_AT_ONCE, "wanted burst exceeded WANTED_AT_ONCE"); + assert_eq!(gate.working.load(Ordering::SeqCst), WANTED_AT_ONCE); + } + + #[test] + fn wait_for_memory_drains_concurrent_waiters_within_cap() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let low_avail = 1u64 << 30; + let threads = 12; + let barrier = Barrier::new(threads); + let active = AtomicUsize::new(0); + let max_active = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| true); + barrier.wait(); + gate.wait_with(reserve, || Some(low_avail), Duration::from_secs(60), &wanted); + let cur = active.fetch_add(1, Ordering::SeqCst) + 1; + max_active.fetch_max(cur, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(25)); + active.fetch_sub(1, Ordering::SeqCst); + gate.release(); + }); + } + }); + let peak = max_active.load(Ordering::SeqCst); + assert!(peak <= WANTED_AT_ONCE, "peak concurrent slots {peak} exceeded WANTED_AT_ONCE ({WANTED_AT_ONCE})"); + assert_eq!(gate.working.load(Ordering::SeqCst), 0); + } + + #[test] + fn low_commit_unwanted_admits_only_one_progress_slot() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let low_avail = 1u64 << 30; + let threads = 8; + let barrier = Barrier::new(threads); + let admitted = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| false); + barrier.wait(); + if gate.try_admit(reserve, || Some(low_avail), false, &wanted) { + admitted.fetch_add(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(admitted.load(Ordering::SeqCst), 1, "only one progress compile may run when commit is short and unwanted"); + assert_eq!(gate.working.load(Ordering::SeqCst), 1); + let wanted: Wanted = Box::new(|| false); + assert!(gate.try_admit(reserve, || Some(low_avail), true, &wanted), "timed-out waiter must still admit"); + assert_eq!(gate.working.load(Ordering::SeqCst), 2); + } +} From e67817e4808bcda0d990804fcbe1f4d4997212eb Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 08:01:10 +0300 Subject: [PATCH 053/265] Recompiler: stream gpu::effects without Vec/HashSet and avoid copying compute blobs Replace Vec + HashSet in gpu::effects::of with a single-pass streaming decoder over sorted instruction PCs, delegating to an explicit far-jump path only when S_SETPC_B64 appears. Add early-exit on memory writes and zero-copy slice borrowing for FSPX and FSSM compute shaders in big_and_image_only. Part of #2508 Part of #1833 Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/effects.rs | 232 ++++++++++++++++++++++++++++------ 1 file changed, 196 insertions(+), 36 deletions(-) diff --git a/crates/xcl/src/gpu/effects.rs b/crates/xcl/src/gpu/effects.rs index 4fe79eb859..8703febfb8 100644 --- a/crates/xcl/src/gpu/effects.rs +++ b/crates/xcl/src/gpu/effects.rs @@ -21,16 +21,70 @@ pub struct Effects { pub instructions: usize, } -/// The writes of the RDNA2 program `code` (one program, as `xbox::Fssm::programs` cuts it). -/// None when the program cannot be decoded through a terminator, falls through past decoded -/// code, contains an unresolved indirect transfer, or branches outside the decoded instructions. -pub fn of(code: &[u8]) -> Option { - let mut insts = Vec::new(); +fn update_writes(e: &mut Effects, d: &rdna2::Decoded) { + let n = d.inst.name; + let writes = n.contains("_STORE") || n.contains("_ATOMIC"); + match d.enc.name { + "ENC_MIMG" => e.images |= writes, + "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_SMEM" => e.memory |= writes, + // LDS is the group's own and gone after it; the global data share is not + "ENC_DS" => { + let gds = rdna2::field_value(d.enc, &d.words, "GDS").is_some_and(|v| v != 0); + e.memory |= gds || n == "DS_APPEND" || n == "DS_CONSUME" || n == "DS_ORDERED_COUNT" || n.starts_with("DS_GWS_"); + } + _ => {} + } +} + +fn analyze(code: &[u8], stop_on_memory: bool) -> Option { + let cap = if stop_on_memory { (code.len() / 6).min(256) } else { code.len() / 6 }; + let mut pcs = Vec::with_capacity(cap); + let mut targets = Vec::new(); let mut off = 0; // the whole program: code can follow an early terminator (a branch to it, or past it); what // does not decode (or S_CODE_END padding) after one is taken for trailing data, unless a // decoded branch still targets past it or the tail falls through into it let mut ended = false; + let mut last_ok_end = false; + let mut e = Effects::default(); + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { + if ended { + break; + } + return None; + }; + if ended && d.inst.name == "S_CODE_END" { + break; + } + if d.inst.name == "S_SETPC_B64" { + return analyze_with_far_jumps(code, stop_on_memory); + } + if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 { + targets.push(rdna2::branch_target(&d)?); + } + off += d.len; + let term = d.inst.flags & rdna2::F_TERMINATOR != 0; + ended |= term; + last_ok_end = term || d.inst.name == "S_BRANCH"; + e.instructions += 1; + update_writes(&mut e, &d); + if stop_on_memory && e.memory { + return None; + } + pcs.push(d.pc); + } + if !ended || !last_ok_end || !targets.iter().all(|t| pcs.binary_search(t).is_ok()) { + return None; + } + Some(e) +} + +fn analyze_with_far_jumps(code: &[u8], stop_on_memory: bool) -> Option { + let mut insts = Vec::with_capacity(code.len() / 6); + let mut off = 0; + let mut ended = false; + let mut e = Effects::default(); while off + 4 <= code.len() { let Ok(d) = rdna2::decode(&code[off..], off as u64) else { if ended { @@ -43,6 +97,11 @@ pub fn of(code: &[u8]) -> Option { } off += d.len; ended |= d.inst.flags & rdna2::F_TERMINATOR != 0; + e.instructions += 1; + update_writes(&mut e, &d); + if stop_on_memory && e.memory { + return None; + } insts.push(d); } if !ended { @@ -53,42 +112,25 @@ pub fn of(code: &[u8]) -> Option { if last.inst.flags & rdna2::F_TERMINATOR == 0 && last.inst.name != "S_BRANCH" && last.far_target.is_none() { return None; } - let pcs: std::collections::HashSet = insts.iter().map(|d| d.pc).collect(); - let mut e = Effects::default(); for d in &insts { - if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 && rdna2::branch_target(d).is_none_or(|t| !pcs.contains(&t)) { + if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 + && rdna2::branch_target(d).is_none_or(|t| insts.binary_search_by_key(&t, |x| x.pc).is_err()) + { return None; } - e.instructions += 1; - let n = d.inst.name; - let writes = n.contains("_STORE") || n.contains("_ATOMIC"); - match d.enc.name { - "ENC_MIMG" => e.images |= writes, - "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_SMEM" => e.memory |= writes, - // LDS is the group's own and gone after it; the global data share is not - "ENC_DS" => { - let gds = rdna2::field_value(d.enc, &d.words, "GDS").is_some_and(|v| v != 0); - e.memory |= gds || n == "DS_APPEND" || n == "DS_CONSUME" || n == "DS_ORDERED_COUNT" || n.starts_with("DS_GWS_"); - } - _ => {} - } } Some(e) } -/// The compute program of a console shader container (the hardware CS variant of an FSSM, or -/// an FSPX driver container), as the translators take it. -fn compute_code(blob: &[u8]) -> Option> { - if let Some(f) = recomp::pso::fspx(blob) { - return Some(f.code.to_vec()); - } - let sh = xbox::parse(blob)?; - let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; - if f.error.is_some() { - return None; - } - let p = f.programs.first()?; - Some(f.data.get(p.offset..p.offset.checked_add(p.len)?)?.to_vec()) +/// The writes of the RDNA2 program `code` (one program, as `xbox::Fssm::programs` cuts it). +/// None when the program cannot be decoded through a terminator, falls through past decoded +/// code, contains an unresolved indirect transfer, or branches outside the decoded instructions. +pub fn of(code: &[u8]) -> Option { + analyze(code, false) +} + +fn is_big_image_only_code(code: &[u8]) -> bool { + code.len() >= BIG_CODE && analyze(code, true).is_some() } /// Console code a compute program needs to be `big`: 16 KiB, about 4 000 instructions. The @@ -100,8 +142,17 @@ pub const BIG_CODE: usize = 16 << 10; /// title can do without for the frames its pipeline takes to build. False for anything that /// cannot be read. pub fn big_and_image_only(blob: &[u8]) -> bool { - let Some(code) = compute_code(blob) else { return false }; - code.len() >= BIG_CODE && of(&code).is_some_and(|e| !e.memory) + if let Some(f) = recomp::pso::fspx(blob) { + return is_big_image_only_code(f.code); + } + let Some(sh) = xbox::parse(blob) else { return false }; + let Some(f) = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)) else { return false }; + if f.error.is_some() { + return false; + } + let Some(p) = f.programs.first() else { return false }; + let Some(end) = p.offset.checked_add(p.len) else { return false }; + f.data.get(p.offset..end).is_some_and(is_big_image_only_code) } #[cfg(test)] @@ -255,4 +306,113 @@ mod tests { assert!(sh.fssm[0].error.is_some() && !sh.fssm[0].programs.is_empty()); assert!(!big_and_image_only(&errored)); } + + fn of_reference(code: &[u8]) -> Option { + let (mut insts, mut off, mut ended) = (Vec::new(), 0, false); + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { if ended { break; } return None; }; + if ended && d.inst.name == "S_CODE_END" { break; } + off += d.len; ended |= d.inst.flags & rdna2::F_TERMINATOR != 0; insts.push(d); + } + if !ended { return None; } + rdna2::resolve_far_jumps(&mut insts); + let last = insts.last()?; + if last.inst.flags & rdna2::F_TERMINATOR == 0 && last.inst.name != "S_BRANCH" && last.far_target.is_none() { return None; } + let pcs: std::collections::HashSet = insts.iter().map(|d| d.pc).collect(); + let mut e = Effects::default(); + for d in &insts { + if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 && rdna2::branch_target(d).is_none_or(|t| !pcs.contains(&t)) { return None; } + e.instructions += 1; update_writes(&mut e, d); + } + Some(e) + } + + fn fspx_blob(code: &[u8]) -> Vec { + let mut head = [0u8; 0x20]; + for o in [0x0C, 0x0E, 0x10] { head[o..o + 2].copy_from_slice(&1u16.to_le_bytes()); } + let mut accc = [b"FSPX".as_slice(), &[0; 4], &2u32.to_le_bytes(), &[0; 4]].concat(); + for w in [0u32, 0x30, 0x20, 0, 6, 0x50, (0x24 + code.len()) as u32, 0] { accc.extend_from_slice(&w.to_le_bytes()); } + accc.extend_from_slice(&head); accc.extend_from_slice(&[0u8; 0x24]); accc.extend_from_slice(code); + let mut out = [b"DXBC".as_slice(), &[0; 16]].concat(); + for w in [1u32, (44 + accc.len()) as u32, 1, 36] { out.extend_from_slice(&w.to_le_bytes()); } + out.extend_from_slice(b"ACCC"); out.extend_from_slice(&(accc.len() as u32).to_le_bytes()); out.extend_from_slice(&accc); + out + } + + #[test] + fn streaming_matches_reference_of_across_edge_cases() { + let store: (&str, &str, &[(&str, u64)]) = ("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("SRSRC", 2)]); + let setpc: (&str, &str, &[(&str, u64)]) = ("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 0)]); + let swappc: (&str, &str, &[(&str, u64)]) = ("S_SWAPPC_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 0)]); + let call_ok: (&str, &str, &[(&str, u64)]) = ("S_CALL_B64", "ENC_SOPK", &[("SDST", 0), ("SIMM16", 0)]); + let code_end: (&str, &str, &[(&str, u64)]) = ("S_CODE_END", "ENC_SOPP", &[]); + let oob_br: (&str, &str, &[(&str, u64)]) = ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 9)]); + let getpc: (&str, &str, &[(&str, u64)]) = ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 0)]); + let add16: (&str, &str, &[(&str, u64)]) = ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 128 + 16)]); + let addc0: (&str, &str, &[(&str, u64)]) = ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)]); + let mut cases = vec![ + Vec::new(), + [asm(&[store]), vec![0xff; 8]].concat(), + asm(&[store, oob_br, END]), + asm(&[store, END, code_end]), + asm(&[IMAGE_STORE, END, store, END]), + asm(&[getpc, add16, addc0, setpc, END, IMAGE_STORE, END]), + asm(&[IMAGE_STORE, END, getpc, ("S_SUB_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 128 + 16)]), ("S_SUBB_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)]), setpc]), + asm(&[getpc, ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 128 + 64)]), addc0, setpc, END]), + asm(&[getpc, add16, addc0, setpc, END, store, END]), + asm(&[store, getpc, add16, addc0, setpc, END, IMAGE_STORE, END]), + asm(&[IMAGE_STORE, swappc, END]), + asm(&[IMAGE_STORE, call_ok, END]), + ]; + assert_eq!(of(&cases[6]), Some(Effects { memory: false, images: true, instructions: 6 })); + let pool = [asm(&[MOV]), asm(&[IMAGE_STORE]), asm(&[store]), asm(&[END]), asm(&[code_end]), asm(&[("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0)])]), asm(&[oob_br]), asm(&[setpc])]; + let mut rng = 0x9E37_79B9_7F4A_7C15u64; + for _ in 0..64 { + let mut s = Vec::new(); + for _ in 0..16 { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; s.extend_from_slice(&pool[(rng as usize) % pool.len()]); } + cases.push(s); + } + for c in &cases { + let want = of_reference(c); + assert_eq!(of(c), want); + assert_eq!(analyze(c, true).is_some(), want.is_some_and(|e| !e.memory)); + } + + let (mov, small) = (asm(&[MOV]), asm(&[IMAGE_STORE, END])); + assert!(!big_and_image_only(&xbox::tests::sample(5, &[xbox::tests::fssm(&small, &[(6, 0)])]))); + assert!(!big_and_image_only(&fspx_blob(&small))); + let mut big_img = Vec::with_capacity(BIG_CODE + 16); + while big_img.len() < BIG_CODE { big_img.extend_from_slice(&mov); } + big_img.extend(asm(&[IMAGE_STORE, END])); + let mut big_mem = asm(&[store]); + while big_mem.len() < BIG_CODE { big_mem.extend_from_slice(&mov); } + big_mem.extend(asm(&[END])); + assert!(big_and_image_only(&fspx_blob(&big_img)) && !big_and_image_only(&fspx_blob(&big_mem)) && !big_and_image_only(&fspx_blob(&big_img)[..40])); + assert!(big_and_image_only(&xbox::tests::sample(5, &[xbox::tests::fssm(&big_img, &[(6, 0)])])) && !big_and_image_only(&xbox::tests::sample(5, &[xbox::tests::fssm(&big_mem, &[(6, 0)])]))); + + if !cfg!(debug_assertions) { + fn bench(iters: u32, mut f: impl FnMut() -> bool) -> (f64, u32) { + let (t0, mut acc) = (std::time::Instant::now(), 0u32); + for _ in 0..iters { acc += u32::from(std::hint::black_box(f())); } + (t0.elapsed().as_micros() as f64 / iters as f64, acc) + } + let (mut img_100k, mut mem_100k) = (Vec::with_capacity(100_016), asm(&[store])); + while img_100k.len() < 100_000 { img_100k.extend_from_slice(&mov); } + img_100k.extend(asm(&[IMAGE_STORE, END])); + while mem_100k.len() < 100_000 { mem_100k.extend_from_slice(&mov); } + mem_100k.extend(asm(&[END])); + let (blob_img, blob_mem) = (xbox::tests::sample(5, &[xbox::tests::fssm(&img_100k, &[(6, 0)])]), xbox::tests::sample(5, &[xbox::tests::fssm(&mem_100k, &[(6, 0)])])); + let ref_big = |blob: &[u8]| { + let sh = xbox::parse(blob)?; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; + let p = f.programs.first()?; + let c = f.data.get(p.offset..p.offset.checked_add(p.len)?)?.to_vec(); + Some(c.len() >= BIG_CODE && of_reference(&c).is_some_and(|e| !e.memory)) + }; + let ((ib, a1), (ia, a2)) = (bench(50, || ref_big(&blob_img).unwrap_or(false)), bench(50, || big_and_image_only(&blob_img))); + let ((mb, b1), (ma, b2)) = (bench(50, || ref_big(&blob_mem).unwrap_or(false)), bench(50, || big_and_image_only(&blob_mem))); + assert_eq!((a1, a2, b1, b2), (50, 50, 0, 0)); + println!("EFFECTS_BENCH_US img_100k: before={ib:.1} after={ia:.1} | mem_100k: before={mb:.1} after={ma:.1}"); + } + } } From b0deef15ae41288fbc03049b15f29ae45cf42c6f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:29:57 -0800 Subject: [PATCH 054/265] D3D12.X: clamp descriptor publication to heap bounds Descriptor range publication could continue past small heaps and partial tail pages into adjacent shared-heap ranges. Carry the source heap's remaining slot count into the resolved slot and clamp the existing zero-allocation publication loop without changing its lock coverage. Adapted from the bounds portion of xcl-dev/xcl PR #2631 commit 3b49f094ec06e7f7a8c1f6d085b42f62382390bf by Decodere. The PR's lock-removal portion is intentionally excluded because it permits range reuse before a delayed copy. Cross-target cargo check for library and tests passed; Windows execution was unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/console_heap.rs | 94 ++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 2 +- 2 files changed, 92 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 4862abd84c..81ce117ed0 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -429,6 +429,8 @@ pub struct Slot { pub shared_srv: u64, /// the slot's number in its heap pub k: u32, + /// slots from this one through the end of its heap + pub remaining: u32, } /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot @@ -448,7 +450,7 @@ pub fn slot(cpu: u64) -> Option { // shared heap must map overflowed slots to reserved zero-sampler slot 0 rather than // aliasing unrelated heap entries at local index `k`. let (index, shared_srv) = shared.unwrap_or_else(|| (sampler_unmapped_index(!h.pages.is_empty(), k), 0)); - return Some(Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k }); + return Some(Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k, remaining: h.n - k }); } let uav = ((2 * k + 1) * h.inc) as u64; let shared = page_of(h, k).and_then(|(first, k0)| { @@ -458,7 +460,7 @@ pub fn slot(cpu: u64) -> Option { Some((i, g.gpu + (i as u64 + 1) * g.inc as u64, g.cpu + i as u64 * g.inc as u64)) }); let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or((2 * k, if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0)); - Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k }) + Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k, remaining: h.n - k }) } /// The view (or sampler) just made in slot `s` (its SRV, or with `uav` its UAV) goes to the shared heap. @@ -484,8 +486,9 @@ pub unsafe fn publish(s: &Slot, uav: bool) { } /// `n` view or sampler slots from `first` were copied (in the title's heap): they go to the shared heap, -/// a run per page (a heap's pages lie apart there). +/// a run per page (a heap's pages lie apart there), stopping at the title heap's end. pub unsafe fn publish_range(first: &Slot, n: u32) { + let n = n.min(first.remaining); let page_slots = if first.sampler { SAMPLER_PAGE_SLOTS } else { PAGE_SLOTS }; let step = if first.sampler { SAMPLER_SLOT } else { SLOT }; let mut done = 0; @@ -1176,4 +1179,89 @@ mod tests { assert_eq!(sampler_own_index(&[], 0), 0); assert_eq!(sampler_own_index(&[], 42), 42); } + + #[test] + fn publish_range_stops_at_small_and_tail_heap_bounds() { + const CHILD: &str = "XCL_TEST_PUBLISH_BOUNDS_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::publish_range_stops_at_small_and_tail_heap_bounds", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + + static CALLS: Mutex> = Mutex::new(Vec::new()); + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn copy_simple( + _this: *mut c_void, + n: u32, + dst: D3D12_CPU_DESCRIPTOR_HANDLE, + src: D3D12_CPU_DESCRIPTOR_HANDLE, + ty: D3D12_DESCRIPTOR_HEAP_TYPE, + ) { + CALLS.lock().unwrap().push((n, dst.ptr as u64, src.ptr as u64, ty.0)); + } + + let mut vt = [0usize; 25]; + vt[1] = retain as usize; + vt[2] = retain as usize; + vt[24] = copy_simple as usize; + let (mut device, mut view_heap, mut sampler_heap) = + (Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }); + let view4 = vec![0u8; (4 * SLOT) as usize]; + let sampler3 = vec![0u8; (3 * SAMPLER_SLOT) as usize]; + let view260 = vec![0u8; (260 * SLOT) as usize]; + unsafe { + let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); + *GLOBAL.lock().unwrap() = Some(Global { + dev: dev.clone(), + heap: ID3D12DescriptorHeap::from_raw(&mut view_heap as *mut _ as *mut c_void), + cpu: 0x10_0000, + gpu: 0x18_0000, + inc: 32, + cap: 4096, + next: 64, + free: Vec::new(), + }); + *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { + dev, + heap: ID3D12DescriptorHeap::from_raw(&mut sampler_heap as *mut _ as *mut c_void), + cpu: 0x20_0000, + inc: 16, + cap: 256, + next: 1, + free: Vec::new(), + }); + { + let mut heaps = HEAPS.lock().unwrap(); + heaps.push(Heap { obj: 1, shadow: view4.as_ptr() as usize, n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 2, shadow: sampler3.as_ptr() as usize, n: 3, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 3, shadow: view260.as_ptr() as usize, n: 260, pc_cpu: 0x50_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); + } + let v1 = slot(view4.as_ptr() as u64 + SLOT as u64).unwrap(); + publish_range(&v1, 10); + let s1 = slot(sampler3.as_ptr() as u64 + SAMPLER_SLOT as u64).unwrap(); + publish_range(&s1, 10); + let v250 = slot(view260.as_ptr() as u64 + (250 * SLOT) as u64).unwrap(); + publish_range(&v250, 20); + HEAPS.lock().unwrap().clear(); + *GLOBAL_SAMPLER.lock().unwrap() = None; + *GLOBAL.lock().unwrap() = None; + } + assert_eq!( + *CALLS.lock().unwrap(), + vec![ + (6, 0x10_0000 + 66 * 32, 0x30_0000 + 2 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + (2, 0x20_0000 + 2 * 16, 0x40_0000 + 16, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0), + (12, 0x10_0000 + (72 + 500) * 32, 0x50_0000 + 500 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + (8, 0x10_0000 + 584 * 32, 0x50_0000 + 512 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + ] + ); + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 6de60f9285..83c6ec49fc 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -8324,7 +8324,7 @@ mod tests { #[test] fn uav_clear_handles_translate_console_slots() { use super::super::console_heap::Slot; - let s = |pc_uav: u64, pc_gpu_uav: u64, sampler: bool| Some(Slot { at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv: 0, k: 0 }); + let s = |pc_uav: u64, pc_gpu_uav: u64, sampler: bool| Some(Slot { at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv: 0, k: 0, remaining: 1 }); assert_eq!(uav_clear_handles(s(0x10, 0x5010, false), s(0x20, 0, false)), UavClearHandles::Console { gpu: 0x5010, cpu: 0x20 }); assert_eq!(uav_clear_handles(None, None), UavClearHandles::Pc); // a console slot beside a PC handle, a GPU slot of a heap that is not shader visible, From 00fb896305d488065357afc47b69f7d77b564bf7 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 07:32:54 +0300 Subject: [PATCH 055/265] Recompiler: eliminate BTree/Vec allocations and skip dominator pass on acyclic CFGs in direct DXIL cfg Replace BTreeMap/BTreeSet leader and block-index tables in Cfg::build_with with binary search over monotonically decoded instruction PCs and flat Vec tables, remove the unused reach BTreeSet, replace heap-allocated succ_of Vec with a Copy stack-allocated Succs, avoid cloning preds[x] in make_reducible, and short-circuit the dominator pass in make_reducible when order() finds no back edges (acyclic DAG). Part of #2508 Part of #1833 Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/cfg.rs | 178 +++++++++++++++++++++++++++------ 1 file changed, 147 insertions(+), 31 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/cfg.rs b/crates/xcl/src/gpu/dxil/cfg.rs index 31b3dcec2a..4f114cb15e 100644 --- a/crates/xcl/src/gpu/dxil/cfg.rs +++ b/crates/xcl/src/gpu/dxil/cfg.rs @@ -1,7 +1,7 @@ //! Basic blocks of a decoded RDNA2 program, their edges and a reverse //! post-order (the emission order: every block after its dominators). -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeSet; use crate::gpu::rdna2::{self, Decoded}; @@ -58,35 +58,47 @@ impl Cfg { insts.push(d); } rdna2::resolve_far_jumps(&mut insts); - let index: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); - let mut leaders: BTreeSet = BTreeSet::from([0]); + let index_of = |pc: u64| insts.binary_search_by_key(&pc, |d| d.pc).ok(); + let mut is_leader = vec![false; insts.len()]; + if !is_leader.is_empty() { + is_leader[0] = true; + } let is_setpc = |d: &Decoded| setpc.is_some() && d.inst.name == "S_SETPC_B64" && d.far_target.is_none(); let setpc_target = match setpc { - Some(Some(t)) => Some(*index.get(&t).ok_or_else(|| format!("GS start {t:#x} is not the start of an instruction"))?), + Some(Some(t)) => Some(index_of(t).ok_or_else(|| format!("GS start {t:#x} is not the start of an instruction"))?), _ => None, }; if let Some(t) = setpc_target { - leaders.insert(t); + is_leader[t] = true; } for (i, d) in insts.iter().enumerate() { if is_setpc(d) { - leaders.insert(i + 1); + if i + 1 < is_leader.len() { + is_leader[i + 1] = true; + } continue; } if let Some(t) = rdna2::branch_target(d) { - let ti = *index.get(&t).ok_or_else(|| format!("+{:#x}: branch to {t:#x}, which is not the start of an instruction", d.pc))?; - leaders.insert(ti); - leaders.insert(i + 1); + let ti = index_of(t).ok_or_else(|| format!("+{:#x}: branch to {t:#x}, which is not the start of an instruction", d.pc))?; + is_leader[ti] = true; + if i + 1 < is_leader.len() { + is_leader[i + 1] = true; + } } else if d.inst.flags & rdna2::F_TERMINATOR != 0 || is_end(d.inst.name) { - leaders.insert(i + 1); + if i + 1 < is_leader.len() { + is_leader[i + 1] = true; + } } } - let starts: Vec = leaders.into_iter().filter(|&l| l < insts.len()).collect(); - let block_of: BTreeMap = starts.iter().enumerate().map(|(b, &i)| (i, b)).collect(); - let mut blocks = Vec::new(); + let starts: Vec = (0..insts.len()).filter(|&i| is_leader[i]).collect(); + let mut block_of = vec![usize::MAX; insts.len()]; + for (b, &i) in starts.iter().enumerate() { + block_of[i] = b; + } + let mut blocks = Vec::with_capacity(starts.len()); for (b, &s) in starts.iter().enumerate() { let e = starts.get(b + 1).copied().unwrap_or(insts.len()); - let mut list = Vec::new(); + let mut list = Vec::with_capacity(e - s); let mut term = if e < insts.len() { Term::Jump(b + 1) } else { Term::End }; for i in s..e { let d = &insts[i]; @@ -96,13 +108,13 @@ impl Cfg { } if is_setpc(d) { term = match setpc_target { - Some(t) => Term::Jump(block_of[&t]), + Some(t) => Term::Jump(block_of[t]), None => Term::End, }; break; } if let Some(t) = rdna2::branch_target(d) { - let tb = block_of[&index[&t]]; + let tb = block_of[index_of(t).unwrap()]; let name = d.inst.name; term = if name == "S_BRANCH" || d.far_target.is_some() { Term::Jump(tb) @@ -131,16 +143,13 @@ impl Cfg { // CFG; the console compiler emits loops entered in the middle): split nodes until // every retreating edge is a back edge to a dominator let (post, headers) = make_reducible(&mut blocks)?; - let succ = succ_of; - let reach: BTreeSet = post.iter().copied().collect(); for &b in &post { - for t in succ(&blocks[b]) { + for t in succ_of(&blocks[b]) { if !blocks[t].preds.contains(&b) { blocks[t].preds.push(b); } } } - let _ = reach; Ok(Cfg { insts, blocks, rpo: post, headers }) } } @@ -150,10 +159,20 @@ impl Cfg { /// it elsewhere. The reverse post-order and loop headers of the result; gives up past four /// times the original block count. fn make_reducible(blocks: &mut Vec) -> Result<(Vec, BTreeSet), String> { + let (post, headers, _) = make_reducible_inner(blocks)?; + Ok((post, headers)) +} + +fn make_reducible_inner(blocks: &mut Vec) -> Result<(Vec, BTreeSet, usize), String> { let limit = 4 * blocks.len() + 256; + let mut dom_passes = 0usize; loop { let (post, headers) = order(blocks); - let Some((_, t)) = irreducible_edge(blocks, &post) else { return Ok((post, headers)) }; + if headers.is_empty() { + return Ok((post, headers, dom_passes)); + } + dom_passes += 1; + let Some((_, t)) = irreducible_edge(blocks, &post) else { return Ok((post, headers, dom_passes)) }; let n = blocks.len(); let mut pos = vec![usize::MAX; n]; for (i, &b) in post.iter().enumerate() { @@ -171,8 +190,9 @@ fn make_reducible(blocks: &mut Vec) -> Result<(Vec, BTreeSet) -> Result<(Vec, BTreeSet Vec { +#[derive(Clone, Copy)] +struct Succs { + buf: [usize; 2], + len: usize, +} + +impl Succs { + fn as_slice(&self) -> &[usize] { + &self.buf[..self.len] + } +} + +impl IntoIterator for Succs { + type Item = usize; + type IntoIter = std::iter::Take>; + fn into_iter(self) -> Self::IntoIter { + self.buf.into_iter().take(self.len) + } +} + +fn succ_of(b: &CfgBlock) -> Succs { match b.term { - Term::Jump(t) => vec![t], - Term::Cond(_, t, f) => vec![t, f], - Term::End => vec![], + Term::Jump(t) => Succs { buf: [t, 0], len: 1 }, + Term::Cond(_, t, f) => Succs { buf: [t, f], len: 2 }, + Term::End => Succs { buf: [0, 0], len: 0 }, } } @@ -236,15 +276,16 @@ fn succ_of(b: &CfgBlock) -> Vec { /// retreating edges. fn order(blocks: &[CfgBlock]) -> (Vec, BTreeSet) { let n = blocks.len(); - let succ = succ_of; let mut state = vec![0u8; n]; // 0 new, 1 on stack, 2 done - let mut post = Vec::new(); + let mut post = Vec::with_capacity(n); let mut headers = BTreeSet::new(); if n > 0 { - let mut stack: Vec<(usize, usize)> = vec![(0, 0)]; + let mut stack: Vec<(usize, usize)> = Vec::with_capacity(n.min(64).max(1)); + stack.push((0, 0)); state[0] = 1; while let Some(&mut (b, ref mut k)) = stack.last_mut() { - let s = succ(&blocks[b]); + let succs = succ_of(&blocks[b]); + let s = succs.as_slice(); if *k < s.len() { let t = s[*k]; *k += 1; @@ -346,4 +387,79 @@ mod tests { assert_eq!(headers.len(), 1); assert_eq!(headers2.len(), 1); } + + #[test] + fn acyclic_cfg_skips_dominator_pass_and_matches_rpo_and_preds() { + let mut code = Vec::new(); + code.extend(rdna2::encode("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 2)], None).unwrap()); + code.extend(rdna2::encode("S_NOP", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap()); + code.extend(rdna2::encode("S_BRANCH", "ENC_SOPP", &[("SIMM16", 1)], None).unwrap()); + code.extend(rdna2::encode("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap()); + code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + code.extend(rdna2::encode("S_NOP", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap()); + + let mut cfg = Cfg::build(&code).unwrap(); + assert_eq!(cfg.blocks.len(), 5); + assert_eq!(cfg.blocks[2].term, Term::Jump(3)); + assert!(cfg.headers.is_empty()); + assert_eq!(cfg.rpo, vec![0, 1, 2, 3]); + assert_eq!(cfg.blocks[0].preds, Vec::::new()); + assert_eq!(cfg.blocks[1].preds, vec![0]); + assert_eq!(cfg.blocks[2].preds, vec![0]); + assert_eq!(cfg.blocks[3].preds, vec![1, 2]); + assert_eq!(cfg.blocks[4].preds, Vec::::new()); + assert!(irreducible_edge(&cfg.blocks, &cfg.rpo).is_none()); + + let (rpo, headers, dom_passes) = make_reducible_inner(&mut cfg.blocks).unwrap(); + assert_eq!(dom_passes, 0, "acyclic CFG must skip dominator pass"); + assert!(headers.is_empty()); + assert_eq!(rpo, cfg.rpo); + } + + #[test] + fn succ_of_is_copy_and_covers_all_terminators() { + fn assert_copy() {} + assert_copy::(); + for (term, want) in [ + (Term::End, &[][..]), + (Term::Jump(5), &[5][..]), + (Term::Cond(9, 2, 7), &[2, 7][..]), + ] { + let s = succ_of(&blk(term)); + assert_eq!(s.as_slice(), want); + assert_eq!(s.into_iter().collect::>(), want); + } + } + + #[test] + fn empty_reducible_loop_irreducible_and_geometry_cfgs_match() { + let empty = Cfg::build(&[]).unwrap(); + assert!(empty.insts.is_empty() && empty.blocks.is_empty() && empty.rpo.is_empty() && empty.headers.is_empty()); + + let mut red = vec![blk(Term::Jump(1)), blk(Term::Cond(0, 1, 2)), blk(Term::End)]; + let (rpo, headers, dom_passes) = make_reducible_inner(&mut red).unwrap(); + assert_eq!((dom_passes, rpo, headers), (1, vec![0, 1, 2], BTreeSet::from([1]))); + + let mut irred = vec![blk(Term::Cond(0, 3, 1)), blk(Term::Jump(2)), blk(Term::Jump(3)), blk(Term::Cond(0, 2, 4)), blk(Term::End)]; + let (rpo, headers, dom_passes) = make_reducible_inner(&mut irred).unwrap(); + assert!(dom_passes >= 2 && headers.len() == 1 && irreducible_edge(&irred, &rpo).is_none()); + + let mut gs = Vec::new(); + gs.extend(rdna2::encode("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 0)], None).unwrap()); + gs.extend(rdna2::encode("S_NOP", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap()); + gs.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let with_gs = Cfg::build_geometry(&gs, Some(8)).unwrap(); + assert_eq!(with_gs.blocks[0].term, Term::Jump(2)); + assert_eq!((with_gs.blocks[2].pc, with_gs.rpo), (8, vec![0, 2])); + for start in [None, Some(0)] { + let ended = Cfg::build_geometry(&gs, start).unwrap(); + assert_eq!((&ended.blocks[0].term, &ended.rpo), (&Term::End, &vec![0])); + } + assert!(Cfg::build_geometry(&gs, Some(2)).err().unwrap().contains("GS start")); + + let bad_br = rdna2::encode("S_BRANCH", "ENC_SOPP", &[("SIMM16", 8)], None).unwrap(); + assert!(Cfg::build(&bad_br).err().unwrap().contains("not the start of an instruction")); + let bad_cbr = rdna2::encode("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", (-1i16) as u16 as u64)], None).unwrap(); + assert!(Cfg::build(&bad_cbr).err().unwrap().contains("conditional branch at the end of the code")); + } } From 936930548405f0511e3e8ef4ca16f1856a7a1376 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:31:08 -0800 Subject: [PATCH 056/265] D3D12.X: retain busy allocators past final Release A title can release a command allocator while command-list recordings, reserved submits, or GPU fence marks still depend on its native object. Probe the logical final COM Release, transfer that reference only for a busy backing, detach the title namespace, and retire original or pool-created backing ownership outside the allocator state lock once it is free. This is the lifetime prerequisite for pre-execution allocator reservations; production submit wiring remains disabled. Cross-target cargo check for tests passed; Windows GPU execution was unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 256 +++++++++++++++++++++--- crates/xcl/src/hle/d3d12x/real.rs | 24 ++- 2 files changed, 256 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index b87a958a5d..1ae89cd2a4 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -32,6 +32,10 @@ struct Backing { marks: HashMap, /// Submits reserved before ExecuteCommandLists whose completion is not marked yet. submit_pins: usize, + /// Probe reference transferred from the title's Release while this backing is busy. + release_owner: Option, + /// Its allocator namespace is gone; release its retained/raw owner once it becomes free. + retire_when_free: bool, } impl Backing { @@ -76,6 +80,61 @@ unsafe impl Send for State {} static STATE: Mutex> = Mutex::new(None); +pub(super) fn release_with_probe( + add_ref: impl FnOnce(), + mut release: impl FnMut() -> u32, + retain_probe: impl FnOnce() -> bool, +) -> (u32, bool) { + add_ref(); + let after_caller = release(); + if after_caller == 1 && retain_probe() { (0, true) } else { (release(), false) } +} + +/// Transfer the caller's temporary AddRef probe into pool ownership when releasing `raw` would +/// otherwise destroy an allocator that still owns recordings or unretired GPU work. +pub(super) unsafe fn retain_release_probe(raw: *mut c_void) -> bool { + let mut g = STATE.lock().unwrap(); + let Some(backing) = g.as_mut().and_then(|s| s.backings.get_mut(&(raw as usize))) else { return false }; + if backing.free() || backing.release_owner.is_some() { + return false; + } + backing.release_owner = Some(ID3D12CommandAllocator::from_raw(raw)); + true +} + +/// Drop transferred Release probes only after leaving STATE: their hooked Release re-enters here. +pub(super) fn sweep_release_owners() { + sweep_release_owners_with(super::real::release_retained_allocator, drop); +} + +fn sweep_release_owners_with( + mut release_transferred: impl FnMut(ID3D12CommandAllocator), + mut release_made: impl FnMut(ID3D12CommandAllocator), +) { + loop { + let owner = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if let Some(raw) = s.backings.iter().find_map(|(&raw, b)| (b.retire_when_free && unsafe { b.free() }).then_some(raw)) { + let mut gone = s.backings.remove(&raw).unwrap(); + match gone.release_owner.take() { + Some(owner) => Some((owner, true)), + None => Some((unsafe { ID3D12CommandAllocator::from_raw(raw as *mut c_void) }, false)), + } + } else { + return; + } + }; + if let Some((owner, transferred)) = owner { + if transferred { + release_transferred(owner); + } else { + release_made(owner); + } + } + } +} + #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(default)] pub struct AllocatorSubmitStats { @@ -220,6 +279,7 @@ fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &I /// must keep this token until it knows ExecuteCommandLists cannot have run, or convert it with /// `execution_possible` immediately before making the native call. pub(super) fn begin_submit(lists: &[*mut c_void]) -> Option { + sweep_release_owners(); if !enabled() { return Some(BeginSubmit { entries: Vec::new() }); } @@ -269,9 +329,12 @@ impl BeginSubmit { impl Drop for BeginSubmit { fn drop(&mut self) { if !self.entries.is_empty() { - if let Some(s) = STATE.lock().unwrap().as_mut() { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { release_submit_pins(s, &self.entries); } + drop(g); + sweep_release_owners(); } } } @@ -304,6 +367,8 @@ impl PendingSubmit { }; record_submit(s, &self.entries, key, &fence, value); self.entries.clear(); + drop(g); + sweep_release_owners(); true } @@ -347,6 +412,8 @@ pub(super) fn forget_list(list: usize) { b.users.remove(&list); } } + drop(g); + sweep_release_owners(); } /// Reset `list` on the title's allocator `alloc`, committing its new recording association @@ -487,35 +554,57 @@ pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { let g = STATE.lock().unwrap(); let Some(s) = g.as_ref() else { return false }; let mine = s.cur.get(&alloc).into_iter().chain(s.aside.get(&alloc).into_iter().flatten()).chain([&alloc]); - let busy = mine.filter_map(|b| s.backings.get(b)).any(|b| b.marks.values().any(|(f, v)| f.GetCompletedValue() < *v)); + let busy = mine.filter_map(|b| s.backings.get(b)).any(|b| { + b.submit_pins != 0 || b.marks.values().any(|(f, v)| f.GetCompletedValue() < *v) + }); + drop(g); + sweep_release_owners(); busy } -/// The title's allocator `alloc` is gone (its last Release): nothing of it stays here – a later -/// allocator may get its address, and must not go on with this one's PC allocators. The ones -/// made here go with it (those lists still record on are left alone: not freed, not tracked). -pub unsafe fn forget(alloc: usize) { - let made: Vec = { - let mut g = STATE.lock().unwrap(); - let Some(s) = g.as_mut() else { return }; - s.types.remove(&alloc); - let mut mine: Vec = s.aside.remove(&alloc).unwrap_or_default(); - mine.extend(s.cur.remove(&alloc)); - mine.push(alloc); - let mut made = Vec::new(); - for b in mine { - let free = s.backings.get(&b).is_none_or(|x| x.free()); - if let Some(gone) = s.backings.remove(&b) { - for l in gone.users { - s.of_list.remove(&l); - } +/// The title's allocator `alloc` reached its logical final Release. Detach its namespace now; +/// backings still used by recordings/submits retain their native owner until a later sweep. +unsafe fn forget_in(s: &mut State, alloc: usize) -> (Vec, Vec) { + s.types.remove(&alloc); + let mut mine: Vec = s.aside.remove(&alloc).unwrap_or_default(); + mine.extend(s.cur.remove(&alloc)); + mine.push(alloc); + mine.sort_unstable(); + mine.dedup(); + let mut made = Vec::new(); + let mut owners = Vec::new(); + for b in mine { + let free = s.backings.get(&b).is_none_or(|x| x.free()); + if !free { + if let Some(backing) = s.backings.get_mut(&b) { + backing.retire_when_free = true; } - if b != alloc && free { - made.push(b); + continue; + } + let owner = s.backings.remove(&b).and_then(|mut gone| { + for l in gone.users.drain() { + s.of_list.remove(&l); } + gone.release_owner.take() + }); + if let Some(owner) = owner { + owners.push(owner); + } else if b != alloc { + made.push(b); } - made + } + (made, owners) +} + +pub unsafe fn forget(alloc: usize) { + let (made, owners) = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + forget_in(s, alloc) }; + for owner in owners { + super::real::release_retained_allocator(owner); + } // (outside the lock: their Release comes back here) for b in made { drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); @@ -595,6 +684,127 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu mod tests { use super::*; + #[test] + fn release_probe_transfers_only_the_logical_final_reference() { + use std::cell::Cell; + let refs = Cell::new(1u32); + let retained = Cell::new(0u32); + let (remaining, transferred) = release_with_probe( + || refs.set(refs.get() + 1), + || { + refs.set(refs.get() - 1); + refs.get() + }, + || { + retained.set(retained.get() + 1); + true + }, + ); + assert_eq!((remaining, transferred, refs.get(), retained.get()), (0, true, 1, 1)); + refs.set(refs.get() - 1); // the out-of-lock sweep releases the transferred probe + assert_eq!(refs.get(), 0); + + refs.set(2); + retained.set(0); + let (remaining, transferred) = release_with_probe( + || refs.set(refs.get() + 1), + || { + refs.set(refs.get() - 1); + refs.get() + }, + || { + retained.set(retained.get() + 1); + true + }, + ); + assert_eq!((remaining, transferred, refs.get(), retained.get()), (1, false, 1, 0)); + } + + #[test] + fn released_namespace_keeps_busy_made_backing_until_retirement() { + let (alloc, made) = (0x7ffe_6100usize, 0x7ffe_6200usize); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.cur.insert(alloc, made); + s.backings.insert(made, Backing { submit_pins: 1, ..Default::default() }); + } + assert!(unsafe { allocator_in_flight(alloc) }); + unsafe { forget(alloc) }; + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(s.backings[&made].retire_when_free); + assert_eq!(s.backings[&made].submit_pins, 1); + assert!(!s.cur.contains_key(&alloc)); + s.backings.remove(&made); // synthetic raw has no COM reference to sweep + } + } + + #[test] + fn absent_free_made_backing_is_scheduled_for_release_once() { + let (alloc, made) = (0x7ffe_6300usize, 0x7ffe_6400usize); + let mut state = State::default(); + state.cur.insert(alloc, made); + state.aside.insert(alloc, vec![made, alloc, made]); + let (release, owners) = unsafe { forget_in(&mut state, alloc) }; + assert_eq!(release, vec![made]); + assert!(owners.is_empty()); + assert!(!state.cur.contains_key(&alloc) && !state.aside.contains_key(&alloc)); + } + + #[test] + fn transferred_owner_is_released_once_outside_state_after_logical_forget() { + use std::cell::Cell; + + #[repr(C)] + struct FakeAllocator { + vtable: *const usize, + refs: Cell, + releases: Cell, + release_outside_state: Cell, + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let object = &*this.cast::(); + for _ in 0..10_000 { + if STATE.try_lock().is_ok() { + object.release_outside_state.set(true); + break; + } + std::thread::yield_now(); + } + object.releases.set(object.releases.get() + 1); + object.refs.set(object.refs.get() - 1); + object.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + + let vtable = [unexpected_call as usize, unexpected_call as usize, release as usize]; + let mut object = FakeAllocator { + vtable: vtable.as_ptr(), refs: Cell::new(1), releases: Cell::new(0), release_outside_state: Cell::new(false), + }; + let raw = std::ptr::from_mut(&mut object).cast::(); + let owner = unsafe { ID3D12CommandAllocator::from_raw(raw) }; + { + let mut g = STATE.lock().unwrap(); + g.get_or_insert_with(State::default).backings.insert( + raw as usize, + Backing { submit_pins: 1, release_owner: Some(owner), ..Default::default() }, + ); + } + unsafe { forget(raw as usize) }; + { + let mut g = STATE.lock().unwrap(); + let backing = g.as_mut().unwrap().backings.get_mut(&(raw as usize)).unwrap(); + assert!(backing.retire_when_free); + backing.submit_pins = 0; + } + sweep_release_owners_with(drop, drop); + assert_eq!((object.refs.get(), object.releases.get()), (0, 1)); + assert!(object.release_outside_state.get()); + assert!(!STATE.lock().unwrap().as_ref().unwrap().backings.contains_key(&(raw as usize))); + } + #[test] fn execute_topology_counts_only_split_boundaries() { assert_eq!(execute_topology(1), (0, 0)); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 6a7bc8799f..8b9136e97d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7095,9 +7095,31 @@ unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { n } +thread_local! { + static RETAINED_ALLOC_RELEASE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +pub(super) fn release_retained_allocator(owner: ID3D12CommandAllocator) { + let raw = owner.as_raw() as usize; + RETAINED_ALLOC_RELEASE.with(|active| { + let old = active.replace(raw); + debug_assert_eq!(old, 0); + drop(owner); + active.set(old); + }); +} + unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); + if RETAINED_ALLOC_RELEASE.with(|active| active.get() == this as usize) { + return f(this); + } + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); + let (n, _) = super::alloc_pool::release_with_probe( + || { add_ref(this); }, + || f(this), + || super::alloc_pool::retain_release_probe(this), + ); if n == 0 { dispatch_chain::allocator_reset(this as usize); super::alloc_pool::forget(this as usize); From c12d82169a1cd67098942300a6ba67cc3b18888c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:32:21 -0800 Subject: [PATCH 057/265] D3D12.X: refresh title fences outside the global lock Fence refresh and diagnostics held the global fence table lock across driver GetCompletedValue calls, while CPU signals scanned unrelated fences. Snapshot stable cell mirrors, serialize refreshes per fence, and keep raw diagnostic fixtures alive through teardown without blocking ordinary signal/wait bookkeeping. Adapted from xcl-dev/xcl PR #2649 commit 6530439984ad79923fcb7698af76aa0c2d0b9fb2 by Decodere, with the non-cell diagnostic lifetime race fixed. Cross-target cargo check for library and tests passed; Windows execution was unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/fence_x.rs | 362 ++++++++++++++++++++++----- 1 file changed, 299 insertions(+), 63 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs index f67967345e..f6ca932d71 100644 --- a/crates/xcl/src/hle/d3d12x/fence_x.rs +++ b/crates/xcl/src/hle/d3d12x/fence_x.rs @@ -6,7 +6,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D12::ID3D12Fence; @@ -16,17 +16,135 @@ use windows_sys::Win32::System::Threading as th; #[repr(C, align(64))] struct Cell(AtomicU64); +/// Heap-isolated cell plus per-fence refresh lock (`true` = live, `false` = retired). +/// Keeping `Box` off the lock's cache line avoids false-sharing `monitorx`/`mwaitx` wakes. +struct CellMirror { + cell: Box, + refresh_lock: Mutex, +} + #[derive(Default)] struct Fence { - cell: Option<&'static Cell>, + cell: Option>, /// the highest value a queue was told to signal signalled: u64, /// the highest value a queue was told to wait for waited: u64, } -/// (fences are never freed: XCL holds a reference to each) -static FENCES: Mutex>> = Mutex::new(None); +#[derive(Default)] +struct State { + map: HashMap, + cells: Vec<(usize, Arc)>, +} + +/// (fences are never freed in production: XCL holds a reference to each) +struct FenceTable { + /// Keeps test-owned raw fence pointers alive across diagnostic COM calls. + summary_lifetime: Mutex<()>, + inner: Mutex, +} + +impl FenceTable { + fn new() -> Self { + Self { summary_lifetime: Mutex::new(()), inner: Mutex::new(State::default()) } + } + + fn refresh_one(fence: usize, mirror: &CellMirror) { + let live = mirror.refresh_lock.lock().unwrap_or_else(|e| e.into_inner()); + if !*live { + return; + } + if let Some(v) = unsafe { borrowed(fence, |f| f.GetCompletedValue()) } { + mirror.cell.0.store(v, Ordering::Release); + } + } + + fn refresh(&self) { + let cells = self.inner.lock().unwrap_or_else(|e| e.into_inner()).cells.clone(); + for (p, mirror) in cells { + Self::refresh_one(p, &mirror); + } + } + + fn note_queue_signal(&self, fence: usize, value: u64) -> bool { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let f = g.map.entry(fence).or_default(); + f.signalled = f.signalled.max(value); + f.cell.is_some() + } + + fn note_queue_wait(&self, fence: usize, value: u64) { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let f = g.map.entry(fence).or_default(); + f.waited = f.waited.max(value); + } + + fn note_cpu_signal(&self, fence: usize) { + let mirror = self.inner.lock().unwrap_or_else(|e| e.into_inner()).map.get(&fence).and_then(|f| f.cell.clone()); + if let Some(mirror) = mirror { + Self::refresh_one(fence, &mirror); + } + } + + fn pending_summary(&self) -> String { + // Test teardown keeps this order: summary lifetime -> table -> per-cell refresh lock. + let _lifetime = self.summary_lifetime.lock().unwrap_or_else(|e| e.into_inner()); + let snap: Vec<(usize, u64, u64, bool)> = { + let g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + g.map.iter().map(|(&p, f)| (p, f.signalled, f.waited, f.cell.is_some())).collect() + }; + let mut parts = Vec::new(); + for (p, signalled, waited, has_cell) in snap { + let done = unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(0); + if done < signalled || done < waited { + parts.push(format!("{p:#x}(done={done:#x}/sig={signalled:#x}/wait={waited:#x},cell={has_cell})")); + } + } + if parts.is_empty() { "none".into() } else { parts.join(", ") } + } + + fn completed_value_address_with(&self, this: *mut c_void, arm_fn: impl FnOnce(usize, u64)) -> *const u64 { + let key = this as usize; + let (mirror, pending) = { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(m) = g.map.get(&key).and_then(|f| f.cell.as_ref()) { + return m.cell.0.as_ptr(); + } + let m = Arc::new(CellMirror { cell: Box::new(Cell(AtomicU64::new(0))), refresh_lock: Mutex::new(true) }); + let pending = { + let f = g.map.entry(key).or_default(); + f.cell = Some(Arc::clone(&m)); + f.signalled + }; + g.cells.push((key, Arc::clone(&m))); + (m, pending) + }; + if pending > 0 { + arm_fn(key, pending); + } + Self::refresh_one(key, &mirror); + mirror.cell.0.as_ptr() + } + + #[cfg(test)] + fn forget_fence(&self, fence: usize) { + let _lifetime = self.summary_lifetime.lock().unwrap_or_else(|e| e.into_inner()); + let removed = { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + g.cells.retain(|(p, _)| *p != fence); + g.map.remove(&fence).and_then(|f| f.cell) + }; + if let Some(mirror) = removed { + *mirror.refresh_lock.lock().unwrap_or_else(|e| e.into_inner()) = false; + } + } +} + +fn table() -> &'static FenceTable { + static T: OnceLock = OnceLock::new(); + T.get_or_init(FenceTable::new) +} /// the event a completion sets (auto-reset); the first use starts the thread that follows it fn event() -> usize { @@ -35,7 +153,7 @@ fn event() -> usize { let e = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) as usize; let spawned = std::thread::Builder::new().name("xcl-fences".into()).spawn(move || loop { th::WaitForSingleObject(e as _, th::INFINITE); - refresh(); + table().refresh(); }); if let Err(err) = spawned { crate::xlog_error!("D3D12.X: no thread for the fences' completed values: {err}"); @@ -49,17 +167,6 @@ unsafe fn borrowed(fence: usize, f: impl FnOnce(&ID3D12Fence) -> R) -> Option ID3D12Fence::from_raw_borrowed(&p).map(f) } -fn refresh() { - let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - for (&p, f) in g.iter().flatten() { - if let Some(c) = f.cell { - if let Some(v) = unsafe { borrowed(p, |f| f.GetCompletedValue()) } { - c.0.store(v, Ordering::Release); - } - } - } -} - unsafe fn arm(fence: usize, value: u64) { if let Some(Err(e)) = borrowed(fence, |f| f.SetEventOnCompletion(value, HANDLE(event() as *mut c_void))) { crate::xlog_warn!("D3D12.X: fence {fence:#x}: SetEventOnCompletion({value:#x}): {e}"); @@ -68,76 +175,35 @@ unsafe fn arm(fence: usize, value: u64) { /// A queue was told to signal `fence` (one of the title's) with `value`. pub(super) unsafe fn note_queue_signal(fence: usize, value: u64) { - let cell = { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default(); - f.signalled = f.signalled.max(value); - f.cell.is_some() - }; - if cell { + if table().note_queue_signal(fence, value) { arm(fence, value); } } /// A queue was told to wait for `fence` (one of the title's) to reach `value`. pub(super) fn note_queue_wait(fence: usize, value: u64) { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default(); - f.waited = f.waited.max(value); + table().note_queue_wait(fence, value); } /// The CPU signalled `fence`. pub(super) fn note_cpu_signal(fence: usize) { - let known = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.get(&fence).is_some_and(|f| f.cell.is_some())); - if known { - refresh(); - } + table().note_cpu_signal(fence); } /// Diagnostic summary of title fences whose completed value lags their signalled or waited value. pub(super) fn pending_summary() -> String { - let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let mut parts = Vec::new(); - for (&p, f) in g.iter().flatten() { - let done = unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(0); - if done < f.signalled || done < f.waited { - parts.push(format!("{p:#x}(done={done:#x}/sig={:#x}/wait={:#x},cell={})", f.signalled, f.waited, f.cell.is_some())); - } - } - if parts.is_empty() { - "none".into() - } else { - parts.join(", ") - } + table().pending_summary() } /// fence #12: the address of its completed value pub(super) unsafe extern "system" fn completed_value_address(this: *mut c_void) -> *const u64 { - let (cell, pending) = { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); - match f.cell { - Some(c) => return c.0.as_ptr(), - None => { - let c: &'static Cell = Box::leak(Box::new(Cell(AtomicU64::new(0)))); - f.cell = Some(c); - (c, f.signalled) - } - } - }; - if pending > 0 { - arm(this as usize, pending); - } - refresh(); - cell.0.as_ptr() + table().completed_value_address_with(this, |f, v| arm(f, v)) } /// Remove a synthetic test fence from `FENCES` before it is dropped. #[cfg(test)] pub(super) fn forget_fence_for_test(fence: usize) { - if let Some(m) = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { - m.remove(&fence); - } + table().forget_fence(fence); } #[cfg(test)] @@ -183,4 +249,174 @@ mod tests { std::mem::forget(fence); // the map keeps its address } } + + struct Gate { + entered: Arc, + release: Arc, + } + + #[repr(C)] + struct MockFence { + vtable: *const usize, + val: AtomicU64, + calls: std::sync::atomic::AtomicUsize, + gate: Mutex>, + } + unsafe impl Send for MockFence {} + unsafe impl Sync for MockFence {} + + impl MockFence { + fn new(val: u64) -> Box { + use std::mem::{offset_of, size_of}; + unsafe extern "system" fn get_val(this: *mut c_void) -> u64 { + let f = &*this.cast::(); + f.calls.fetch_add(1, Ordering::AcqRel); + let v = f.val.load(Ordering::Acquire); + if let Some(g) = f.gate.lock().unwrap().take() { + g.entered.wait(); + g.release.wait(); + } + v + } + extern "system" fn unexpected() { std::process::abort(); } + const SLOT: usize = size_of::(); + const LEN: usize = size_of::() / SLOT; + static VT: OnceLock<[usize; LEN]> = OnceLock::new(); + let vt = VT.get_or_init(|| { + let mut t = [unexpected as usize; LEN]; + t[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = get_val as usize; + t + }); + Box::new(Self { vtable: vt.as_ptr(), val: AtomicU64::new(val), calls: Default::default(), gate: Mutex::new(None) }) + } + fn as_ptr(&self) -> *mut c_void { std::ptr::from_ref(self) as *mut c_void } + fn arm_gate(&self) -> (Arc, Arc) { + let (e, r) = (Arc::new(std::sync::Barrier::new(2)), Arc::new(std::sync::Barrier::new(2))); + *self.gate.lock().unwrap() = Some(Gate { entered: e.clone(), release: r.clone() }); + (e, r) + } + } + + #[test] + fn refresh_and_pending_summary_do_not_block_concurrent_queue_and_cpu_signals() { + let table = Arc::new(FenceTable::new()); + let (a, b) = (MockFence::new(1), MockFence::new(2)); + let (pa, pb) = (a.as_ptr(), b.as_ptr()); + let _cell_a = table.completed_value_address_with(pa, |_, _| {}); + let cell_b = table.completed_value_address_with(pb, |_, _| {}); + assert!(table.note_queue_signal(pa as usize, 10)); + + // 1. refresh() must not hold global lock across GetCompletedValue(). + let (entered, release) = a.arm_gate(); + let t1 = Arc::clone(&table); + let h1 = std::thread::spawn(move || t1.refresh()); + entered.wait(); + b.val.store(4, Ordering::Release); + assert!(table.note_queue_signal(pb as usize, 4)); + table.note_queue_wait(pb as usize, 4); + table.note_cpu_signal(pb as usize); + assert_eq!(unsafe { (*(cell_b as *const AtomicU64)).load(Ordering::Acquire) }, 4); + release.wait(); + h1.join().unwrap(); + + // 2. pending_summary() must not hold global lock across GetCompletedValue(). + let (entered, release) = a.arm_gate(); + let t2 = Arc::clone(&table); + let h2 = std::thread::spawn(move || t2.pending_summary()); + entered.wait(); + b.val.store(7, Ordering::Release); + assert!(table.note_queue_signal(pb as usize, 7)); + table.note_queue_wait(pb as usize, 7); + table.note_cpu_signal(pb as usize); + assert_eq!(unsafe { (*(cell_b as *const AtomicU64)).load(Ordering::Acquire) }, 7); + release.wait(); + let summary = h2.join().unwrap(); + assert!(summary.contains("done=0x1/sig=0xa/"), "unexpected summary: {summary}"); + } + + #[test] + fn pending_summary_keeps_non_cell_fence_live_until_forget_returns() { + let table = Arc::new(FenceTable::new()); + let fence = MockFence::new(1); + let p = fence.as_ptr() as usize; + assert!(!table.note_queue_signal(p, 2), "the fence must not have a cell"); + let (entered, release) = fence.arm_gate(); + let summary_table = Arc::clone(&table); + let summary = std::thread::spawn(move || summary_table.pending_summary()); + entered.wait(); + + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let forget_table = Arc::clone(&table); + let forget = std::thread::spawn(move || { + started_tx.send(()).unwrap(); + forget_table.forget_fence(p); + done_tx.send(()).unwrap(); + }); + started_rx.recv().unwrap(); + assert!(matches!(table.summary_lifetime.try_lock(), Err(std::sync::TryLockError::WouldBlock))); + assert!(matches!(done_rx.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)), "forget returned during the raw COM query"); + + release.wait(); + assert!(summary.join().unwrap().contains("done=0x1/sig=0x2/")); + forget.join().unwrap(); + done_rx.recv().unwrap(); + drop(fence); + } + + #[test] + fn note_cpu_signal_and_refresh_avoid_unrelated_and_non_cell_fences() { + let table = FenceTable::new(); + let (a, b) = (MockFence::new(3), MockFence::new(5)); + let non_cells: Vec> = (0..64).map(|i| MockFence::new(i)).collect(); + let (pa, pb) = (a.as_ptr(), b.as_ptr()); + let _ = table.completed_value_address_with(pa, |_, _| {}); + let _ = table.completed_value_address_with(pb, |_, _| {}); + for f in &non_cells { + assert!(!table.note_queue_signal(f.as_ptr() as usize, 10)); + table.note_queue_wait(f.as_ptr() as usize, 10); + } + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.note_cpu_signal(pb as usize); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (0, 1)); + assert!(non_cells.iter().all(|f| f.calls.load(Ordering::Acquire) == 0)); + + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.refresh(); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (1, 1)); + assert!(non_cells.iter().all(|f| f.calls.load(Ordering::Acquire) == 0)); + + table.forget_fence(pa as usize); + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.refresh(); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (0, 1)); + } + + #[test] + fn per_cell_lock_prevents_stale_refresh_overwrite() { + let table = Arc::new(FenceTable::new()); + let a = MockFence::new(10); + let pa = a.as_ptr(); + let cell = table.completed_value_address_with(pa, |_, _| {}); + a.calls.store(0, Ordering::Release); + + let (entered, release) = a.arm_gate(); + let t1 = Arc::clone(&table); + let h1 = std::thread::spawn(move || t1.refresh()); + entered.wait(); + a.val.store(11, Ordering::Release); + let t2 = Arc::clone(&table); + let pa_addr = pa as usize; + let h2 = std::thread::spawn(move || t2.note_cpu_signal(pa_addr)); + std::thread::sleep(std::time::Duration::from_millis(20)); + assert_eq!(a.calls.load(Ordering::Acquire), 1, "note_cpu_signal must serialize behind in-flight refresh_lock"); + release.wait(); + h1.join().unwrap(); + h2.join().unwrap(); + assert_eq!(a.calls.load(Ordering::Acquire), 2); + assert_eq!(unsafe { (*(cell as *const AtomicU64)).load(Ordering::Acquire) }, 11); + } } From a151d512a009dfe01b3ccd898b4cc72bf81350df Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:49:27 +0100 Subject: [PATCH 058/265] D3D12.X: the sparse windows' pool heaps are 4 MiB, so freed runs of tiles go back A pool heap is released only when all its tiles are free, and a title frees its tiles in runs spread over all its heaps. With heaps of 64 MiB (1,024 tiles) a retail title's world load unmapped 1.5 GB of its 4.6 GB of tiles and 3 of 78 heaps went back: 1.7 GB of video memory stayed in live heaps as free tiles. With heaps of 64 tiles 1.25 GB goes back and 0.2 GB stays. retire_free_pools marks the pools that go with a flag each: a world load frees hundreds of pools' worth of tiles at once. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/sparse.rs | 54 ++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index abe90f579c..633f0d8d63 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -32,8 +32,11 @@ use windows_sys::Win32::System::Memory::{ }; const TILE: usize = 0x1_0000; -/// tiles of a video-memory pool heap (64 MiB) -const POOL_TILES: u32 = 1024; +/// tiles of a video-memory pool heap (4 MiB). A heap goes back only when every tile of it is +/// free (`State::retire_free_pools`), and a title frees its tiles in runs spread over all its +/// heaps: with heaps of 64 MiB a retail title's world load unmapped 1.5 GB of its 4.6 GB of +/// tiles and 3 of 78 heaps went back (0.2 GB); with heaps of 4 MiB 1.25 GB went back. +const POOL_TILES: u32 = 64; /// tiles decommitted while no title work was submitted that stay mapped (`State::parked`) before /// they are unmapped together: 256 MB of video memory const PARKED_MAX: usize = 4096; @@ -614,7 +617,7 @@ impl State { return Some((t, true)); } // a pool retired a moment ago (its last tile came free) is taken back before a new - // 64 MB heap is made: freeing and allocating a tile in turn made a new pool each time, + // heap is made: freeing and allocating a tile in turn made a new pool each time, // up to 18 GB of retired heaps in 2 s (#913). Its tiles are reused as freed tiles are // (zeroed), so this is no less safe than reusing a tile of a pool in use. if let Some((heap, _, _)) = self.retired.pop() { @@ -654,7 +657,7 @@ impl State { h } - /// Pools whose every tile is free again go (64 MB of video memory each – and as much of the + /// Pools whose every tile is free again go (their video memory – and as much of the /// system's commit: a retail game's homes of physical pages left 0.75 GB of pools for /// 0.29 GB of tiles in use). Call after their tiles are unmapped and signalled. fn retire_free_pools(&mut self) { @@ -668,12 +671,13 @@ impl State { for &(h, _) in &self.free { count[h as usize] += 1; } - let gone: Vec = (0..count.len()).filter(|&h| count[h] == POOL_TILES && self.pools[h].is_some()).collect(); - if gone.is_empty() { + // (a flag a pool: a title's world load frees hundreds of pools' worth of tiles at once) + let gone: Vec = (0..count.len()).map(|h| count[h] == POOL_TILES && self.pools[h].is_some()).collect(); + if !gone.contains(&true) { return; } - self.free.retain(|&(h, _)| !gone.contains(&(h as usize))); - for h in gone { + self.free.retain(|&(h, _)| !gone[h as usize]); + for h in (0..gone.len()).filter(|&h| gone[h]) { if let Some(heap) = self.pools[h].take() { self.retired.push((heap, self.value, now)); } @@ -1813,7 +1817,7 @@ mod tests { /// Freeing the last tile in use of a pool and taking a tile again takes the retired pool - /// back, not a new 64 MB heap each time (#913: 288 pools, 18 GB asked of a 12 GB card). + /// back, not a new heap each time (#913: 288 pools of 64 MB, 18 GB asked of a 12 GB card). #[test] fn a_pool_retired_a_moment_ago_is_taken_back() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; @@ -1886,6 +1890,38 @@ mod tests { } } + /// A title frees its tiles in runs spread over all its pools: the pools of the freed runs go + /// back. With pools of 64 MiB none of these did (every pool kept the tiles still in use). + #[test] + fn pools_of_freed_runs_go_back() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + // 192 MiB of tiles, taken in order as a title's first commits take them + const TILES: usize = 3072; + let tiles: Vec<(u32, u32)> = (0..TILES).map(|_| s.take_tile().expect("a tile").0).collect(); + let made = s.pools.iter().filter(|p| p.is_some()).count(); + assert_eq!(made * POOL_TILES as usize, TILES, "the tiles fill whole pools"); + // of every 64 MiB the title keeps the first 4 MiB and frees the rest + let (mut kept, mut freed) = (0, 0); + for (i, &t) in tiles.iter().enumerate() { + if i % 1024 < 64 { + kept += 1; + } else { + s.free.push(t); + freed += 1; + } + } + s.retire_free_pools(); + let left = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize; + assert_eq!(s.free.len() + s.retired.len() * POOL_TILES as usize, freed, "every freed tile is free or its pool retired"); + assert!(left <= kept * 2, "{left} tiles of video memory stay in pools for {kept} tiles in use ({} MiB for {} MiB)", left * TILE >> 20, kept * TILE >> 20); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + #[test] fn aligned_tile_addresses_spread_across_hash_buckets() { use std::hash::BuildHasher; From 06d03e60f622142b304d3932e1a0c46ade9507c5 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:39:28 -0800 Subject: [PATCH 059/265] D3D12.X: reserve allocator state before native submission Capture and pin each list recording before ExecuteCommandLists can reach the driver. Associate the reservation with exactly one queue fence after native execution, and fail closed before later chunks if bookkeeping cannot be reserved. This closes the reset/release race between native execution and allocator retirement while preserving exact effects for the chunks that actually ran. Checked with the GNU Windows-target cargo check; Windows/MSVC, GPU, and title smoke execution were not available on this host. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 156 ++++++++++++++++++------ crates/xcl/src/hle/d3d12x/list_x.rs | 100 ++++++++++----- crates/xcl/src/hle/d3d12x/real.rs | 26 ++-- 3 files changed, 203 insertions(+), 79 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 1ae89cd2a4..1eb06682f2 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -260,9 +260,11 @@ fn release_submit_pins(s: &mut State, entries: &[SubmitEntry]) { } } -fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &ID3D12Fence, value: u64) { +fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &ID3D12Fence, value: u64) -> u64 { + let mut backing_mark_writes = 0; for entry in entries { if let Some(backing) = entry.backing { + backing_mark_writes += 1; s.backings.entry(backing).or_default().marks.insert(queue, (fence.clone(), value)); } if s.list_lifetimes.get(&entry.list) == Some(&entry.lifetime) { @@ -273,6 +275,7 @@ fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &I } } release_submit_pins(s, entries); + backing_mark_writes } /// Capture and pin the exact backing and recording that a native submit will execute. The caller @@ -346,7 +349,7 @@ impl PendingSubmit { if self.entries.is_empty() { return true; } - let mut g = STATE.lock().unwrap(); + let mut g = lock_for_submit(); let Some(s) = g.as_mut() else { return false }; let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return false }; let key = queue as usize; @@ -359,13 +362,17 @@ impl PendingSubmit { } let (fence, value) = { let (fence, value) = s.fences.get_mut(&key).unwrap(); + SUBMIT.signal_attempts.fetch_add(1, Ordering::Relaxed); if q.Signal(&*fence, *value + 1).is_err() { + SUBMIT.signal_failures.fetch_add(1, Ordering::Relaxed); return false; } *value += 1; (fence.clone(), *value) }; - record_submit(s, &self.entries, key, &fence, value); + let backing_mark_writes = record_submit(s, &self.entries, key, &fence, value); + SUBMIT.lists_marked.fetch_add(self.entries.len() as u64, Ordering::Relaxed); + SUBMIT.backing_mark_writes.fetch_add(backing_mark_writes, Ordering::Relaxed); self.entries.clear(); drop(g); sweep_release_owners(); @@ -375,11 +382,62 @@ impl PendingSubmit { #[cfg(test)] fn finish_with_mark(mut self, queue: usize, fence: &ID3D12Fence, value: u64) { let mut g = STATE.lock().unwrap(); - record_submit(g.as_mut().unwrap(), &self.entries, queue, fence, value); + let _ = record_submit(g.as_mut().unwrap(), &self.entries, queue, fence, value); self.entries.clear(); } } +fn reserve_and_execute_with( + failed: &mut bool, + begin: impl FnOnce() -> Option, + prepare: impl FnOnce(), + arm: impl FnOnce(B) -> P, + execute: impl FnOnce(), + finish: impl FnOnce(P) -> bool, +) -> bool { + if *failed { + return false; + } + let Some(begin) = begin() else { + *failed = true; + return false; + }; + prepare(); + let pending = arm(begin); + execute(); + let _ = finish(pending); + true +} + +#[derive(Default)] +pub(super) struct SubmissionGate { + failed: bool, +} + +impl SubmissionGate { + /// `prepare` runs before the reservation is armed; `execute` must contain only the native call. + pub(super) unsafe fn submit( + &mut self, + queue: *mut c_void, + lists: &[*mut c_void], + prepare: impl FnOnce(), + execute: impl FnOnce(), + ) -> bool { + reserve_and_execute_with( + &mut self.failed, + || begin_submit(lists), + prepare, + BeginSubmit::execution_possible, + execute, + |pending| pending.finish(queue), + ) + } + + pub(super) fn failed(&self) -> bool { + self.failed + } +} + /// `XCL_ALLOC_SWAP=0` turns it off. pub fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -510,43 +568,11 @@ pub fn in_flight(list: usize) -> bool { || s.last_submit.get(&list).is_some_and(|l| unsafe { l.fence.GetCompletedValue() } < l.value) } -/// `lists` were just submitted to `queue`. +/// Compatibility helper for tests that submit directly instead of using `SubmissionGate`. +#[cfg(test)] pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { - if !enabled() || queue.is_null() { - return; - } - // (every submit is marked, also of lists this module does not track – the PC lists behind - // console lists – so note_resubmits sees them all) - let mut g = lock_for_submit(); - let s = g.get_or_insert_with(State::default); - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; - let key = queue as usize; - if !s.fences.contains_key(&key) { - let mut dev: Option = None; - let Some(f) = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()) else { return }; - s.fences.insert(key, (f, 0)); - } - let (fence, value) = { - let (f, v) = s.fences.get_mut(&key).unwrap(); - SUBMIT.signal_attempts.fetch_add(1, Ordering::Relaxed); - if q.Signal(&*f, *v + 1).is_err() { - SUBMIT.signal_failures.fetch_add(1, Ordering::Relaxed); - return; - } - *v += 1; - (f.clone(), *v) - }; - let mut backing_mark_writes = 0u64; - for &l in lists { - if let Some(&b) = s.of_list.get(&(l as usize)) { - backing_mark_writes += 1; - s.backings.entry(b).or_default().marks.insert(key, (fence.clone(), value)); - } - let recording = s.recordings.get(&(l as usize)).copied().unwrap_or(0); - s.last_submit.insert(l as usize, LastSubmit { queue: key, fence: fence.clone(), value, recording }); - } - SUBMIT.lists_marked.fetch_add(lists.len() as u64, Ordering::Relaxed); - SUBMIT.backing_mark_writes.fetch_add(backing_mark_writes, Ordering::Relaxed); + let Some(begin) = begin_submit(lists) else { return }; + let _ = begin.execution_possible().finish(queue); } /// Whether the GPU may still run a recording made on the title's allocator `alloc`. @@ -811,6 +837,56 @@ mod tests { assert_eq!(execute_topology(4), (1, 3)); } + #[test] + fn reserved_submit_orders_prepare_arm_execute_and_finish() { + use std::cell::RefCell; + let calls = RefCell::new(Vec::new()); + let mut failed = false; + let submitted = reserve_and_execute_with( + &mut failed, + || { + calls.borrow_mut().push("begin"); + Some(1) + }, + || calls.borrow_mut().push("prepare"), + |begin| { + calls.borrow_mut().push("arm"); + begin + 1 + }, + || calls.borrow_mut().push("execute"), + |pending| { + calls.borrow_mut().push("finish-failed"); + assert_eq!(pending, 2); + false + }, + ); + assert!(submitted && !failed, "marker failure cannot undo a native execution"); + assert_eq!(*calls.borrow(), ["begin", "prepare", "arm", "execute", "finish-failed"]); + } + + #[test] + fn begin_failure_stops_later_chunks_and_publication() { + use std::cell::Cell; + let mut failed = false; + let executed = Cell::new(0); + let published = Cell::new(0); + for begin_succeeds in [true, false, true] { + let submitted = reserve_and_execute_with( + &mut failed, + || begin_succeeds.then_some(()), + || {}, + |()| (), + || executed.set(executed.get() + 1), + |_| true, + ); + if submitted { + published.set(published.get() + 1); + } + } + assert!(failed); + assert_eq!((executed.get(), published.get()), (1, 1)); + } + #[test] fn submit_reservation_keeps_pre_reset_attribution_across_queues() { use std::cell::Cell; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 83c6ec49fc..39e248baf0 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2468,15 +2468,16 @@ unsafe fn execute_submission_plan_with_completions( queue: *mut c_void, plan: &SubmissionPlan, external_waits: &[PendingWait], - mut submit: impl FnMut(SubmissionChunk<'_>) -> Option, -) -> Vec { + mut submit: impl FnMut(SubmissionChunk<'_>) -> (bool, Option), +) -> (Vec, bool) { let chunk = |start, end| SubmissionChunk { lists: &plan.lists[start..end], effects: &plan.effects[start..end], needs_cpu_completion: plan.chunk_needs_cpu_completion(start, end, external_waits), }; if !plan.has_waits { - return submit(chunk(0, plan.lists.len())).into_iter().collect(); + let (submitted, completion) = submit(chunk(0, plan.lists.len())); + return (completion.into_iter().collect(), submitted); } let mut completions = Vec::new(); let mut start = 0usize; @@ -2489,7 +2490,11 @@ unsafe fn execute_submission_plan_with_completions( continue; } if i > start { - completions.extend(submit(chunk(start, i))); + let (submitted, completion) = submit(chunk(start, i)); + if !submitted { + return (completions, false); + } + completions.extend(completion); } if after_cpu_write { for completion in completions.drain(..) { @@ -2500,25 +2505,37 @@ unsafe fn execute_submission_plan_with_completions( start = i; } if start < plan.lists.len() { - completions.extend(submit(chunk(start, plan.lists.len()))); + let (submitted, completion) = submit(chunk(start, plan.lists.len())); + if !submitted { + return (completions, false); + } + completions.extend(completion); } - completions + (completions, true) +} + +pub(super) unsafe fn execute_submission_plan_until_failure_on( + queue: *mut c_void, + plan: &SubmissionPlan, + submit: impl FnMut(SubmissionChunk<'_>) -> (bool, Option), +) -> (Vec, bool) { + execute_submission_plan_with_completions(queue, plan, &[], submit) } /// Execute a plan for an ordinary queue submission, retaining deferred CPU-write receipts. pub(super) unsafe fn execute_submission_plan_with_completions_on( queue: *mut c_void, plan: &SubmissionPlan, - submit: impl FnMut(SubmissionChunk<'_>) -> Option, + mut submit: impl FnMut(SubmissionChunk<'_>) -> Option, ) -> Vec { - execute_submission_plan_with_completions(queue, plan, &[], submit) + execute_submission_plan_with_completions(queue, plan, &[], |chunk| (true, submit(chunk))).0 } /// Execute an immutable submission plan, splitting before an unsatisfied memory wait. pub(super) unsafe fn execute_submission_plan_on(queue: *mut c_void, plan: &SubmissionPlan, mut submit: impl FnMut(SubmissionChunk<'_>)) { let _ = execute_submission_plan_with_completions(queue, plan, &[], |chunk| { submit(chunk); - None + (true, None) }); } @@ -3807,25 +3824,29 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let kickoff_split = super::title_list::reclaim_for_kickoff(this); let mut prior_cpu_completions = Vec::new(); let mut wait_after_cpu_write = false; + let mut gate = super::alloc_pool::SubmissionGate::default(); if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { let plan = submission_plan(prior); wait_after_cpu_write = plan.cpu_producer_overlaps(&waits, plan.effects.len()); - prior_cpu_completions = execute_submission_plan_with_completions(q_raw, &plan, &waits, |chunk| { + let mut submitted = Vec::with_capacity(prior.len()); + let (completions, _) = execute_submission_plan_with_completions(q_raw, &plan, &waits, |chunk| { let lists = chunk.lists(); - exec(q_raw, lists.len() as u32, lists.as_ptr()); + if !gate.submit(q_raw, lists, || {}, || exec(q_raw, lists.len() as u32, lists.as_ptr())) { + return (false, None); + } + submitted.extend_from_slice(lists); copy_scratch_submitted(q_raw, lists); - super::alloc_pool::executed(q_raw, lists); - chunk.submit_effects(q_raw) + (true, chunk.submit_effects(q_raw)) }); - super::title_textures::submitted(prior); - for &p in prior { + prior_cpu_completions = completions; + super::title_textures::submitted(&submitted); + for &p in &submitted { super::title_textures::list_reset(p as usize); } } } - - if !waits.is_empty() { + if !gate.failed() && !waits.is_empty() { if wait_after_cpu_write { for completion in prior_cpu_completions.drain(..) { let _ = completion.wait(); @@ -3835,19 +3856,25 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } let one = [this]; - exec(q_raw, 1, one.as_ptr()); - copy_scratch_submitted(q_raw, &one); - super::alloc_pool::executed(q_raw, &one); - signal_write64_pairs(q_raw, &write64_signals); - // what ran is in the textures' states; the list records anew after its Reset below - super::title_textures::submitted(&one); - super::title_textures::list_reset(this as usize); - if !sparse_writes.is_empty() { - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { - super::sparse::readback_after_execute(q, &sparse_writes); + let current_submitted = gate.submit(q_raw, &one, || {}, || exec(q_raw, 1, one.as_ptr())); + if current_submitted { + copy_scratch_submitted(q_raw, &one); + signal_write64_pairs(q_raw, &write64_signals); + // what ran is in the textures' states; the list records anew after its Reset below + super::title_textures::submitted(&one); + if !sparse_writes.is_empty() { + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { + super::sparse::readback_after_execute(q, &sparse_writes); + } + } + super::cpu_writes::after(q_raw, cpu_writes); + } else { + if once(&ERR, 8) { + crate::xlog_warn!("D3D12.X: KickoffX – could not reserve submission retirement state; resetting the unsubmitted recording"); } } - super::cpu_writes::after(q_raw, cpu_writes); + // Submitted or discarded, `this` starts a new recording in the common Reset tail. + super::title_textures::list_reset(this as usize); let target = if let Some((primary, _, reclaimed)) = kickoff_split { let (ended_early, pred_buf_obj, bindings_copy) = { @@ -5763,16 +5790,27 @@ mod tests { completed.store(true, Ordering::Release); let _ = done.send(()); }); - Some(receipt) + (true, Some(receipt)) } else { assert!(!chunk.needs_cpu_completion()); assert!(completed.load(Ordering::Acquire), "the CPU producer must complete before the wait segment is submitted"); - None + (true, None) } - }); + }).0; assert!(leftovers.is_empty()); } assert_eq!(chunks, vec![vec![producer], vec![continuation]]); + + let mut callbacks = 0; + let completed_all = unsafe { + execute_submission_plan_with_completions(std::ptr::null_mut(), &plan, &[], |_| { + callbacks += 1; + (false, None) + }) + .1 + }; + assert!(!completed_all); + assert_eq!(callbacks, 1, "a failed first chunk suppresses later waits and submissions"); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 8b9136e97d..2cc2d75a43 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7377,19 +7377,29 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis let plan = super::list_x::submission_plan(&mapped); drop(preparation_stall); let mut chunks = 0usize; - let _ = super::list_x::execute_submission_plan_with_completions_on(this, &plan, |chunk| { - chunks += 1; + let mut gate = super::alloc_pool::SubmissionGate::default(); + let mut submitted = Vec::with_capacity(mapped.len()); + let _ = super::list_x::execute_submission_plan_until_failure_on(this, &plan, |chunk| { let lists = chunk.lists(); - let _ = super::alloc_pool::note_resubmits(this, lists); - f(this, lists.len() as u32, lists.as_ptr()); + if !gate.submit( + this, + lists, + || { + let _ = super::alloc_pool::note_resubmits(this, lists); + }, + || f(this, lists.len() as u32, lists.as_ptr()), + ) { + return (false, None); + } + chunks += 1; + submitted.extend_from_slice(lists); super::list_x::copy_scratch_submitted(this, lists); - super::alloc_pool::executed(this, lists); - chunk.submit_effects(this) + (true, chunk.submit_effects(this)) }); super::alloc_pool::note_execute_call(chunks); // the next uploads into textures kept in step start from the states these lists leave - super::title_textures::submitted(&mapped); - super::present::note_execute(this, &mapped); + super::title_textures::submitted(&submitted); + super::present::note_execute(this, &submitted); stop_if_device_removed(); } From aff341e1697f4f738a6a08c1efb04b27a2e7fad9 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:39:47 -0800 Subject: [PATCH 060/265] D3D12.X: keep cold pipeline builds off title threads Publish foreground demand before scheduling a cold shared build, then wait for the worker result instead of taking the build job onto the binding title thread. This preserves exact pipeline and compute semantics while moving long DXC and driver work out of correctness-critical title execution. GNU Windows-target cargo check passed. Test linking was unavailable because this Linux host lacks the MinGW dlltool; Windows/MSVC and runtime execution were not tested. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 57 ++++++++++++++++++++------ 1 file changed, 44 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index aef496504f..1a9779a2c1 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -40,7 +40,7 @@ struct Pending { /// A pipeline build independent of the title-visible stand-ins that requested it. struct Build { compute_key: Option>, - /// the build, until a worker – or a bind that cannot wait for the queue – takes it + /// the build, until a worker takes it job: Mutex>, /// the build went to the workers (a lazy one goes on its first `resolve`) sent: std::sync::atomic::AtomicBool, @@ -176,9 +176,10 @@ impl Build { fn want(&self) { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_PRIORITY_NORMAL, THREAD_SET_LIMITED_INFORMATION}; + let newly_wanted = !self.wanted.swap(true, Ordering::AcqRel); start_normal_workers(); self.promote(Priority::Foreground); - if !self.wanted.swap(true, Ordering::AcqRel) { + if newly_wanted { let d = self.demand.lock().unwrap(); if d.preload_thread == 0 { return; @@ -537,7 +538,7 @@ fn build_queued(build: &Arc) -> bool { drop_unstarted_job(build); return false; } - // (None: a bind took it and builds it itself) + // (None: an orphaned build was dropped before this queued work ran) let job = build.job.lock().unwrap().take(); if let Some(job) = job { run_build(build, job); @@ -842,6 +843,40 @@ mod used_tests { assert_eq!(released(standins[1]), 0xC101, "the last stand-in releases the one owned reference"); } + #[test] + fn no_budget_wait_runs_a_shared_build_on_a_wanted_worker() { + let standins = [0x7E57_C701usize, 0x7E57_C702]; + let (started_tx, started_rx) = mpsc::channel(); + let (finish_tx, finish_rx) = mpsc::channel::<()>(); + submit_compute(standins[0], 0xC7, Box::new(move || { + started_tx.send((std::thread::current().name().map(str::to_owned), build_is_wanted(), wanted_here()())).unwrap(); + let _ = finish_rx.recv(); + 0xC701 + })); + submit_compute(standins[1], 0xC7, Box::new(|| panic!("duplicate shared build ran"))); + let (a, b) = (entry(standins[0]).unwrap(), entry(standins[1]).unwrap()); + assert!(Arc::ptr_eq(&a.build, &b.build), "equal compute requests share one Build"); + + let (result_tx, result_rx) = mpsc::channel(); + let waiters: Vec<_> = standins.iter().map(|&standin| { + let result_tx = result_tx.clone(); + std::thread::spawn(move || result_tx.send((standin, resolve_wait_for(standin, None))).unwrap()) + }).collect(); + drop(result_tx); + let (thread, wanted, wanted_probe) = started_rx.recv_timeout(std::time::Duration::from_secs(10)).expect("a worker did not start the build"); + assert!(thread.as_deref().is_some_and(|name| name.starts_with("xcl-pso-")), "build ran on caller {thread:?}"); + assert!(wanted && wanted_probe, "the worker did not observe foreground demand"); + assert!(matches!(result_rx.try_recv(), Err(mpsc::TryRecvError::Empty)), "a caller returned before the build finished"); + + finish_tx.send(()).unwrap(); + let mut results: Vec<_> = result_rx.iter().collect(); + results.sort_unstable(); + for waiter in waiters { waiter.join().unwrap(); } + assert_eq!(results, [(standins[0], 0xC701), (standins[1], 0xC701)]); + assert_eq!(released(standins[0]), 0); + assert_eq!(released(standins[1]), 0xC701); + } + #[test] fn unequal_compute_keys_keep_separate_builds() { let standins = [0x7E57_C201usize, 0x7E57_C202]; @@ -1496,8 +1531,7 @@ pub fn resolve(pso: usize) -> usize { } } -/// `resolve`, waiting for a pipeline still being built – built here if no worker has started -/// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). +/// `resolve`, waiting for a pipeline still being built on a foreground worker. pub fn resolve_wait(pso: usize) -> usize { resolve_wait_for(pso, wait_budget()) } @@ -1516,12 +1550,10 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { if let Some(budget) = budget { return resolve_within(&p, pso, budget); } - let job = p.build.job.lock().unwrap().take(); - if let Some(job) = job { - p.build.cancel_queued(); - complete(&p.build, job()); - } + // Mark it wanted before an unsent build is queued: the worker and its DXC/driver admission + // see demand from their first instruction. An already queued build is promoted by `want`. p.build.want(); + schedule(&p.build, Priority::Foreground, false, None); let mut done = p.build.done.lock().unwrap(); while !*done { done = p.build.cv.wait(done).unwrap(); @@ -1533,9 +1565,8 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { } /// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until -/// it is built). A retail game builds compute programs on its own threads: the driver takes up to -/// 30 s for the biggest translated ones, and the title's watchdog ends it when its main thread -/// has been held 30 s. +/// it is built). A retail game's foreground worker can spend over 30 s in the driver on the +/// biggest translated programs; the waiting title thread remains held for that time. fn wait_budget() -> Option { static B: OnceLock> = OnceLock::new(); *B.get_or_init(|| std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()).filter(|&ms| ms > 0).map(std::time::Duration::from_millis)) From 11cf89f91f61b3375250963f1afddaa5f2d90cf0 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:44:54 -0800 Subject: [PATCH 061/265] D3D12.X: mark deferred pipelines wanted at record time Publish wanted demand as soon as a dispatch is deferred to submission. The shared Build is promoted before scheduling, so DXC and driver admission see correctness-critical demand immediately without restoring title-thread compilation. The bounded wanted-build concurrency makes the old four-segment lookahead unnecessary. GNU Windows-target cargo check passed. Focused test linking was unavailable because this Linux host lacks MinGW dlltool; Windows/MSVC and runtime execution were not tested. Adapted from PR #2579. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 5 -- crates/xcl/src/hle/d3d12x/list_x.rs | 8 +-- crates/xcl/src/hle/d3d12x/pso_async.rs | 74 +++++++++++++++++++------- 3 files changed, 57 insertions(+), 30 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 5c6619cde3..a43c46923c 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -146,11 +146,6 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u install_prepared_split(prepare_split(from, to, allocator)); } -/// A submit is about to wait for the pipeline `this` has bound. -pub(super) fn want_bound(this: *mut c_void) { - super::pso_async::want(with(this, |s| s.pso)); -} - /// A put-off dispatch that could not be recorded. pub(super) fn dispatch_dropped() { count(DISPATCHES_SKIPPED); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 39e248baf0..6bd30154bb 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3098,9 +3098,6 @@ pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { true } -/// Builds of a submit's put-off calls that go on without the commit headroom, as a title thread's own do: about what the title's threads had in the driver at once before. -const WANTED_AT_ONCE: usize = 4; - /// Records the deferred dispatches of `wrapper`'s recording, waiting for their pipelines as a bind did. pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { let mut segs = Vec::new(); @@ -3108,10 +3105,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { let Some(&first) = segs.first() else { return }; segs.retain(|&seg| seg == first || LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(seg as usize))).is_some_and(|s| s.deferred.is_some())); let mut last: Option<*mut c_void> = None; - for (i, &seg) in segs.iter().enumerate().skip(1) { - for &ahead in segs[i..].iter().take(WANTED_AT_ONCE) { - super::bind::want_bound(ahead); - } + for &seg in segs.iter().skip(1) { let Some((what, ty, heaps)) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(seg as usize))).and_then(|s| Some((s.deferred.take()?, s.list_type?, s.bindings.heaps.clone()))) else { continue; }; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 1a9779a2c1..fb724725eb 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -53,7 +53,8 @@ struct Build { orphan: std::sync::atomic::AtomicBool, /// Title-visible `Pending`s sharing this build. Changed while holding `done`. owners: AtomicUsize, - /// One of the title's threads waits for this build. Polled by DXC admission. + /// One of the title's threads waits, or a recorded submit will wait, for this build. Polled + /// by DXC and driver admission. wanted: AtomicBool, demand: Mutex, queued: Mutex>, @@ -171,8 +172,8 @@ impl Build { } } - /// One of the title's threads is about to wait for it: the worker building it goes on now, - /// at a normal priority. + /// One of the title's threads waits or a recorded submit will wait for it: the worker + /// building it goes on now, at a normal priority. fn want(&self) { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_PRIORITY_NORMAL, THREAD_SET_LIMITED_INFORMATION}; @@ -924,6 +925,30 @@ mod used_tests { assert_eq!(released(standins[1]), 0xC401); } + #[test] + fn submit_demand_is_shared_by_coalesced_stand_ins() { + let standins = [0x7E57_C411usize, 0x7E57_C412]; + let (wanted_tx, wanted_rx) = mpsc::channel(); + let (go_tx, go_rx) = mpsc::channel(); + submit_compute(standins[0], 0xD7, Box::new(move || { + wanted_tx.send(build_is_wanted()).unwrap(); + go_rx.recv().unwrap(); + 0xC411 + })); + submit_compute(standins[1], 0xD7, Box::new(|| panic!("duplicate job ran"))); + let build = entry(standins[0]).unwrap().build.clone(); + assert!(Arc::ptr_eq(&build, &entry(standins[1]).unwrap().build)); + + need_by_submit(standins[1]); + assert!(build.wanted.load(Ordering::Acquire)); + assert!(wanted_rx.recv_timeout(std::time::Duration::from_secs(10)).expect("a worker builds it")); + go_tx.send(()).unwrap(); + assert_eq!(resolve_wait_for(standins[0], None), 0xC411); + assert_eq!(resolve_wait_for(standins[1], None), 0xC411); + assert_eq!(released(standins[0]), 0); + assert_eq!(released(standins[1]), 0xC411); + } + #[test] fn releasing_one_waiter_does_not_orphan_shared_build() { let standins = [0x7E57_C501usize, 0x7E57_C502]; @@ -1152,6 +1177,24 @@ mod used_tests { } } + #[test] + fn a_build_a_submit_needs_is_wanted_from_record_time() { + let standin = 0x7E57_B006usize; + let (started_tx, started) = mpsc::channel(); + submit(standin, true, Box::new(move || { + started_tx.send(()).unwrap(); + let t = std::time::Instant::now(); + while !build_is_wanted() && t.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + if build_is_wanted() { 0x5757 } else { 0 } + })); + started.recv_timeout(std::time::Duration::from_secs(10)).expect("a worker did not start the build"); + need_by_submit(standin); + assert_eq!(resolve_wait_for(standin, None), 0x5757, "record-time demand did not reach the running build"); + assert_eq!(released(standin), 0x5757); + } + /// A bind waits for a pipeline still being built no longer than its budget and goes on with /// the stand-in; later binds do not wait for it again; once built it is the real one. #[test] @@ -1176,19 +1219,19 @@ mod used_tests { let _ = released(standin); } - /// DXC admission probes demand while holding its own queue lock: the probe cannot take this - /// build's demand lock, and submit demand is intentionally not a title-thread wait. + /// DXC admission probes demand while holding its own queue lock: submit demand is published + /// through the atomic wanted signal, so the probe cannot take this build's demand lock. #[test] - fn wanted_probe_is_lock_free_and_excludes_submit_demand() { + fn submit_demand_wanted_probe_is_lock_free() { let build = Arc::new(Build::new(Box::new(|| 0), false)); let before = BUILDING.with(|building| building.replace(Some(build.clone()))); let _restore = RestoreBuilding(before); let wanted = wanted_here(); build.demand.lock().unwrap().by_submit = true; - assert!(!wanted(), "submit demand does not mean a title thread is waiting"); + build.want(); + assert!(wanted(), "submit demand reaches DXC and driver admission"); let demand = build.demand.lock().unwrap(); - build.wanted.store(true, Ordering::Release); let (tx, rx) = mpsc::channel(); let thread = std::thread::spawn(move || tx.send(wanted()).unwrap()); assert!(rx.recv_timeout(std::time::Duration::from_secs(2)).expect("wanted probe took the demand lock")); @@ -1683,19 +1726,14 @@ pub fn is_pending(pso: usize) -> bool { entry(pso).is_some_and(|p| !*p.build.done.lock().unwrap()) } -/// One of the title's threads is about to wait for `pso`. -pub fn want(pso: usize) { - if let Some(p) = entry(pso) { - p.build.want(); - } -} - -/// A call with `pso` was put off to the submit: its build goes before the workers' queue. +/// A call with `pso` was put off to the submit, which will wait for it: its shared build is +/// wanted from record time and goes before the workers' queue. pub fn need_by_submit(pso: usize) { let Some(p) = entry(pso) else { return }; - if !std::mem::replace(&mut p.build.demand.lock().unwrap().by_submit, true) { + p.build.want(); + let first = !std::mem::replace(&mut p.build.demand.lock().unwrap().by_submit, true); + if first { schedule(&p.build, Priority::BoundSoon, false, None); - p.build.promote(Priority::Foreground); } } From 4e62e7c8c44cad58ee0f62aa41cdf724f706d6ed Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:46:01 -0800 Subject: [PATCH 062/265] D3D12.X: classify the pipeline selected by ExecuteIndirect Return ExecuteIndirect's resolved pipeline and the unbuilt state of that exact bound choice from one captured Pending. A build completing between resolution and classification can no longer send a stale stand-in to the driver with an incompatible root signature. The shared Build completion state distinguishes a successful late completion from the permanent fallback of a failed build. GNU Windows-target cargo check passed. Windows/MSVC, GPU, and title smoke execution were not available on this host. Adapted from PR #2598. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 4 +- crates/xcl/src/hle/d3d12x/pso_async.rs | 119 ++++++++++++++++++++----- 2 files changed, 99 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 5c6619cde3..cb07a58ced 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -299,7 +299,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if unbuilt_compute && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { return super::pso_async::need_by_submit(raw_pso); } - let pso = super::pso_async::resolve_wait(raw_pso); + let (pso, bound_unbuilt) = super::pso_async::resolve_wait_bound(raw_pso); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if !gfx && !compute { @@ -308,7 +308,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // call with that pair is invalid (debug layer 953, "the currently set Root Signature // doesn't match the currently set Pipeline State Object"; a retail title's world then // hung the GPU, 0x887a0006). Skipped, like a draw or dispatch of such a pipeline. - if super::pso_async::is_pending(raw_pso) { + if bound_unbuilt { count(DRAWS_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 1a9779a2c1..7bc05b6607 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -843,6 +843,53 @@ mod used_tests { assert_eq!(released(standins[1]), 0xC101, "the last stand-in releases the one owned reference"); } + #[test] + fn bound_state_follows_the_choice_from_a_shared_build() { + let standins = [0x7E57_C111usize, 0x7E57_C112]; + let drivers = [0x7E57_D111usize, 0x7E57_D112]; + let (started_tx, started_rx) = mpsc::channel(); + let (finish_tx, finish_rx) = mpsc::channel::<()>(); + submit_compute(standins[0], 0xE6, Box::new(move || { + started_tx.send(()).unwrap(); + finish_rx.recv().unwrap(); + 0xC111 + })); + submit_compute(standins[1], 0xE6, Box::new(|| panic!("duplicate shared build ran"))); + for (&standin, &driver) in standins.iter().zip(&drivers) { + shared(standin, driver); + image_only(standin); + } + + let before = standins.map(|standin| resolve_wait_bound_for(standin, None)); + assert_eq!(before, [(drivers[0], true), (drivers[1], true)]); + started_rx.recv_timeout(std::time::Duration::from_secs(10)).expect("a worker did not start the build"); + finish_tx.send(()).unwrap(); + let start = std::time::Instant::now(); + while is_pending(standins[0]) && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!is_pending(standins[0]), "shared build did not finish"); + for ((&standin, &driver), &(bound, _)) in standins.iter().zip(&drivers).zip(&before) { + let pending = entry(standin).unwrap(); + assert!(pending.bound_unbuilt(standin, bound), "the earlier driver stand-in stays unbuilt"); + assert_eq!(resolve_wait_bound_for(standin, None), (0xC111, false)); + assert_ne!(driver, 0xC111); + } + assert_eq!(released(standins[0]), 0); + assert_eq!(released(standins[1]), 0xC111); + } + + #[test] + fn a_failed_builds_permanent_stand_in_is_not_unbuilt() { + let standin = 0x7E57_C121usize; + let driver = 0x7E57_D121usize; + submit_lazy(standin, true, Box::new(|| 0), 0); + shared(standin, driver); + assert_eq!(resolve_wait_bound_for(standin, None), (driver, false)); + assert_eq!(resolve_wait_bound_for(0x7E57_C122, None), (0x7E57_C122, false)); + assert_eq!(released(standin), 0); + } + #[test] fn no_budget_wait_runs_a_shared_build_on_a_wanted_worker() { let standins = [0x7E57_C701usize, 0x7E57_C702]; @@ -1504,6 +1551,13 @@ impl Pending { d => d, } } + + /// `bound` was this pending pipeline's stand-in before its build finished successfully. + /// A failed build keeps its stand-in permanently, so that is a finished pipeline choice. + fn bound_unbuilt(&self, pso: usize, bound: usize) -> bool { + let done = self.build.done.lock().unwrap(); + bound == self.stand(pso) && !(*done && self.build.real.load(Ordering::Acquire) == 0) + } } /// Stand-in `standin` is no driver object (`standin::shell`): binds get `driver` in its place. @@ -1536,32 +1590,53 @@ pub fn resolve_wait(pso: usize) -> usize { resolve_wait_for(pso, wait_budget()) } +/// The pipeline to bind and whether that exact choice was a stand-in for an unfinished build. +/// The answer stays true if a successful build ends after this bind chose its stand-in. +pub fn resolve_wait_bound(pso: usize) -> (usize, bool) { + resolve_wait_bound_for(pso, wait_budget()) +} + /// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). fn resolve_wait_for(pso: usize, budget: Option) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); - if p.spared.load(Ordering::Acquire) { - return resolve_spared(&p, pso); - } - // (the title's thread is held from here until the pipeline is built or the budget is over) - let waiting = !*p.build.done.lock().unwrap(); - let _held = waiting.then(Held::new); - let _stall = waiting.then(|| crate::stall::span(crate::stall::StallKind::PipelineWait)).flatten(); - if let Some(budget) = budget { - return resolve_within(&p, pso, budget); - } - // Mark it wanted before an unsent build is queued: the worker and its DXC/driver admission - // see demand from their first instruction. An already queued build is promoted by `want`. - p.build.want(); - schedule(&p.build, Priority::Foreground, false, None); - let mut done = p.build.done.lock().unwrap(); - while !*done { - done = p.build.cv.wait(done).unwrap(); - } - match p.build.real.load(Ordering::Acquire) { - 0 => p.stand(pso), - r => r, - } + resolve_wait_pending(&p, pso, budget) +} + +fn resolve_wait_bound_for(pso: usize, budget: Option) -> (usize, bool) { + let Some(p) = entry(pso) else { return (pso, false) }; + p.note_use(); + let bound = resolve_wait_pending(&p, pso, budget); + (bound, p.bound_unbuilt(pso, bound)) +} + +fn resolve_wait_pending(p: &Arc, pso: usize, budget: Option) -> usize { + let bound = if p.spared.load(Ordering::Acquire) { + resolve_spared(p, pso) + } else { + // (the title's thread is held from here until the pipeline is built or the budget is over) + let waiting = !*p.build.done.lock().unwrap(); + let _held = waiting.then(Held::new); + let _stall = waiting.then(|| crate::stall::span(crate::stall::StallKind::PipelineWait)).flatten(); + if let Some(budget) = budget { + resolve_within(p, pso, budget) + } else { + // Mark it wanted before an unsent build is queued: the worker and its DXC/driver + // admission see demand from their first instruction. An already queued build is + // promoted by `want`. + p.build.want(); + schedule(&p.build, Priority::Foreground, false, None); + let mut done = p.build.done.lock().unwrap(); + while !*done { + done = p.build.cv.wait(done).unwrap(); + } + match p.build.real.load(Ordering::Acquire) { + 0 => p.stand(pso), + r => r, + } + } + }; + bound } /// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until From 76e87252f093675a8d0d96e68fda01f6c683b5e6 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:47:45 -0800 Subject: [PATCH 063/265] D3D12.X: avoid deferred segments for bounded pipeline waits When XCL_PSO_WAIT_MS is positive, record a dispatch immediately and use the same bounded bind wait instead of splitting one deferred command-list segment per call. This prevents bounded mode from exhausting command-list memory during large cold-pipeline bursts. Unset, zero, and malformed values preserve the default deferred-submit path. The change is stacked on atomic ExecuteIndirect stand-in classification. GNU Windows-target cargo check passed. Windows/MSVC, GPU, and title smoke execution were not available on this host. Adapted from PR #2581. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 19 ++++++++++++++++++- crates/xcl/src/hle/d3d12x/pso_async.rs | 6 ++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 6bd30154bb..4281d2e13c 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3087,7 +3087,11 @@ fn wait_target_after_split(list: *mut c_void, placement: WaitPlacement, continua /// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { - if split_recording(list, SegmentReason::DeferredDispatch(what)).is_none() { + // A bounded bind records now and waits for the same bound. Deferring it only adds a segment; + // thousands of these exhausted command-list memory in a retail title with a 1 ms budget. + if !defer_pipeline_wait(super::pso_async::waits_bounded(), || { + split_recording(list, SegmentReason::DeferredDispatch(what)).is_some() + }) { return false; } static N: AtomicU64 = AtomicU64::new(0); @@ -3098,6 +3102,10 @@ pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { true } +fn defer_pipeline_wait(waits_bounded: bool, split: impl FnOnce() -> bool) -> bool { + !waits_bounded && split() +} + /// Records the deferred dispatches of `wrapper`'s recording, waiting for their pipelines as a bind did. pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { let mut segs = Vec::new(); @@ -5814,6 +5822,15 @@ mod tests { assert_eq!(SegmentReason::DeferredDispatch(Deferred::Dispatch(1, 2, 3)).extra_segments(), 2); } + #[test] + fn bounded_pipeline_wait_does_not_allocate_a_deferred_segment() { + let mut splits = 0; + assert!(!defer_pipeline_wait(true, || { splits += 1; true })); + assert_eq!(splits, 0); + assert!(defer_pipeline_wait(false, || { splits += 1; true })); + assert_eq!(splits, 1, "the default still defers to the submit"); + } + #[test] fn failed_split_preflight_does_not_consume_recording_state() { let query = (0x7000, 2); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 2a7be716a1..36c522ffbe 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1690,6 +1690,12 @@ fn wait_budget() -> Option { *B.get_or_init(|| std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()).filter(|&ms| ms > 0).map(std::time::Duration::from_millis)) } +/// Whether binds have an explicit time bound. A dispatch is then recorded immediately instead of +/// deferred to the submit, where it would only wait for the same bound. +pub(super) fn waits_bounded() -> bool { + wait_budget().is_some() +} + /// `resolve_wait` for at most `budget`: the build goes to the workers (not this thread), and a /// pipeline not built by then is `late` – it and later binds of it get the stand-in (their /// dispatches are skipped) until a worker has built it. From 3cf3451c79ac4ed679fdec9e0abaa59d847b7bcb Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 08:21:00 +0300 Subject: [PATCH 064/265] Recompiler: assemble DXIL containers with one bitcode copy Write the DXIL program header and bitcode directly into one exactly sized container allocation. Remove intermediate part, string, and signature allocations while preserving all public formats and digest coverage. Keep an independent golden full-PSV byte fixture from the prior serializer so a same-length field reordering cannot hide behind the new assembly helpers. The upstream release microbenchmark reported 2.18-2.47x faster 1-2 MiB container assembly. GNU Windows-target cargo check passed here; Windows/MSVC, GPU tests, and title smoke were not run on this host. Adapted from PR #2664. Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/container.rs | 342 ++++++++++++++++++--------- 1 file changed, 234 insertions(+), 108 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/container.rs b/crates/xcl/src/gpu/dxil/container.rs index b92b10ede7..903538ce14 100644 --- a/crates/xcl/src/gpu/dxil/container.rs +++ b/crates/xcl/src/gpu/dxil/container.rs @@ -134,24 +134,31 @@ fn fourcc(s: &[u8; 4]) -> u32 { u32::from_le_bytes(*s) } -/// The `DXIL` part: program header, bitcode header, bitcode. -fn program_part(stage: Stage, sm: (u32, u32), dxil_version: (u32, u32), bitcode: &[u8]) -> Vec { - assert!(bitcode.len() % 4 == 0); - let mut p = Vec::with_capacity(24 + bitcode.len()); - let total = 24 + bitcode.len(); - p.extend_from_slice(&(((stage as u32) << 16) | (sm.0 << 4) | sm.1).to_le_bytes()); - p.extend_from_slice(&((total / 4) as u32).to_le_bytes()); - p.extend_from_slice(&fourcc(b"DXIL").to_le_bytes()); - p.extend_from_slice(&((dxil_version.0 << 8) | dxil_version.1).to_le_bytes()); - p.extend_from_slice(&16u32.to_le_bytes()); - p.extend_from_slice(&(bitcode.len() as u32).to_le_bytes()); - p.extend_from_slice(bitcode); - p +/// The 24-byte `DXIL` part header: program header + bitcode header. +fn program_header(stage: Stage, sm: (u32, u32), dxil_version: (u32, u32), bitcode_len: usize) -> [u8; 24] { + assert!(bitcode_len % 4 == 0); + let words = [ + ((stage as u32) << 16) | (sm.0 << 4) | sm.1, + ((24 + bitcode_len) / 4) as u32, + fourcc(b"DXIL"), + (dxil_version.0 << 8) | dxil_version.1, + 16u32, + bitcode_len as u32, + ]; + let mut hdr = [0u8; 24]; + for (i, v) in words.into_iter().enumerate() { + hdr[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes()); + } + hdr } /// PSV0 with `PSVRuntimeInfo3` (validator 1.8+). fn psv_part(psv: &Psv) -> Vec { - let mut p = Vec::new(); + let str_raw = psv.entry.len() + 2; + let str_len = str_raw.next_multiple_of(4); + let res_len = if psv.resources.is_empty() { 0 } else { 4 + 24 * psv.resources.len() }; + let exact_len = 68 + res_len + str_len; + let mut p = Vec::with_capacity(exact_len); let w = |p: &mut Vec, v: u32| p.extend_from_slice(&v.to_le_bytes()); w(&mut p, 52); p.extend_from_slice(&[0; 16]); // stage-specific union (none for compute) @@ -174,60 +181,69 @@ fn psv_part(psv: &Psv) -> Vec { } } // String table: "" then the entry name, padded to 4 bytes. - let mut strings = vec![0u8]; - strings.extend_from_slice(psv.entry.as_bytes()); - strings.push(0); - while strings.len() % 4 != 0 { - strings.push(0); - } - w(&mut p, strings.len() as u32); - p.extend_from_slice(&strings); + w(&mut p, str_len as u32); + p.push(0); + p.extend_from_slice(psv.entry.as_bytes()); + p.push(0); + p.extend_from_slice(&[0u8; 3][..str_len - str_raw]); w(&mut p, 0); // semantic index table + debug_assert_eq!(p.len(), exact_len); p } -/// An empty input / output signature. -fn empty_signature() -> Vec { - let mut p = Vec::new(); - p.extend_from_slice(&0u32.to_le_bytes()); - p.extend_from_slice(&8u32.to_le_bytes()); - p -} +/// An empty input / output signature (`0u32`, `8u32` LE). +const EMPTY_SIGNATURE: [u8; 8] = [0, 0, 0, 0, 8, 0, 0, 0]; -/// Builds the signed container for a DXIL program. -pub fn container(stage: Stage, sm: (u32, u32), bitcode: &[u8], features: u64, psv: &Psv) -> Vec { +/// Assembles and signs a DXBC container directly from borrowed prefix parts and `bitcode` +/// (single bitcode copy, exact allocation). +fn assemble_container(prefix_parts: &[([u8; 4], &[u8])], stage: Stage, sm: (u32, u32), bitcode: &[u8]) -> Vec { let dxil_version = (1, sm.1.min(8)); - let parts: Vec<([u8; 4], Vec)> = vec![ - (*b"SFI0", features.to_le_bytes().to_vec()), - (*b"ISG1", empty_signature()), - (*b"OSG1", empty_signature()), - (*b"PSV0", psv_part(psv)), - (*b"DXIL", program_part(stage, sm, dxil_version, bitcode)), - ]; - let header = 32 + 4 * parts.len(); - let total: usize = header + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); + let dxil_hdr = program_header(stage, sm, dxil_version, bitcode.len()); + let dxil_len = dxil_hdr.len() + bitcode.len(); + let part_count = prefix_parts.len() + 1; + let header = 32 + 4 * part_count; + let total = header + prefix_parts.iter().map(|(_, d)| 8 + d.len()).sum::() + 8 + dxil_len; let mut out = Vec::with_capacity(total); out.extend_from_slice(b"DXBC"); out.extend_from_slice(&[0; 16]); out.extend_from_slice(&1u16.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&(total as u32).to_le_bytes()); - out.extend_from_slice(&(parts.len() as u32).to_le_bytes()); + out.extend_from_slice(&(part_count as u32).to_le_bytes()); let mut off = header; - for (_, d) in &parts { + for (_, d) in prefix_parts { out.extend_from_slice(&(off as u32).to_le_bytes()); off += 8 + d.len(); } - for (cc, d) in &parts { + out.extend_from_slice(&(off as u32).to_le_bytes()); + for (cc, d) in prefix_parts { out.extend_from_slice(cc); out.extend_from_slice(&(d.len() as u32).to_le_bytes()); out.extend_from_slice(d); } + out.extend_from_slice(b"DXIL"); + out.extend_from_slice(&(dxil_len as u32).to_le_bytes()); + out.extend_from_slice(&dxil_hdr); + out.extend_from_slice(bitcode); + debug_assert_eq!(out.len(), total); let digest = hash(&out[20..]); out[4..20].copy_from_slice(&digest); out } +/// Builds the signed container for a DXIL program. +pub fn container(stage: Stage, sm: (u32, u32), bitcode: &[u8], features: u64, psv: &Psv) -> Vec { + let sfi0 = features.to_le_bytes(); + let psv_bytes = psv_part(psv); + let prefix = [ + (*b"SFI0", sfi0.as_slice()), + (*b"ISG1", EMPTY_SIGNATURE.as_slice()), + (*b"OSG1", EMPTY_SIGNATURE.as_slice()), + (*b"PSV0", psv_bytes.as_slice()), + ]; + assemble_container(&prefix, stage, sm, bitcode) +} + // ------------------------------------------------- graphics signatures /// One row of an `ISG1`/`OSG1`/`PSG1` signature (`DxilProgramSignatureElement`). @@ -253,11 +269,11 @@ pub struct SigPartElement { /// (DXC writes names in declaration order while sorting elements by register). pub fn signature_part(elems: &[SigPartElement], name_order: &[&str]) -> Vec { let mut strings: Vec = Vec::new(); - let mut offs: Vec<(String, u32)> = Vec::new(); + let mut offs: Vec<(&str, u32)> = Vec::with_capacity(name_order.len() + elems.len()); let base = 8 + 32 * elems.len() as u32; for n in name_order.iter().copied().chain(elems.iter().map(|e| e.name.as_str())) { - if !offs.iter().any(|(s, _)| s == n) { - offs.push((n.to_string(), base + strings.len() as u32)); + if !offs.iter().any(|&(s, _)| s == n) { + offs.push((n, base + strings.len() as u32)); strings.extend_from_slice(n.as_bytes()); strings.push(0); } @@ -265,12 +281,13 @@ pub fn signature_part(elems: &[SigPartElement], name_order: &[&str]) -> Vec while strings.len() % 4 != 0 { strings.push(0); } - let mut p = Vec::new(); + let exact_len = 8 + 32 * elems.len() + strings.len(); + let mut p = Vec::with_capacity(exact_len); let w = |p: &mut Vec, v: u32| p.extend_from_slice(&v.to_le_bytes()); w(&mut p, elems.len() as u32); w(&mut p, 8); for e in elems { - let off = offs.iter().find(|(s, _)| *s == e.name).unwrap().1; + let off = offs.iter().find(|&&(s, _)| s == e.name).unwrap().1; for v in [e.stream, off, e.index, e.system_value, e.comp_type, e.register] { w(&mut p, v); } @@ -278,6 +295,7 @@ pub fn signature_part(elems: &[SigPartElement], name_order: &[&str]) -> Vec w(&mut p, e.min_precision); } p.extend_from_slice(&strings); + debug_assert_eq!(p.len(), exact_len); p } @@ -330,24 +348,15 @@ pub struct PsvFull { /// Writes PSV0 for [`PsvFull`]. pub fn psv_part_full(psv: &PsvFull) -> Vec { - let mut p = Vec::new(); - let w = |p: &mut Vec, v: u32| p.extend_from_slice(&v.to_le_bytes()); - w(&mut p, 52); - p.extend_from_slice(&psv.stage_info); - w(&mut p, psv.min_wave); - w(&mut p, psv.max_wave); - p.extend_from_slice(&[psv.stage as u8, psv.uses_view_id as u8, psv.info1[0], psv.info1[1]]); - p.extend_from_slice(&[psv.inputs.len() as u8, psv.outputs.len() as u8, psv.prims.len() as u8, psv.input_vectors]); - p.extend_from_slice(&psv.output_vectors); - for n in psv.numthreads { - w(&mut p, n); - } - let all: Vec<&PsvSigElement> = psv.inputs.iter().chain(&psv.outputs).chain(&psv.prims).collect(); + let total_elems = psv.inputs.len() + psv.outputs.len() + psv.prims.len(); + let elems = || psv.inputs.iter().chain(&psv.outputs).chain(&psv.prims); // String table: "" then non-system names in element order (not // deduplicated, as DXC writes it), then the entry name. - let mut strings = vec![0u8]; - let mut name_off = Vec::new(); - for e in &all { + let str_raw = 1 + elems().map(|e| if e.name.is_empty() { 0 } else { e.name.len() + 1 }).sum::() + psv.entry.len() + 1; + let mut strings = Vec::with_capacity(str_raw.next_multiple_of(4)); + strings.push(0); + let mut name_off = Vec::with_capacity(total_elems); + for e in elems() { if e.name.is_empty() { name_off.push(0); } else { @@ -362,22 +371,10 @@ pub fn psv_part_full(psv: &PsvFull) -> Vec { while strings.len() % 4 != 0 { strings.push(0); } - w(&mut p, entry_off); - w(&mut p, psv.resources.len() as u32); - if !psv.resources.is_empty() { - w(&mut p, 24); - for r in &psv.resources { - for v in [r.res_type as u32, r.space, r.lower, r.upper, r.kind, r.flags] { - w(&mut p, v); - } - } - } - w(&mut p, strings.len() as u32); - p.extend_from_slice(&strings); // Semantic index table: each element's index list, reusing an existing run. let mut table: Vec = Vec::new(); - let mut idx_off = Vec::new(); - for e in &all { + let mut idx_off = Vec::with_capacity(total_elems); + for e in elems() { let n = e.indices.len(); let found = if n == 0 || table.len() < n { None } else { (0..=table.len() - n).find(|&i| table[i..i + n] == e.indices[..]) }; idx_off.push(match found { @@ -388,13 +385,41 @@ pub fn psv_part_full(psv: &PsvFull) -> Vec { } }); } + let res_len = if psv.resources.is_empty() { 0 } else { 4 + 24 * psv.resources.len() }; + let sig_len = if total_elems == 0 { 0 } else { 4 + 16 * total_elems }; + let tbl_len = 4 * psv.tables.iter().map(Vec::len).sum::(); + let p_len = 68 + res_len + strings.len() + 4 * table.len() + sig_len + tbl_len; + let mut p = Vec::with_capacity(p_len); + let w = |p: &mut Vec, v: u32| p.extend_from_slice(&v.to_le_bytes()); + w(&mut p, 52); + p.extend_from_slice(&psv.stage_info); + w(&mut p, psv.min_wave); + w(&mut p, psv.max_wave); + p.extend_from_slice(&[psv.stage as u8, psv.uses_view_id as u8, psv.info1[0], psv.info1[1]]); + p.extend_from_slice(&[psv.inputs.len() as u8, psv.outputs.len() as u8, psv.prims.len() as u8, psv.input_vectors]); + p.extend_from_slice(&psv.output_vectors); + for n in psv.numthreads { + w(&mut p, n); + } + w(&mut p, entry_off); + w(&mut p, psv.resources.len() as u32); + if !psv.resources.is_empty() { + w(&mut p, 24); + for r in &psv.resources { + for v in [r.res_type as u32, r.space, r.lower, r.upper, r.kind, r.flags] { + w(&mut p, v); + } + } + } + w(&mut p, strings.len() as u32); + p.extend_from_slice(&strings); w(&mut p, table.len() as u32); for v in &table { w(&mut p, *v); } - if !all.is_empty() { + if total_elems > 0 { w(&mut p, 16); - for (i, e) in all.iter().enumerate() { + for (i, e) in elems().enumerate() { w(&mut p, name_off[i]); w(&mut p, idx_off[i]); let cs = (e.cols & 0xF) | ((e.start_col & 3) << 4) | ((e.allocated as u8) << 6); @@ -406,6 +431,7 @@ pub fn psv_part_full(psv: &PsvFull) -> Vec { w(&mut p, *v); } } + debug_assert_eq!(p.len(), p_len); p } @@ -413,35 +439,17 @@ pub fn psv_part_full(psv: &PsvFull) -> Vec { /// mesh primitive outputs) and a prebuilt PSV0. #[allow(clippy::too_many_arguments)] pub fn container_with_signatures(stage: Stage, sm: (u32, u32), bitcode: &[u8], features: u64, isg: Vec, osg: Vec, psg: Option>, psv: Vec) -> Vec { - let dxil_version = (1, sm.1.min(8)); - let mut parts: Vec<([u8; 4], Vec)> = vec![(*b"SFI0", features.to_le_bytes().to_vec()), (*b"ISG1", isg), (*b"OSG1", osg)]; - if let Some(p) = psg { - parts.push((*b"PSG1", p)); - } - parts.push((*b"PSV0", psv)); - parts.push((*b"DXIL", program_part(stage, sm, dxil_version, bitcode))); - let header = 32 + 4 * parts.len(); - let total: usize = header + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); - let mut out = Vec::with_capacity(total); - out.extend_from_slice(b"DXBC"); - out.extend_from_slice(&[0; 16]); - out.extend_from_slice(&1u16.to_le_bytes()); - out.extend_from_slice(&0u16.to_le_bytes()); - out.extend_from_slice(&(total as u32).to_le_bytes()); - out.extend_from_slice(&(parts.len() as u32).to_le_bytes()); - let mut off = header; - for (_, d) in &parts { - out.extend_from_slice(&(off as u32).to_le_bytes()); - off += 8 + d.len(); + let sfi0 = features.to_le_bytes(); + match psg.as_deref() { + Some(p) => assemble_container( + &[(*b"SFI0", sfi0.as_slice()), (*b"ISG1", isg.as_slice()), (*b"OSG1", osg.as_slice()), (*b"PSG1", p), (*b"PSV0", psv.as_slice())], + stage, sm, bitcode, + ), + None => assemble_container( + &[(*b"SFI0", sfi0.as_slice()), (*b"ISG1", isg.as_slice()), (*b"OSG1", osg.as_slice()), (*b"PSV0", psv.as_slice())], + stage, sm, bitcode, + ), } - for (cc, d) in &parts { - out.extend_from_slice(cc); - out.extend_from_slice(&(d.len() as u32).to_le_bytes()); - out.extend_from_slice(d); - } - let digest = hash(&out[20..]); - out[4..20].copy_from_slice(&digest); - out } #[cfg(test)] @@ -484,6 +492,124 @@ mod tests { assert_eq!(ours, theirs); } + #[test] + fn parts_and_containers_are_exact_sized_and_match_reference_layout() { + let ref_dxbc = |parts: &[([u8; 4], &[u8])]| -> Vec { + let hdr = 32 + 4 * parts.len(); + let tot = hdr + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); + let mut o = Vec::with_capacity(tot); + o.extend_from_slice(b"DXBC"); + o.extend_from_slice(&[0; 16]); + o.extend_from_slice(&1u16.to_le_bytes()); + o.extend_from_slice(&0u16.to_le_bytes()); + o.extend_from_slice(&(tot as u32).to_le_bytes()); + o.extend_from_slice(&(parts.len() as u32).to_le_bytes()); + let mut off = hdr; + for (_, d) in parts { o.extend_from_slice(&(off as u32).to_le_bytes()); off += 8 + d.len(); } + for (cc, d) in parts { o.extend_from_slice(cc); o.extend_from_slice(&(d.len() as u32).to_le_bytes()); o.extend_from_slice(d); } + let d = hash(&o[20..]); + o[4..20].copy_from_slice(&d); + o + }; + let ref_dxil = |stage: Stage, sm: (u32, u32), bc: &[u8]| -> Vec { + let mut p = Vec::new(); + for v in [((stage as u32) << 16) | (sm.0 << 4) | sm.1, ((24 + bc.len()) / 4) as u32, fourcc(b"DXIL"), (1 << 8) | sm.1.min(8), 16, bc.len() as u32] { + p.extend_from_slice(&v.to_le_bytes()); + } + p.extend_from_slice(bc); + p + }; + let res = PsvResource { res_type: PsvResType::UavRaw, space: 1, lower: 2, upper: 4, kind: 11, flags: 3 }; + let bc = [0xDEu8, 0xAD, 0xBE, 0xEF, 1, 2, 3, 4]; + + // 1. psv_part + container across 0 & N resources and all entry padding remainders. + for n_res in [0usize, 3] { + for entry in ["", "a", "ab", "abc", "main"] { + let psv = Psv { stage: Stage::Compute, min_wave: 32, max_wave: 64, numthreads: [8, 4, 1], resources: vec![res.clone(); n_res], entry: entry.into() }; + let p = psv_part(&psv); + assert_eq!(p.capacity(), p.len(), "psv_part over-allocated for n_res={n_res} entry={entry:?}"); + let s0 = 0x1234_5678_9ABC_DEF0u64.to_le_bytes(); + let dxil = ref_dxil(Stage::Compute, (6, 9), &bc); + let got = container(Stage::Compute, (6, 9), &bc, 0x1234_5678_9ABC_DEF0, &psv); + let want = ref_dxbc(&[(*b"SFI0", &s0), (*b"ISG1", &EMPTY_SIGNATURE), (*b"OSG1", &EMPTY_SIGNATURE), (*b"PSV0", &p), (*b"DXIL", &dxil)]); + assert_eq!(got.capacity(), got.len()); + assert_eq!(got, want); + assert_eq!(part(&got, b"PSV0"), p.as_slice()); + } + } + + // 2. signature_part with empty & repeated names + name_order reordering. + let empty_sig = signature_part(&[], &[]); + assert_eq!(empty_sig.as_slice(), &EMPTY_SIGNATURE); + assert_eq!(empty_sig.capacity(), empty_sig.len()); + let mk_sig = |name: &str, idx: u32, reg: u32| SigPartElement { + stream: 0, name: name.into(), index: idx, system_value: 0, comp_type: 3, register: reg, mask: 0xF, rw_mask: 0x3, min_precision: 0, + }; + let elems = [mk_sig("TEXCOORD", 0, 0), mk_sig("SV_Position", 0, 1), mk_sig("TEXCOORD", 1, 2)]; + let isg = signature_part(&elems, &["SV_Position", "TEXCOORD"]); + assert_eq!(isg.capacity(), isg.len()); + let off0 = u32::from_le_bytes(isg[12..16].try_into().unwrap()) as usize; + let off1 = u32::from_le_bytes(isg[44..48].try_into().unwrap()) as usize; + let off2 = u32::from_le_bytes(isg[76..80].try_into().unwrap()) as usize; + assert_eq!(off0, off2, "repeated semantic name must share one string offset"); + assert!(off1 < off0, "name_order must place SV_Position before TEXCOORD"); + + // 3. psv_part_full (inputs/outputs/prims, empty & non-empty names, reused index runs, view_id, tables) + // + container_with_signatures with PSG1 = Some and None. + let mk_psv_el = |name: &str, indices: &[u32], row: u8| PsvSigElement { + name: name.into(), indices: indices.to_vec(), rows: 1, start_row: row, cols: 4, start_col: 0, + allocated: true, kind: 0, comp_type: 3, interp: 2, dynamic_mask: 0, stream: 0, + }; + let full = PsvFull { + stage: Stage::Mesh, stage_info: [7; 16], min_wave: 32, max_wave: 32, uses_view_id: true, + info1: [1, 2], numthreads: [32, 1, 1], resources: vec![res], entry: "mesh_main".into(), + inputs: vec![mk_psv_el("", &[0], 0), mk_psv_el("TEXCOORD", &[0, 1], 1)], + outputs: vec![mk_psv_el("COLOR", &[1], 0)], + prims: vec![mk_psv_el("PRIM", &[0, 1], 0)], + input_vectors: 2, output_vectors: [1, 0, 0, 0], tables: vec![vec![0x11, 0x22], vec![0x33]], + }; + let pfull = psv_part_full(&full); + // Captured from the pre-refactor serializer. Keep this oracle independent of the + // container/reference helpers above so a same-length PSV field reordering is visible. + let golden = concat!( + "340000000707070707070707070707070707070720000000200000000d010102", + "0201010201000000200000000100000001000000150000000100000018000000", + "070000000100000002000000040000000b000000030000002000000000544558", + "434f4f524400434f4c4f52005052494d006d6573685f6d61696e000003000000", + "0000000000000000010000001000000000000000000000000100440003020000", + "010000000100000001014400030200000a000000020000000100440003020000", + "10000000010000000100440003020000110000002200000033000000", + ); + let golden: Vec = golden.as_bytes().chunks_exact(2).map(|b| { + u8::from_str_radix(std::str::from_utf8(b).unwrap(), 16).unwrap() + }).collect(); + assert_eq!(pfull, golden, "full PSV bytes changed from the pre-refactor serializer"); + assert_eq!(pfull.capacity(), pfull.len()); + let pfull_empty = psv_part_full(&PsvFull { + stage: Stage::Vertex, stage_info: [0; 16], min_wave: 0, max_wave: 0, uses_view_id: false, + info1: [0; 2], numthreads: [0; 3], resources: vec![], entry: "vs".into(), + inputs: vec![], outputs: vec![], prims: vec![], input_vectors: 0, output_vectors: [0; 4], tables: vec![], + }); + assert_eq!(pfull_empty.capacity(), pfull_empty.len()); + + let osg = signature_part(&[mk_sig("COLOR", 0, 0)], &[]); + let psg = signature_part(&[mk_sig("PRIM", 0, 0)], &[]); + let sfi = 0x55u64.to_le_bytes(); + let dxil = ref_dxil(Stage::Mesh, (6, 6), &bc); + let with_psg = container_with_signatures(Stage::Mesh, (6, 6), &bc, 0x55, isg.clone(), osg.clone(), Some(psg.clone()), pfull.clone()); + assert_eq!(with_psg.capacity(), with_psg.len()); + assert_eq!(with_psg, ref_dxbc(&[(*b"SFI0", &sfi), (*b"ISG1", &isg), (*b"OSG1", &osg), (*b"PSG1", &psg), (*b"PSV0", &pfull), (*b"DXIL", &dxil)])); + let without_psg = container_with_signatures(Stage::Mesh, (6, 6), &bc, 0x55, isg.clone(), osg.clone(), None, pfull.clone()); + assert_eq!(without_psg.capacity(), without_psg.len()); + assert_eq!(without_psg, ref_dxbc(&[(*b"SFI0", &sfi), (*b"ISG1", &isg), (*b"OSG1", &osg), (*b"PSV0", &pfull), (*b"DXIL", &dxil)])); + } + + #[test] + #[should_panic] + fn program_header_rejects_unaligned_bitcode() { + let _ = program_header(Stage::Compute, (6, 6), (1, 6), 6); + } + pub(crate) fn part<'a>(c: &'a [u8], cc: &[u8; 4]) -> &'a [u8] { let n = u32::from_le_bytes(c[28..32].try_into().unwrap()) as usize; for i in 0..n { From b59e59b63250ed198c028bf3eb94c7b9c2313a23 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 08:21:57 +0300 Subject: [PATCH 065/265] Loader: reject out-of-module addresses in constant time Pack the lock-free module ranges into a single table with a monotonic address envelope, making the common PC/driver-address rejection O(1). Publish registration and removal under the mapped-module write lock and make all containment arithmetic overflow-safe. A controlled same-base test holds registration between range publication and vector publication and proves unregister cannot create a zombie entry. The upstream release microbenchmark reported a 19-23x improvement for out-of-envelope probes against 32 modules. GNU Windows-target cargo check passed here; Windows/MSVC and runtime tests were not run on this host. Adapted from PR #2673. Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/modules.rs | 277 ++++++++++++++++++++++++++++++++++---- 1 file changed, 252 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/modules.rs b/crates/xcl/src/modules.rs index 7aa418fc92..785642dfe3 100644 --- a/crates/xcl/src/modules.rs +++ b/crates/xcl/src/modules.rs @@ -31,7 +31,7 @@ pub struct MappedModule { impl MappedModule { pub fn contains(&self, addr: usize) -> bool { - addr >= self.base && addr < self.base + self.size + addr.checked_sub(self.base).is_some_and(|off| off < self.size) } } @@ -39,41 +39,113 @@ static MAPPED: RwLock>> = RwLock::new(Vec::new()); static MAIN: RwLock>> = RwLock::new(None); const MAX_RANGES: usize = 512; -static RANGE_BASE: [AtomicUsize; MAX_RANGES] = [const { AtomicUsize::new(0) }; MAX_RANGES]; -static RANGE_SIZE: [AtomicUsize; MAX_RANGES] = [const { AtomicUsize::new(0) }; MAX_RANGES]; -static RANGE_COUNT: AtomicUsize = AtomicUsize::new(0); -pub fn register_mapped(m: Arc) { - let i = RANGE_COUNT.fetch_add(1, Ordering::AcqRel); - if i < MAX_RANGES { - RANGE_SIZE[i].store(m.size, Ordering::Release); - RANGE_BASE[i].store(m.base, Ordering::Release); +#[repr(C)] +struct RangeEntry { + base: AtomicUsize, + size: AtomicUsize, +} + +struct RangeTable { + count: AtomicUsize, + min_addr: AtomicUsize, + max_inclusive: AtomicUsize, + overflow_warned: AtomicBool, + entries: [RangeEntry; MAX_RANGES], +} + +impl RangeTable { + const fn new() -> Self { + Self { + count: AtomicUsize::new(0), + min_addr: AtomicUsize::new(usize::MAX), + max_inclusive: AtomicUsize::new(0), + overflow_warned: AtomicBool::new(false), + entries: [const { RangeEntry { base: AtomicUsize::new(0), size: AtomicUsize::new(0) } }; MAX_RANGES], + } + } + + fn insert(&self, base: usize, size: usize) -> bool { + if base == 0 || size == 0 { + return false; + } + let n = self.count.load(Ordering::Relaxed); + if n >= MAX_RANGES { + return !self.overflow_warned.swap(true, Ordering::Relaxed); + } + self.entries[n].size.store(size, Ordering::Relaxed); + self.entries[n].base.store(base, Ordering::Relaxed); + self.min_addr.fetch_min(base, Ordering::Relaxed); + self.max_inclusive.fetch_max(base.saturating_add(size - 1), Ordering::Relaxed); + self.count.store(n + 1, Ordering::Release); + false + } + + fn remove(&self, base: usize) { + if base == 0 { + return; + } + let n = self.count.load(Ordering::Relaxed); + for entry in &self.entries[..n] { + if entry.base.load(Ordering::Relaxed) == base { + entry.base.store(0, Ordering::Release); + } + } + } + + fn lookup(&self, addr: usize) -> Option { + let n = self.count.load(Ordering::Acquire); + if n == 0 { + return None; + } + let lo = self.min_addr.load(Ordering::Relaxed); + let hi = self.max_inclusive.load(Ordering::Relaxed); + if addr < lo || addr > hi { + return None; + } + for entry in &self.entries[..n] { + let b = entry.base.load(Ordering::Acquire); + if b != 0 && addr >= b { + let s = entry.size.load(Ordering::Relaxed); + if addr - b < s { + return Some(b); + } + } + } + None + } +} + +static RANGES: RangeTable = RangeTable::new(); + +fn register_mapped_with(m: Arc, after_range: impl FnOnce()) { + let warn_overflow = { + let mut g = MAPPED.write().unwrap(); + let warn = RANGES.insert(m.base, m.size); + after_range(); + g.push(m); + warn + }; + if warn_overflow { + crate::xlog_warn!("modules: lock-free range table full ({MAX_RANGES} entries); subsequent modules are not tracked in RANGES"); } - MAPPED.write().unwrap().push(m); +} + +pub fn register_mapped(m: Arc) { + register_mapped_with(m, || {}); } /// The image at `base` failed to load: it is no longer found (by name, base, address), so a /// later load maps it again – as Windows' loader unloads a DLL that failed. pub fn unregister_mapped(base: usize) { - MAPPED.write().unwrap().retain(|m| m.base != base); - for i in 0..RANGE_COUNT.load(Ordering::Acquire).min(MAX_RANGES) { - if RANGE_BASE[i].load(Ordering::Acquire) == base { - RANGE_BASE[i].store(0, Ordering::Release); - } - } + let mut g = MAPPED.write().unwrap(); + g.retain(|m| m.base != base); + RANGES.remove(base); } /// Lock-free: base of the mapped image containing `addr`. pub fn image_base_for_addr(addr: usize) -> Option { - let n = RANGE_COUNT.load(Ordering::Acquire).min(MAX_RANGES); - for i in 0..n { - let b = RANGE_BASE[i].load(Ordering::Acquire); - let s = RANGE_SIZE[i].load(Ordering::Acquire); - if b != 0 && addr >= b && addr < b + s { - return Some(b); - } - } - None + RANGES.lookup(addr) } pub fn mapped_modules() -> Vec> { @@ -202,4 +274,159 @@ mod tests { let _ = describe_address(addr); } } + + fn fake_module(name: &str, base: usize, size: usize) -> Arc { + Arc::new(MappedModule { + name: name.to_string(), + path: PathBuf::from(name), + base, + size, + entry_rva: 0, + is_dll: true, + exports: OwnedExports::default(), + tls_callbacks: Mutex::new(Vec::new()), + no_thread_calls: AtomicBool::new(false), + initialized: AtomicBool::new(true), + stack_reserve: 0, + }) + } + + #[test] + fn contains_and_range_table_handle_overflow_and_envelope_boundaries() { + let hi_base = usize::MAX - 0xFFF; + let m = fake_module("high.dll", hi_base, 0x2000); + assert!(m.contains(usize::MAX) && m.contains(hi_base) && !m.contains(hi_base - 1)); + + let t = RangeTable::new(); + assert_eq!(t.lookup(0x1_4000_0000), None); + assert!(!t.insert(0, 0x1000) && !t.insert(0x1_4000_0000, 0)); + assert_eq!((t.count.load(Ordering::Relaxed), t.min_addr.load(Ordering::Relaxed)), (0, usize::MAX)); + + assert!(!t.insert(0x1_4000_0000, 0x1000)); + assert!(!t.insert(0x1_5000_0000, 0x2000)); + assert_eq!(t.lookup(0x1_3FFF_FFFF), None); + assert_eq!(t.lookup(0x1_4000_0000), Some(0x1_4000_0000)); + assert_eq!(t.lookup(0x1_4000_0FFF), Some(0x1_4000_0000)); + assert_eq!(t.lookup(0x1_4000_1000), None); + assert_eq!(t.lookup(0x1_5000_1FFF), Some(0x1_5000_0000)); + assert_eq!(t.lookup(0x1_5000_2000), None); + + t.remove(0); + t.remove(0x1_4000_0000); + assert_eq!((t.lookup(0x1_4000_0100), t.lookup(0x1_5000_0100)), (None, Some(0x1_5000_0000))); + + assert!(!t.insert(hi_base, 0x2000)); + assert_eq!((t.lookup(usize::MAX), t.lookup(hi_base), t.lookup(hi_base - 1)), (Some(hi_base), Some(hi_base), None)); + + let full = RangeTable::new(); + for k in 0..MAX_RANGES { assert!(!full.insert(0x2_0000_0000 + k * 0x10000, 0x1000)); } + assert!(full.insert(0x3_0000_0000, 0x1000)); + assert!(!full.insert(0x3_0001_0000, 0x1000)); + assert_eq!(full.count.load(Ordering::Relaxed), MAX_RANGES); + } + + #[test] + fn concurrent_register_and_unregister_leave_no_zombie_ranges() { + struct UnregGuard(Vec); + impl Drop for UnregGuard { + fn drop(&mut self) { for &b in &self.0 { unregister_mapped(b); } } + } + let origin = 0x0000_6ABC_0000_0000usize; + let bases: Vec = (0..13).map(|k| origin + k * 0x10_0000).collect(); + let _guard = UnregGuard(bases.clone()); + register_mapped(fake_module("sib.dll", bases[0], 0x4000)); + + let stop = Arc::new(AtomicBool::new(false)); + let readers: Vec<_> = (0..2).map(|_| { + let (stop, b0, probes) = (Arc::clone(&stop), bases[0], bases.clone()); + std::thread::spawn(move || { + while !stop.load(Ordering::Relaxed) { + assert_eq!(image_base_for_addr(b0 + 0x100), Some(b0)); + for &b in &probes[1..] { let _ = image_base_for_addr(b + 0x100); } + assert_eq!(image_base_for_addr(0x0000_7FFF_DEAD_0000), None); + } + }) + }).collect(); + let writers: Vec<_> = [1..=6, 7..=12].into_iter().map(|range| { + let bases = bases.clone(); + std::thread::spawn(move || { + for k in range { + register_mapped(fake_module(&format!("tmp{k}.dll"), bases[k], 0x2000)); + assert_eq!(image_base_for_addr(bases[k] + 0x40), Some(bases[k])); + unregister_mapped(bases[k]); + } + }) + }).collect(); + for w in writers { w.join().unwrap(); } + stop.store(true, Ordering::Relaxed); + for r in readers { r.join().unwrap(); } + assert_eq!(image_base_for_addr(bases[0] + 0x100), Some(bases[0])); + for &b in &bases[1..] { + assert_eq!(image_base_for_addr(b + 0x100), None); + assert!(find_mapped_by_base(b).is_none()); + } + + if !cfg!(debug_assertions) { + let (t, old_b, old_s) = (RangeTable::new(), [const { AtomicUsize::new(0) }; 32], [const { AtomicUsize::new(0) }; 32]); + for k in 0..32usize { + let b = 0x1_4000_0000 + k * 0x100_0000; + t.insert(b, 0x80_0000); + old_b[k].store(b, Ordering::Relaxed); + old_s[k].store(0x80_0000, Ordering::Relaxed); + } + let probe = std::hint::black_box(0x7FF9_1234_5678usize); + let n_iters = 200_000u32; + let t0 = std::time::Instant::now(); + let mut old_hits = 0u32; + for _ in 0..n_iters { + let mut hit = false; + for i in 0..32 { + let (b, s) = (old_b[i].load(Ordering::Acquire), old_s[i].load(Ordering::Acquire)); + if b != 0 && probe >= b && probe < b.wrapping_add(s) { hit = true; break; } + } + old_hits += u32::from(std::hint::black_box(hit)); + } + let old_ns = t0.elapsed().as_nanos() as f64 / n_iters as f64; + let t1 = std::time::Instant::now(); + let mut new_hits = 0u32; + for _ in 0..n_iters { new_hits += u32::from(std::hint::black_box(t.lookup(probe).is_some())); } + let new_ns = t1.elapsed().as_nanos() as f64 / n_iters as f64; + assert_eq!((old_hits, new_hits), (0, 0)); + println!("MODULES_BENCH_NS out_of_envelope_32: before={old_ns:.2} after={new_ns:.2}"); + } + } + + #[test] + fn same_base_unregister_waits_for_registration_publication() { + use std::sync::mpsc; + use std::time::Duration; + + let base = 0x0000_6ABD_0000_0000usize; + unregister_mapped(base); + let (published_tx, published_rx) = mpsc::channel(); + let (continue_tx, continue_rx) = mpsc::channel(); + let register = std::thread::spawn(move || { + register_mapped_with(fake_module("same-base.dll", base, 0x4000), || { + published_tx.send(()).unwrap(); + continue_rx.recv().unwrap(); + }); + }); + published_rx.recv().unwrap(); + + let (started_tx, started_rx) = mpsc::channel(); + let (done_tx, done_rx) = mpsc::channel(); + let unregister = std::thread::spawn(move || { + started_tx.send(()).unwrap(); + unregister_mapped(base); + done_tx.send(()).unwrap(); + }); + started_rx.recv().unwrap(); + assert!(done_rx.recv_timeout(Duration::from_millis(50)).is_err(), "unregister passed the in-flight registration's write lock"); + continue_tx.send(()).unwrap(); + register.join().unwrap(); + unregister.join().unwrap(); + + assert!(find_mapped_by_base(base).is_none()); + assert_eq!(image_base_for_addr(base + 0x100), None); + } } From 55ac0394ef0a74ca4d83241e1be3131956e76b8c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:53:55 -0800 Subject: [PATCH 066/265] D3D12.X: replace pipeline workers parked at compile slots Let a bounded normal-band helper serve demanded pipeline work when a normal worker first blocks at the huge-driver-compile gate. Helpers retain BuildQueue priority, shared-Build wanted state, DXC admission, driver slot, and commit limits, then retire once parked workers return. The helper count never exceeds the configured normal worker count and preload/speculative work stays isolated. GNU Windows-target cargo check passed; Windows/MSVC, peak commit, thread churn, GPU, and title smoke were not measured on this host. Adapted from PR #2628. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/build_queue.rs | 85 +++++++++++---- crates/xcl/src/hle/d3d12x/pso_async.rs | 130 ++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 4 + 3 files changed, 198 insertions(+), 21 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/build_queue.rs b/crates/xcl/src/hle/d3d12x/build_queue.rs index fec7b62dfe..c445bb7817 100644 --- a/crates/xcl/src/hle/d3d12x/build_queue.rs +++ b/crates/xcl/src/hle/d3d12x/build_queue.rs @@ -249,30 +249,37 @@ impl Inner { } } + fn take_ready(&self, state: &mut State, low: Priority, high: Priority) -> Option<(Work, Arc)> { + for priority in (low.index()..=high.index()).rev() { + let priority = match priority { + 0 => Priority::Speculative, + 1 => Priority::Preload, + 2 => Priority::BoundSoon, + _ => Priority::Foreground, + }; + while let Some(ticket) = state.pop(priority) { + let current = state.jobs.get(&ticket.id).is_some_and(|job| { + job.priority == priority && job.generation == ticket.generation + }); + if current { + let job = state.jobs.remove(&ticket.id).unwrap(); + if priority == Priority::Preload && job.preload_rank.is_some() { + self.ranked_preloads.started.fetch_add(1, Ordering::Relaxed); + } + job.completion.set(JobStatus::Running); + return Some((job.work, job.completion)); + } + } + } + None + } + fn take(&self, wait: bool, low: Priority, high: Priority) -> Option<(Work, Arc)> { let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); let changed = self.changed(low, high); loop { - for priority in (low.index()..=high.index()).rev() { - let priority = match priority { - 0 => Priority::Speculative, - 1 => Priority::Preload, - 2 => Priority::BoundSoon, - _ => Priority::Foreground, - }; - while let Some(ticket) = state.pop(priority) { - let current = state.jobs.get(&ticket.id).is_some_and(|job| { - job.priority == priority && job.generation == ticket.generation - }); - if current { - let job = state.jobs.remove(&ticket.id).unwrap(); - if priority == Priority::Preload && job.preload_rank.is_some() { - self.ranked_preloads.started.fetch_add(1, Ordering::Relaxed); - } - job.completion.set(JobStatus::Running); - return Some((job.work, job.completion)); - } - } + if let Some(job) = self.take_ready(&mut state, low, high) { + return Some(job); } if state.stopped || !wait { return None; @@ -281,6 +288,20 @@ impl Inner { } } + fn take_while(&self, low: Priority, high: Priority, keep_running: &mut impl FnMut() -> bool) -> Option<(Work, Arc)> { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + let changed = self.changed(low, high); + loop { + if !keep_running() || state.stopped { + return None; + } + if let Some(job) = self.take_ready(&mut state, low, high) { + return Some(job); + } + state = changed.wait_timeout(state, std::time::Duration::from_millis(250)).unwrap_or_else(|e| e.into_inner()).0; + } + } + fn shutdown(&self) { let jobs = { let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); @@ -400,6 +421,13 @@ impl Worker { run(job); } } + + /// Run until `keep_running` closes, checking it while idle without stopping the queue. + pub(super) fn run_while(self, mut keep_running: impl FnMut() -> bool) { + while let Some(job) = self.inner.take_while(self.low, self.high, &mut keep_running) { + run(job); + } + } } fn run((work, completion): (Work, Arc)) { @@ -513,6 +541,23 @@ mod tests { preload_thread.join().unwrap(); } + #[test] + fn conditional_foreground_worker_retires_without_stopping_the_queue() { + let q = BuildQueue::new(); + let keep = Arc::new(AtomicBool::new(true)); + let worker = q.worker_between(Priority::BoundSoon, Priority::Foreground); + let worker_keep = keep.clone(); + let thread = std::thread::spawn(move || worker.run_while(|| worker_keep.load(Ordering::Acquire))); + let preload = q.submit(Priority::Preload, Box::new(|| {})).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + q.submit(Priority::Foreground, Box::new(move || tx.send(()).unwrap())).unwrap(); + rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(); + assert_eq!(preload.status(), JobStatus::Queued, "the replacement stays in its priority band"); + keep.store(false, Ordering::Release); + thread.join().unwrap(); + assert!(q.try_run_one_between(Priority::Preload, Priority::Preload), "retirement leaves the queue usable"); + } + #[test] fn promoted_preload_moves_to_the_foreground_worker_band() { let q = BuildQueue::new(); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 36c522ffbe..0f7ad5e4df 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -74,6 +74,8 @@ thread_local! { static BUILDING: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; /// this is one of the workers reserved for low-priority preload builds static PRELOAD_WORKER: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// this thread serves the normal (`BoundSoon` through `Foreground`) worker band + static NORMAL_WORKER: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// This thread is a worker and one of the title's threads waits for what it is building: the @@ -471,11 +473,85 @@ fn start_normal_workers() { let n = crate::gpu::recomp::dxc::compile_threads(); for k in 0..n { let worker = q.worker_between(Priority::BoundSoon, Priority::Foreground); - let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || worker.run()); + let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || { + NORMAL_WORKER.set(true); + worker.run(); + }); } }); } +/// Normal workers waiting for a huge driver-compile slot, and bounded replacements serving their +/// priority band. Preload workers have their own band and do not need foreground replacements. +static PARKED_NORMAL: AtomicUsize = AtomicUsize::new(0); +static NORMAL_HELPERS: AtomicUsize = AtomicUsize::new(0); +static NORMAL_HELPERS_STARTED: AtomicUsize = AtomicUsize::new(0); + +/// A normal pipeline worker is about to wait for a huge driver-compile slot. A bounded helper +/// serves its queue until workers return; calls from title and preload threads do nothing. +pub(super) fn parked_for_big_compile() -> ParkedWorker { + if !NORMAL_WORKER.get() { + return ParkedWorker(false); + } + let parked = PARKED_NORMAL.fetch_add(1, Ordering::AcqRel) + 1; + let most = parked.min(crate::gpu::recomp::dxc::compile_threads()); + let mut helpers = NORMAL_HELPERS.load(Ordering::Acquire); + while helpers < most { + match NORMAL_HELPERS.compare_exchange(helpers, helpers + 1, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + spawn_normal_helper(helpers); + break; + } + Err(now) => helpers = now, + } + } + ParkedWorker(true) +} + +pub(super) struct ParkedWorker(bool); + +impl Drop for ParkedWorker { + fn drop(&mut self) { + if self.0 { + PARKED_NORMAL.fetch_sub(1, Ordering::AcqRel); + } + } +} + +fn spawn_normal_helper(k: usize) { + let worker = queue().worker_between(Priority::BoundSoon, Priority::Foreground); + let n = NORMAL_HELPERS_STARTED.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a pipeline worker waits for a huge compile slot – a helper serves its queue meanwhile ({n} helpers so far)"); + } + let spawned = std::thread::Builder::new().name(format!("xcl-pso-h{k}")).stack_size(64 << 20).spawn(move || { + NORMAL_WORKER.set(true); + let mut retired = false; + worker.run_while(|| { + retired = retire_normal_helper(); + !retired + }); + if !retired { + NORMAL_HELPERS.fetch_sub(1, Ordering::AcqRel); + } + }); + if spawned.is_err() { + NORMAL_HELPERS.fetch_sub(1, Ordering::AcqRel); + } +} + +/// Reserve this helper's retirement once more helpers exist than parked normal workers. +fn retire_normal_helper() -> bool { + let mut helpers = NORMAL_HELPERS.load(Ordering::Acquire); + while helpers > PARKED_NORMAL.load(Ordering::Acquire) { + match NORMAL_HELPERS.compare_exchange(helpers, helpers - 1, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return true, + Err(now) => helpers = now, + } + } + false +} + fn start_preload_workers() { static STARTED: std::sync::Once = std::sync::Once::new(); STARTED.call_once(|| { @@ -1370,6 +1446,58 @@ mod used_tests { static WORKER_SATURATION_LOCK: Mutex<()> = Mutex::new(()); + /// Normal workers parked at the huge-driver-compile gate leave their priority band live, and + /// the bounded replacement workers retire after the gate opens. + #[test] + fn parked_normal_workers_leave_the_queue_to_bounded_helpers() { + let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use std::time::{Duration, Instant}; + + struct OpenGate(Arc<(Mutex, Condvar)>); + impl Drop for OpenGate { + fn drop(&mut self) { + *self.0 .0.lock().unwrap() = true; + self.0 .1.notify_all(); + } + } + + let outside = parked_for_big_compile(); + assert!(!outside.0, "a title/test thread must not start a replacement"); + drop(outside); + + start_normal_workers(); + let n = crate::gpu::recomp::dxc::compile_threads(); + let (started_tx, started_rx) = mpsc::channel(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let open = OpenGate(gate.clone()); + for _ in 0..n { + let (tx, gate) = (started_tx.clone(), gate.clone()); + queue().submit(Priority::Foreground, Box::new(move || { + let _parked = parked_for_big_compile(); + tx.send(()).unwrap(); + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + })).unwrap(); + } + for _ in 0..n { + started_rx.recv_timeout(Duration::from_secs(10)).expect("every blocker parked"); + } + assert!(NORMAL_HELPERS.load(Ordering::Acquire) <= n, "replacement count is bounded by the normal pool"); + let (ran_tx, ran_rx) = mpsc::channel(); + queue().submit(Priority::Foreground, Box::new(move || ran_tx.send(()).unwrap())).unwrap(); + ran_rx.recv_timeout(Duration::from_secs(10)).expect("a replacement served the queue"); + drop(open); + + let deadline = Instant::now() + Duration::from_secs(10); + while (PARKED_NORMAL.load(Ordering::Acquire) != 0 || NORMAL_HELPERS.load(Ordering::Acquire) != 0) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(PARKED_NORMAL.load(Ordering::Acquire), 0); + assert_eq!(NORMAL_HELPERS.load(Ordering::Acquire), 0, "replacement workers retired"); + } + /// A queued normal worker job whose stand-in was released before a worker starts it is /// skipped as orphaned instead of entering the compiler. #[test] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 2cc2d75a43..5f49965099 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4137,6 +4137,7 @@ fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool) -> SlotGuard { const LOOK: std::time::Duration = std::time::Duration::from_millis(50); let mut n = slots.n.lock().unwrap(); + let mut parked = None; loop { let is_wanted = wanted(); let cap = if is_wanted { slots.wanted_most() } else { slots.most() }; @@ -4144,6 +4145,9 @@ fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wante *n += 1; return SlotGuard(slots); } + if parked.is_none() { + parked = Some(super::pso_async::parked_for_big_compile()); + } n = slots.cv.wait_timeout(n, LOOK).unwrap().0; } } From 7ea65ea9bfd5969b906663194dedcf028272bb8b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:56:22 -0800 Subject: [PATCH 067/265] D3D12.X: journal used pipeline keys off bind threads Move used-pipelines.txt appends to one ordered background writer. Producers sequence and deduplicate keys under one shared state, retain the exact in-flight batch until a successful append, and cannot let later keys overtake retries. Normal exit and NtTerminate use bounded close/flush waits with no unbounded join or caller-side file handle. Partial append retries begin on a fresh line, and close success means the writer dropped its handle. GNU Windows-target cargo check passed. Runtime tests could not link without MinGW dlltool; Windows/MSVC and termination smoke were not tested. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/eh.rs | 1 + crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/pso_async.rs | 46 +-- crates/xcl/src/hle/d3d12x/used_journal.rs | 349 ++++++++++++++++++++++ crates/xcl/src/host.rs | 2 + 5 files changed, 382 insertions(+), 17 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/used_journal.rs diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2d431e5a47..06277d4a41 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -136,6 +136,7 @@ unsafe extern "system" fn hk_nt_terminate_process(h: isize, status: i32) -> i32 crate::xlog_info!("process ends (thread {tid}); on the stack: {stack}"); } crate::log::flush(); + crate::hle::d3d12x::pso_async::flush_used_bounded(std::time::Duration::from_millis(100)); } let orig: unsafe extern "system" fn(isize, i32) -> i32 = std::mem::transmute(ORIG_NT_TERMINATE.load(Ordering::Acquire)); orig(h, status) diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 6c24260e3c..c221345c66 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -34,6 +34,7 @@ pub mod sparse; mod standin; pub mod title_list; pub mod title_textures; +mod used_journal; pub mod vram; use std::ffi::c_void; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 2a7be716a1..eb86b2fcd1 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -686,6 +686,17 @@ pub fn earlier_used_keys() -> std::collections::HashSet { used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt")).unwrap_or_default()) } +/// Ask the used-pipeline writer to finish without ever joining it unboundedly. +pub fn shutdown_used() { + used::shutdown(std::time::Duration::from_millis(500)); +} + +/// Best effort at process termination: only the one writer touches the append handle, and a +/// loader-lock-blocked writer cannot hold termination longer than `timeout`. +pub fn flush_used_bounded(timeout: std::time::Duration) { + used::shutdown(timeout); +} + /// The pipelines a title used, by a hash of their shaders, kept between runs /// (`used-pipelines.txt` beside the DXIL cache, a key a line). /// @@ -697,14 +708,18 @@ pub fn earlier_used_keys() -> std::collections::HashSet { /// this and 94 – 150 with it. mod used { use std::collections::{HashMap, HashSet}; - use std::io::Write; - use std::sync::{Mutex, OnceLock, RwLock}; + use std::sync::{OnceLock, RwLock}; + use std::time::Duration; + + use super::super::used_journal::Journal; struct Used { earlier: RwLock>, - now: Mutex<(HashSet, Option)>, + now: Journal, } + static U: OnceLock = OnceLock::new(); + /// The keys in a `used-pipelines.txt` (lines that are not a hexadecimal key are passed over). pub fn parse(text: &str) -> HashSet { parse_ranked(text).into_keys().collect() @@ -721,25 +736,27 @@ mod used { } fn get() -> &'static Used { - static U: OnceLock = OnceLock::new(); U.get_or_init(|| { // (a test neither reads nor writes the user's file) if cfg!(test) { - return Used { earlier: RwLock::new(HashMap::new()), now: Mutex::new((HashSet::new(), None)) }; + return Used { earlier: RwLock::new(HashMap::new()), now: Journal::memory(HashSet::new()) }; } let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); let earlier = parse_ranked(&std::fs::read_to_string(&path).unwrap_or_default()); if !earlier.is_empty() { crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); } - if let Some(dir) = path.parent() { - let _ = std::fs::create_dir_all(dir); - } - let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok(); - Used { now: Mutex::new((earlier.keys().copied().collect(), file)), earlier: RwLock::new(earlier) } + let now = Journal::file(path, earlier.keys().copied().collect()); + Used { now, earlier: RwLock::new(earlier) } }) } + pub fn shutdown(timeout: Duration) { + if let Some(used) = U.get() { + let _ = used.now.shutdown_bounded(timeout); + } + } + /// First-use rank when an earlier run used a pipeline of these shaders. pub fn rank(key: u64) -> Option { (key != 0).then(|| get().earlier.read().unwrap().get(&key).copied()).flatten() @@ -750,18 +767,13 @@ mod used { if key == 0 { return; } - let mut g = get().now.lock().unwrap(); - if g.0.insert(key) { - if let Some(f) = g.1.as_mut() { - let _ = writeln!(f, "{key:016x}"); - } - } + get().now.note(key); } /// (tests) This run used a pipeline of these shaders. #[cfg(test)] pub fn noted(key: u64) -> bool { - get().now.lock().unwrap().0.contains(&key) + get().now.contains(key) } #[cfg(test)] diff --git a/crates/xcl/src/hle/d3d12x/used_journal.rs b/crates/xcl/src/hle/d3d12x/used_journal.rs new file mode 100644 index 0000000000..1c058df440 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/used_journal.rs @@ -0,0 +1,349 @@ +//! Ordered background append journal for `used-pipelines.txt`. + +use std::collections::HashSet; +use std::fmt::Write as _; +use std::io::Write; +use std::path::PathBuf; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +const COALESCE: Duration = Duration::from_millis(25); +const FULL_BATCH: usize = 64; + +trait Sink: Send { + fn append(&mut self, bytes: &[u8]) -> bool; +} + +struct FileSink { + path: PathBuf, + file: Option, +} + +impl Sink for FileSink { + fn append(&mut self, bytes: &[u8]) -> bool { + if self.file.is_none() { + if let Some(dir) = self.path.parent() { + let _ = std::fs::create_dir_all(dir); + } + self.file = std::fs::OpenOptions::new().create(true).append(true).open(&self.path).ok(); + } + let ok = self.file.as_mut().is_some_and(|file| file.write_all(bytes).is_ok()); + if !ok { + self.file = None; + } + ok + } +} + +#[derive(Clone)] +struct Batch { + end_seq: u64, + keys: Arc<[u64]>, +} + +struct State { + seen: HashSet, + pending: Vec<(u64, u64)>, + in_flight: Option, + next_seq: u64, + completed_seq: u64, + flush_now: bool, + closed: bool, + stopped: bool, +} + +struct Shared { + state: Mutex, + wake: Condvar, + completed: Condvar, +} + +/// A single writer owns the append handle. Producers only touch `Shared::state`; the batch being +/// written stays there until it succeeds, so a later producer can never hide or overtake it. +pub(super) struct Journal { + shared: Arc, +} + +impl Journal { + pub(super) fn file(path: PathBuf, seen: HashSet) -> Self { + Self::with_sink(seen, Box::new(FileSink { path, file: None }), COALESCE) + } + + pub(super) fn memory(seen: HashSet) -> Self { + let shared = Arc::new(Shared { + state: Mutex::new(State { + seen, + pending: Vec::new(), + in_flight: None, + next_seq: 0, + completed_seq: 0, + flush_now: false, + closed: false, + stopped: true, + }), + wake: Condvar::new(), + completed: Condvar::new(), + }); + Self { shared } + } + + fn with_sink(seen: HashSet, sink: Box, coalesce: Duration) -> Self { + let shared = Arc::new(Shared { + state: Mutex::new(State { + seen, + pending: Vec::new(), + in_flight: None, + next_seq: 0, + completed_seq: 0, + flush_now: false, + closed: false, + stopped: false, + }), + wake: Condvar::new(), + completed: Condvar::new(), + }); + let worker = shared.clone(); + if std::thread::Builder::new().name("xcl-pso-used".into()).spawn(move || writer(worker, sink, coalesce)).is_err() { + shared.state.lock().unwrap().stopped = true; + } + Self { shared } + } + + pub(super) fn note(&self, key: u64) { + if key == 0 { + return; + } + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.closed || !state.seen.insert(key) { + return; + } + // An in-memory/test journal, or a worker that could not start, still deduplicates. + if state.stopped { + return; + } + state.next_seq += 1; + let seq = state.next_seq; + state.pending.push((seq, key)); + if state.pending.len() == 1 || state.pending.len() == FULL_BATCH { + self.shared.wake.notify_one(); + } + } + + #[cfg(test)] + pub(super) fn contains(&self, key: u64) -> bool { self.shared.state.lock().unwrap_or_else(|e| e.into_inner()).seen.contains(&key) } + + #[cfg(test)] + fn flush_bounded(&self, timeout: Duration) -> bool { self.wait_bounded(timeout, false) } + + pub(super) fn shutdown_bounded(&self, timeout: Duration) -> bool { self.wait_bounded(timeout, true) } + + fn wait_bounded(&self, timeout: Duration, close: bool) -> bool { + let deadline = Instant::now() + timeout; + let mut state = loop { + match self.shared.state.try_lock() { + Ok(state) => break state, + Err(std::sync::TryLockError::Poisoned(e)) => break e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + if Instant::now() >= deadline { + return false; + } + std::thread::yield_now(); + } + } + }; + if close { + state.closed = true; + } + let target = state.next_seq; + state.flush_now = true; + self.shared.wake.notify_one(); + while (state.completed_seq < target || close && !state.stopped) && !state.stopped { + let Some(left) = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (next, waited) = self.shared.completed.wait_timeout(state, left).unwrap_or_else(|e| e.into_inner()); + state = next; + if waited.timed_out() { + break; + } + } + state.completed_seq >= target && (!close || state.stopped) + } +} + +impl Drop for Journal { + fn drop(&mut self) { + let _ = self.shutdown_bounded(Duration::from_millis(100)); + } +} + +struct Stopped(Arc); + +impl Drop for Stopped { + fn drop(&mut self) { + let mut state = self.0.state.lock().unwrap_or_else(|e| e.into_inner()); + state.stopped = true; + self.0.completed.notify_all(); + } +} + +fn writer(shared: Arc, mut sink: Box, coalesce: Duration) { + let stopped = Stopped(shared.clone()); + let mut bytes = String::new(); + let mut retrying = false; + loop { + let batch = { + let mut state = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + while state.in_flight.is_none() && state.pending.is_empty() && !state.closed { + state = shared.wake.wait(state).unwrap_or_else(|e| e.into_inner()); + } + if state.in_flight.is_none() && !state.pending.is_empty() && !coalesce.is_zero() && !state.flush_now && !state.closed { + let until = Instant::now() + coalesce; + while state.pending.len() < FULL_BATCH && !state.flush_now && !state.closed { + let Some(left) = until.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (next, waited) = shared.wake.wait_timeout(state, left).unwrap_or_else(|e| e.into_inner()); + state = next; + if waited.timed_out() { + break; + } + } + } + state.flush_now = false; + if state.in_flight.is_none() && !state.pending.is_empty() { + let pending = std::mem::take(&mut state.pending); + let end_seq = pending.last().unwrap().0; + state.in_flight = Some(Batch { end_seq, keys: pending.into_iter().map(|(_, key)| key).collect() }); + } + let Some(batch) = state.in_flight.clone() else { + if state.closed { break } else { continue }; + }; + batch + }; + + bytes.clear(); + if retrying { + // `write_all` may have appended an arbitrary prefix before reporting failure. End + // that fragment so replay cannot concatenate it with the first key into a lost line. + bytes.push('\n'); + } + bytes.reserve(batch.keys.len() * 17); + for key in batch.keys.iter() { + let _ = writeln!(bytes, "{key:016x}"); + } + let written = sink.append(bytes.as_bytes()); + retrying = !written; + let mut state = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if written { + if state.in_flight.as_ref().is_some_and(|current| current.end_seq == batch.end_seq) { + state.in_flight = None; + state.completed_seq = state.completed_seq.max(batch.end_seq); + shared.completed.notify_all(); + } + } else { + let (next, _) = shared.wake.wait_timeout(state, coalesce.max(Duration::from_millis(1))).unwrap_or_else(|e| e.into_inner()); + drop(next); + } + } + drop(sink); + drop(stopped); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + + struct Blocking { + first: bool, + entered: mpsc::Sender<()>, + release: mpsc::Receiver<()>, + output: Arc>>, + } + + impl Sink for Blocking { + fn append(&mut self, bytes: &[u8]) -> bool { + if self.first { + self.first = false; + self.entered.send(()).unwrap(); + self.release.recv().unwrap(); + } + self.output.lock().unwrap().extend_from_slice(bytes); + true + } + } + + #[test] + fn flush_waits_for_the_shared_in_flight_batch_and_later_producers() { + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let output = Arc::new(Mutex::new(Vec::new())); + let journal = Arc::new(Journal::with_sink( + HashSet::new(), + Box::new(Blocking { first: true, entered: entered_tx, release: release_rx, output: output.clone() }), + Duration::ZERO, + )); + journal.note(1); + entered_rx.recv_timeout(Duration::from_secs(2)).expect("writer did not take the first batch"); + journal.note(2); + let waiter = journal.clone(); + let (flushed_tx, flushed_rx) = mpsc::channel(); + std::thread::spawn(move || flushed_tx.send(waiter.flush_bounded(Duration::from_secs(2))).unwrap()); + assert!(matches!(flushed_rx.recv_timeout(Duration::from_millis(20)), Err(mpsc::RecvTimeoutError::Timeout))); + release_tx.send(()).unwrap(); + assert!(flushed_rx.recv_timeout(Duration::from_secs(2)).unwrap()); + assert_eq!(String::from_utf8(output.lock().unwrap().clone()).unwrap(), "0000000000000001\n0000000000000002\n"); + assert!(journal.shutdown_bounded(Duration::from_secs(2))); + } + + struct FailOnce { + failed: bool, + output: Arc>>, + } + + impl Sink for FailOnce { + fn append(&mut self, bytes: &[u8]) -> bool { + if !self.failed { + self.failed = true; + self.output.lock().unwrap().extend_from_slice(&bytes[..8.min(bytes.len())]); + return false; + } + self.output.lock().unwrap().extend_from_slice(bytes); + true + } + } + + #[test] + fn failed_batch_is_retried_before_later_keys() { + let output = Arc::new(Mutex::new(Vec::new())); + let journal = Journal::with_sink( + HashSet::new(), + Box::new(FailOnce { failed: false, output: output.clone() }), + Duration::from_millis(1), + ); + journal.note(3); + journal.note(4); + assert!(journal.flush_bounded(Duration::from_secs(2))); + journal.note(5); + assert!(journal.flush_bounded(Duration::from_secs(2))); + let text = String::from_utf8(output.lock().unwrap().clone()).unwrap(); + let keys: Vec = text.lines().filter_map(|line| u64::from_str_radix(line, 16).ok()).filter(|&key| key != 0).collect(); + assert_eq!(keys, [3, 4, 5]); + assert!(journal.shutdown_bounded(Duration::from_secs(2))); + } + + #[test] + fn shutdown_is_bounded_when_the_only_writer_is_blocked() { + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let journal = Journal::with_sink( + HashSet::new(), + Box::new(Blocking { first: true, entered: entered_tx, release: release_rx, output: Arc::new(Mutex::new(Vec::new())) }), + Duration::ZERO, + ); + journal.note(6); + entered_rx.recv_timeout(Duration::from_secs(2)).expect("writer did not block"); + let start = Instant::now(); + assert!(!journal.shutdown_bounded(Duration::from_millis(20))); + assert!(start.elapsed() < Duration::from_millis(500), "bounded shutdown waited {:?}", start.elapsed()); + release_tx.send(()).unwrap(); + assert!(journal.shutdown_bounded(Duration::from_secs(2))); + } +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index c20049322c..84a7fce1d0 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -115,6 +115,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title ({shown} frames shown, {presented} PresentX calls)"); crate::report::write_final(None); crate::log::flush(); + crate::hle::d3d12x::pso_async::shutdown_used(); crate::hle::d3d12x::real::end_title(0); }); } @@ -159,5 +160,6 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::xlog_info!("game entry point returned code {code}"); crate::report::write_final(None); crate::log::flush(); + crate::hle::d3d12x::pso_async::shutdown_used(); code as i32 } From 355826c5b23e690d5a61c7a550a7f209330ad5f9 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:59:42 +0100 Subject: [PATCH 068/265] Shaders: reuse unsplit cache file buffers After validating an unsplit translated-shader cache entry, move its payload to the front of the file buffer and retain that allocation instead of making a second payload-sized copy. Split entries keep the existing copy path so they do not retain all piece bytes. Preserve cache-I/O stall attribution and add ownership, sampler-offset, malformed-entry, and split round-trip coverage. The upstream extracted-loader benchmark reported 27-35% faster 4-16 MiB warm-cache loads with roughly half the incremental heap peak. GNU Windows-target cargo check passed. Windows/MSVC, GPU tests, and retail smoke were not run on this host. Adapted from PR #2594. Assisted-by: OpenAI Codex (gpt-6-astra) Assisted-by: Codex (GPT-5.6-sol) --- README.md | 2 + crates/xcl/src/gpu/recomp/pso.rs | 76 +++++++++++++++++++++++++++++++- 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 557265dfb7..4b8eef90ad 100644 --- a/README.md +++ b/README.md @@ -263,6 +263,8 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder default. - Translated shaders are reused across XCL rebuilds when the translator sources and DXC toolchain are unchanged; `XCL_TRANSLATED_CACHE=0` disables that disk cache. + Loading a cached shader without split pieces reuses the file buffer, avoiding a second + payload-sized allocation. - Direct compute dispatches can split large programs into pipelines built in parallel. `XCL_DIRECT_SPLIT_INSTRUCTIONS` sets the target instructions per piece (default 12500, zero disables splitting). Loops stay in one piece. A strongly connected component over the diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 0fb7ef6271..d448906732 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -346,6 +346,10 @@ mod translated { let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); std::fs::read(path) }.ok()?; + decode_entry(b, ident, blob) + } + + pub(super) fn decode_entry(mut b: Vec, ident: u64, blob: &[u8]) -> Option { let head = header(ident, blob); let mut r = b.strip_prefix(head.as_slice())?; let u32_ = |r: &mut &[u8]| -> Option { @@ -369,7 +373,12 @@ mod translated { let (whole, mut rest) = r.split_at_checked(len)?; if !super::dxc::valid_dxil_container(whole) { return None; } let dispatch_chain = if rest.is_empty() { - None + // Keep the file allocation instead of allocating a second payload-sized buffer. + // Split entries still copy below, so the whole shader does not retain all pieces. + let start = b.len() - len; + b.copy_within(start.., 0); + b.truncate(len); + return Some(Compiled { dxil: b, samplers, dispatch_chain: None }); } else { let dwords_per_group = u32_(&mut rest)?; let count = u32_(&mut rest)?; @@ -1836,6 +1845,71 @@ mod shader_cache_tests { } } + #[test] + fn translated_cache_reuses_unsplit_read_buffer() { + let dir = std::env::temp_dir().join(format!("xcl-translated-buffer-{}", std::process::id())); + let path = dir.join("entry"); + let blob = b"console-buffer"; + for count in [0, 1, 65] { + let mut expected = compiled(7); + expected.samplers = (0..count).map(|i| ([i, i + 1, i + 2, i + 3], i % 2 != 0)).collect(); + translated::store_in(&path, 42, blob, &expected); + let raw = std::fs::read(&path).unwrap(); + let (ptr, capacity) = (raw.as_ptr(), raw.capacity()); + let actual = translated::decode_entry(raw, 42, blob).unwrap(); + assert_eq!(actual.dxil, expected.dxil); + assert_eq!(actual.samplers, expected.samplers); + assert!(actual.dispatch_chain.is_none()); + assert_eq!(actual.dxil.as_ptr(), ptr, "reuse the file allocation"); + assert_eq!(actual.dxil.capacity(), capacity); + } + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn translated_cache_buffer_decode_preserves_validation_and_split_entries() { + let dir = std::env::temp_dir().join(format!("xcl-translated-decode-{}", std::process::id())); + let path = dir.join("entry"); + let blob = b"console-decode"; + let mut expected = compiled(9); + translated::store_in(&path, 42, blob, &expected); + let raw = std::fs::read(&path).unwrap(); + for len in 0..raw.len() { + assert!(translated::decode_entry(raw[..len].to_vec(), 42, blob).is_none(), "truncated at {len}"); + } + for count in 1..=16 { + let mut trailing = raw.clone(); + trailing.resize(raw.len() + count, 0); + assert!(translated::decode_entry(trailing, 42, blob).is_none(), "{count} trailing bytes"); + } + + let chain = Arc::new(crate::gpu::dxil::kernel::DispatchChain { + dwords_per_group: 8, + pieces: vec![synthetic_dxil(2), synthetic_dxil(3)], + }); + expected.dispatch_chain = Some(chain.clone()); + translated::store_in(&path, 42, blob, &expected); + let split = std::fs::read(&path).unwrap(); + let actual = translated::load_in(&path, 42, blob).unwrap(); + assert_eq!(actual.dxil, expected.dxil); + assert_eq!(actual.samplers, expected.samplers); + let actual_chain = actual.dispatch_chain.unwrap(); + assert_eq!(actual_chain.dwords_per_group, chain.dwords_per_group); + assert_eq!(actual_chain.pieces, chain.pieces); + for len in raw.len() + 1..split.len() { + assert!(translated::decode_entry(split[..len].to_vec(), 42, blob).is_none(), "split truncated at {len}"); + } + for offset in [0, 4, 8, 12] { + let mut corrupt = split.clone(); + corrupt[raw.len() + offset..raw.len() + offset + 4].fill(0); + assert!(translated::decode_entry(corrupt, 42, blob).is_none(), "invalid split field at {offset}"); + } + let mut trailing = split; + trailing.push(0); + assert!(translated::decode_entry(trailing, 42, blob).is_none()); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn shader_cache_skips_repeated_translation_and_disk_lookups() { let cache = Mutex::new(ShaderCache::new(1 << 20)); From d93c63a7489fcede78523a957632e4c4fd5c6068 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 21:58:38 -0800 Subject: [PATCH 069/265] D3D12.X: snapshot submitted queues with owned references Replace the raw submitted-queue list with a registry that owns exactly one process-lifetime interface per queue and clones strong snapshots under its mutex. Migrate late release, GPU drain, VRAM, and sparse consumers away from unlocked raw-interface reconstruction. This is behavior-neutral preparation for explicit active/retiring queue ownership: deduplication, insertion order, and permanent retention remain unchanged. GNU Windows-target cargo check passed. Windows/MSVC, GPU, and title smoke execution were not available on this host. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/late_release.rs | 8 +-- crates/xcl/src/hle/d3d12x/present.rs | 66 +++++++++++++++++++---- crates/xcl/src/hle/d3d12x/real.rs | 4 +- crates/xcl/src/hle/d3d12x/sparse.rs | 9 ++-- crates/xcl/src/hle/d3d12x/vram.rs | 5 +- 5 files changed, 63 insertions(+), 29 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..864c1693f3 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -128,13 +128,7 @@ pub unsafe fn drain_known(seal_now: bool) { if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { return; } - let mut queues: Vec = Vec::new(); - for raw in super::present::known_queues() { - let raw = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { - queues.push(q.clone()); - } - } + let mut queues = super::present::known_queues_held(); queues.extend(super::sparse::queue()); queues.extend(super::title_textures::upload_queues()); let gone = match HELD.lock().unwrap().as_mut() { diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index aabcd2a019..ad1feb5510 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -289,12 +289,38 @@ unsafe fn backbuffer_like(res: usize) -> Option { ok.then_some(d) } -/// queues the title submitted work to (AddRef'd: they stay valid for `drain`) -static QUEUES: Mutex> = Mutex::new(Vec::new()); +struct OwnedQueues { + entries: Vec<(usize, T)>, +} + +impl OwnedQueues { + const fn new() -> Self { + Self { entries: Vec::new() } + } + + /// Add the first owner for `key`. `make` is not called for a duplicate, so no temporary + /// owner can be dropped while the registry lock is held. + fn ensure_with(&mut self, key: usize, make: impl FnOnce() -> Option) -> bool { + if self.entries.iter().any(|&(k, _)| k == key) { + return false; + } + let Some(owner) = make() else { return false }; + self.entries.push((key, owner)); + true + } + + fn snapshot(&self) -> Vec { + self.entries.iter().map(|(_, owner)| owner.clone()).collect() + } +} + +/// Queues the title submitted work to. One process-lifetime owner per raw queue, as before. +static QUEUES: Mutex> = Mutex::new(OwnedQueues::new()); -/// The queues the title submitted work to. -pub fn known_queues() -> Vec { - QUEUES.lock().unwrap().clone() +/// Strong snapshot of the queues the title submitted work to. Every AddRef happens while the +/// registry is locked; callers own the returned references and drop them after the lock is gone. +pub fn known_queues_held() -> Vec { + QUEUES.lock().unwrap().snapshot() } static EXECUTES: AtomicU64 = AtomicU64::new(0); @@ -307,11 +333,8 @@ pub fn activity() -> (u64, u64) { pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) { EXECUTES.fetch_add(1, Ordering::Relaxed); { - let mut q = QUEUES.lock().unwrap(); - if !q.contains(&(queue as usize)) { - add_ref(queue as usize); - q.push(queue as usize); - } + let mut queues = QUEUES.lock().unwrap(); + queues.ensure_with(queue as usize, || ID3D12CommandQueue::from_raw_borrowed(&queue).cloned()); } super::late_release::drain_known(false); if !enabled() || IN_PRESENT.with(|c| c.get()) || PRESENTX.load(Ordering::Relaxed) { @@ -1477,6 +1500,29 @@ impl Drop for Presenter { mod tests { use super::*; + #[test] + fn owned_queue_registry_deduplicates_without_making_a_temporary_owner() { + let mut registry = OwnedQueues::new(); + assert!(registry.ensure_with(0xA, || Some(std::sync::Arc::new(1)))); + assert!(!registry.ensure_with(0xA, || -> Option> { panic!("duplicate owner was made") })); + assert!(registry.ensure_with(0xB, || Some(std::sync::Arc::new(2)))); + let values: Vec<_> = registry.snapshot().iter().map(|v| **v).collect(); + assert_eq!(values, [1, 2]); + } + + #[test] + fn owned_queue_snapshot_has_its_own_lifetime() { + let owner = std::sync::Arc::new(()); + let weak = std::sync::Arc::downgrade(&owner); + let mut registry = OwnedQueues::new(); + assert!(registry.ensure_with(0xA, || Some(owner))); + let snapshot = registry.snapshot(); + drop(registry); + assert!(weak.upgrade().is_some(), "the snapshot did not keep its owner alive"); + drop(snapshot); + assert!(weak.upgrade().is_none(), "the caller did not release its snapshot owner"); + } + #[test] fn present_ring_overlaps_previous_frame_and_drains_cleanly() { let mut ring = PresentRing::new(PRESENT_SLOTS); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5f49965099..bdcdbf2412 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7417,9 +7417,7 @@ pub fn drain_gpu() { unsafe { // a fence per queue (they finish in any order) let mut fences = Vec::new(); - for q in super::present::known_queues() { - let qr = q as *mut c_void; - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qr) else { continue }; + for q in super::present::known_queues_held() { let submit = || { let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) .map_err(|e| fence::api_error(dev, "CreateFence", e))?; diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 633f0d8d63..a4104352d4 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1445,12 +1445,9 @@ impl State { unsafe fn sync_known_queues(&mut self) -> bool { let mut ok = true; - for raw in super::present::known_queues() { - if !self.queue_fences.contains_key(&raw) { - let ptr = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&ptr) { - ok &= self.note_queue(q); - } + for q in super::present::known_queues_held() { + if !self.queue_fences.contains_key(&(q.as_raw() as usize)) { + ok &= self.note_queue(&q); } } ok diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 59582fa641..a58d38acbb 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1160,9 +1160,8 @@ unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueu out.push((key, q)); } }; - for raw in super::present::known_queues() { - let raw = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { add(q.clone()); } + for q in super::present::known_queues_held() { + add(q); } for q in extra.into_iter().cloned().chain(super::title_textures::upload_queues()).chain(super::sparse::queue()) { add(q); From c9f56d64cb44a6d3ed055cdebc8ab137117b7eec Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:28:06 +0300 Subject: [PATCH 070/265] D3D12.X: stop tracking placed aliases after the log cap Replace per-placement String formatting with a compact copyable descriptor summary, release the alias mutex before logging, and take a lock-free return after the 16 diagnostic lines have been emitted. Bound pre-cap unique-address tracking and free the table at the cap. GNU Windows-target cargo check passed. Windows/MSVC, long-run placement behavior, GPU tests, and title smoke were not run on this host. Adapted from PR #2636. Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/device_x.rs | 137 ++++++++++++++++++++++++-- 1 file changed, 128 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 57c30e0ffe..9bfae21fcf 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1065,19 +1065,78 @@ pub(super) unsafe extern "system" fn get_custom_heap_properties_x(a: *mut c_void ret } +const MAX_ALIAS_LOGS: u64 = 16; +const MAX_ALIAS_TRACKED: usize = 16_384; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PlacedDescSummary { + dim: u32, + width: u64, + height: u32, + format: u32, + flags: u32, +} + +impl PlacedDescSummary { + fn from_desc(x: &[u8; 0x38]) -> Self { + let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + Self { + dim: u(0), + width: u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), + height: u(0x18), + format: u(0x20), + flags: u(0x30), + } + } +} + +impl std::fmt::Display for PlacedDescSummary { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "dimension {} {}x{} format {} flags {:#x}", self.dim, self.width, self.height, self.format, self.flags) + } +} + +fn record_alias_in( + seen: &mut Option>, + logged: &AtomicU64, + va: usize, + cur: PlacedDescSummary, + max_tracked: usize, +) -> Option { + if logged.load(Ordering::Relaxed) >= MAX_ALIAS_LOGS { + *seen = None; + return None; + } + let m = seen.get_or_insert_with(std::collections::HashMap::new); + if let Some(slot) = m.get_mut(&va) { + let prev = std::mem::replace(slot, cur); + let prev_count = logged.fetch_add(1, Ordering::Relaxed); + if prev_count + 1 >= MAX_ALIAS_LOGS { + *seen = None; + } + return (prev_count < MAX_ALIAS_LOGS).then_some(prev); + } + if m.len() < max_tracked { + m.insert(va, cur); + } + None +} + /// Resources the title placed at an address an earlier one was placed at: on the console they /// share that memory (aliasing – transient render targets reuse it). Logged (first 16). fn note_alias(va: usize, x: &[u8; 0x38]) { - static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); + static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); static N: AtomicU64 = AtomicU64::new(0); - let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); - let what = format!("dimension {} {}x{} format {} flags {:#x}", u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u(0x20), u(0x30)); - let mut g = SEEN.lock().unwrap(); - let m = g.get_or_insert_with(std::collections::HashMap::new); - if let Some(prev) = m.insert(va, what.clone()) { - if N.fetch_add(1, Ordering::Relaxed) < 16 { - crate::xlog_info!("D3D12.X: CreatePlacedResourceX at {va:#x} ({what}) – aliases an earlier resource there ({prev})"); - } + if N.load(Ordering::Relaxed) >= MAX_ALIAS_LOGS { + return; + } + let cur = PlacedDescSummary::from_desc(x); + let prev = { + let mut g = SEEN.lock().unwrap(); + record_alias_in(&mut g, &N, va, cur, MAX_ALIAS_TRACKED) + }; + if let Some(prev) = prev { + crate::xlog_info!("D3D12.X: CreatePlacedResourceX at {va:#x} ({cur}) – aliases an earlier resource there ({prev})"); } } @@ -1722,4 +1781,64 @@ mod tests { m.remove(&((luid.LowPart, luid.HighPart), 24)); } } + + fn placed_desc(dim: u32, width: u64, height: u32, format: u32, flags: u32) -> [u8; 0x38] { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&dim.to_le_bytes()); + x[0x10..0x18].copy_from_slice(&width.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&height.to_le_bytes()); + x[0x20..0x24].copy_from_slice(&format.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + x + } + + #[test] + fn note_alias_logs_first_16_and_drops_table_after_cap() { + let first = PlacedDescSummary::from_desc(&placed_desc(3, 1920, 1080, 28, 0x5)); + assert_eq!(first.to_string(), "dimension 3 1920x1080 format 28 flags 0x5"); + + let mut seen = None; + let logged = AtomicU64::new(0); + assert_eq!(record_alias_in(&mut seen, &logged, 0x1000, first, MAX_ALIAS_TRACKED), None); + let mut expected_prev = first; + for i in 1..=MAX_ALIAS_LOGS { + let next = PlacedDescSummary::from_desc(&placed_desc(3, 1920 + i, 1080, 28, i as u32)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x1000, next, MAX_ALIAS_TRACKED), Some(expected_prev), "alias #{i}"); + expected_prev = next; + if i < MAX_ALIAS_LOGS { + assert!(seen.is_some(), "table stays active before cap (alias #{i})"); + } + } + assert!(seen.is_none(), "16th alias must drop the tracking table"); + let after = PlacedDescSummary::from_desc(&placed_desc(1, 4096, 1, 0, 0)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x1000, after, MAX_ALIAS_TRACKED), None); + assert_eq!(record_alias_in(&mut seen, &logged, 0x2000, after, MAX_ALIAS_TRACKED), None); + assert!(seen.is_none(), "calls after cap must not reallocate the tracking table"); + } + + #[test] + fn note_alias_bounds_tracked_entries_without_aliases() { + let mut seen = None; + let logged = AtomicU64::new(0); + let max_tracked = 8; + let d0 = PlacedDescSummary::from_desc(&placed_desc(3, 64, 64, 28, 1)); + for i in 0..(max_tracked + 5) { + assert_eq!(record_alias_in(&mut seen, &logged, 0x10000 + i * 0x1000, d0, max_tracked), None); + } + assert_eq!(seen.as_ref().unwrap().len(), max_tracked, "tracked VA count must stay bounded"); + let d1 = PlacedDescSummary::from_desc(&placed_desc(3, 128, 128, 28, 2)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x10000, d1, max_tracked), Some(d0), "aliasing a tracked entry still fires"); + assert_eq!(logged.load(Ordering::Relaxed), 1); + } + + #[test] + fn note_alias_short_circuits_when_cap_already_reached() { + let d0 = PlacedDescSummary::from_desc(&placed_desc(3, 32, 32, 28, 0)); + let mut seen = Some(std::collections::HashMap::from([(0x5000usize, d0)])); + let logged = AtomicU64::new(MAX_ALIAS_LOGS); + let d1 = PlacedDescSummary::from_desc(&placed_desc(3, 64, 64, 28, 4)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x5000, d1, MAX_ALIAS_TRACKED), None); + assert!(seen.is_none(), "residual map must be freed once cap is reached"); + assert_eq!(logged.load(Ordering::Relaxed), MAX_ALIAS_LOGS); + } } From 5d91261c4e35d61d4ebe051a4a33e2d2a68de9b1 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:00:32 -0800 Subject: [PATCH 071/265] Shaders: precompile runtime-selected graphics variants Route standalone VS and PS variants through the exact runtime console_to_dxil_in path so precompile warms translated/v2 serialization and the selected HLSL/direct-DXIL backend instead of only manually warming HLSL output. Selection matches the runtime's first hardware VS/PS FSSM and exact stage, split, windows, and base-zero keys. Paired PS variants with nonzero VS sampler bases remain cold because the shader archive has no pipeline pairing data. GNU Windows-target cargo check passed. Fresh-cache Windows probes, GPU execution, and retail smoke were not available on this host. Adapted from PR #2613. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/shaders.rs | 68 ++++++++++++++++++++++++++++++++------- 1 file changed, 56 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 0cd2ed7b3a..bfde971f5b 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1185,16 +1185,15 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl } /// `--precompile`: translate every VS / PS / MS / CS program and compile it into the DXIL cache -/// (`recomp::dxc::cache_dir()`), the same HLSL the runtime will ask for, so a title does not -/// wait for DXC on first use. Resumable: cached programs are skipped. GS halves need their -/// pipeline partner and are left to the runtime. -/// The cache key is the HLSL, so the options are the runtime's: `windows` memory windows as a -/// title's unified memory has (`pso::mem_windows`, 4; `--windows 1` for a title without it), -/// and the split wave64 form when this machine's GPU (`XCL_ADAPTER`) runs only 32-lane waves -/// (`pso::wave32_only_for_device`). Before, the programs were translated with one window and -/// no split form, so a title asked for other HLSL and compiled everything again. Still -/// different at run time: a PS's static samplers after its VS's (sampler base 0 here) and the -/// mesh pass-through, which the runtime builds for its pixel shader. +/// (`recomp::dxc::cache_dir()`), matching the runtime path so a title does not translate or run +/// DXC on first use. CS and standalone VS / PS variants also warm the runtime's `translated/v2` +/// cache (including the direct graphics backend). Resumable: cached programs are skipped. GS +/// halves need their pipeline partner and are left to the runtime. +/// The options are the runtime's: `windows` memory windows as a title's unified memory has +/// (`pso::mem_windows`, 4; `--windows 1` for a title without it), and the split wave64 form when +/// this machine's GPU (`XCL_ADAPTER`) runs 32-lane waves. Still different at run time: a paired +/// PS follows its VS's static samplers (only sampler base 0 can be known here), and the mesh +/// pass-through is built with its pixel shader. /// `--pipelines`: each compute program's pipeline made on the GPU as a title's would be (XCL's /// ABI root signature with its static samplers). Save the driver's compiled blob in the same /// cache the runtime reads at startup. Nothing runs on the GPU. @@ -1590,6 +1589,19 @@ fn used_compute(blob: &[u8], used: &std::collections::HashSet) -> bool { used.contains(&crate::hle::d3d12x::real::shaders_key(&[blob.to_vec()])) } +/// Standalone graphics variants whose runtime cache keys can be known without a pipeline pairing. +/// Runtime selection also uses the first hardware stage of the first matching FSSM (4: VS, 5: PS). +fn standalone_graphics_variants(blob: &[u8], sh: &xbox::XboxShader, split: bool, windows: u32) -> Vec<(recomp::pso::Stage, u32, bool, u32)> { + [(recomp::pso::Stage::Vertex, 4), (recomp::pso::Stage::Pixel, 5)] + .into_iter() + .filter(|&(stage, hw)| { + let Some(f) = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == hw)) else { return false }; + matches!((recomp::interface(blob, sh, f), stage), (Some(recomp::Mode::Vertex(_)), recomp::pso::Stage::Vertex) | (Some(recomp::Mode::Pixel(_)), recomp::pso::Stage::Pixel)) + }) + .map(|(stage, _)| (stage, 0, split, windows)) + .collect() +} + fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant) -> i32 { let pipelines = if pipelines { match Pipelines::new() { @@ -1670,11 +1682,22 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } continue; } + for (stage, sampler_base, split, windows) in standalone_graphics_variants(&blob, &sh, graphics_split, windows) { + match recomp::pso::console_to_dxil_in(&blob, stage, sampler_base, split, windows) { + Ok(_) => compiled.fetch_add(1, Ordering::Relaxed), + Err(e) => { + let mut g = errors.lock().unwrap(); + if g.len() < 10 { + g.push(format!("{name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or(e.lines().next().unwrap_or("")))); + } + failed.fetch_add(1, Ordering::Relaxed) + } + }; + } for f in &sh.fssm { let Some(mode) = recomp::interface(&blob, &sh, f) else { continue }; let jobs: Vec<(&str, Option)> = match &mode { - recomp::Mode::Vertex(_) => vec![("vs_6_6", None)], - recomp::Mode::Pixel(_) => vec![("ps_6_6", None)], + recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_) => continue, recomp::Mode::Compute(_) => vec![("cs_6_6", None)], recomp::Mode::Mesh(ms) => vec![("cs_6_6", None), ("ms_6_6", Some(recomp::mesh_passthrough(ms)))], _ => { @@ -2096,6 +2119,27 @@ mod tests { sample(5, &[compute]) } + #[test] + fn graphics_precompile_variants_match_runtime_stage_and_key_inputs() { + let vs_blob = sample(1, &[fssm(&CODE, &[(4, 0)]), fssm(&CODE, &[(4, 0)])]); + let ps_blob = sample(0, &[fssm(&CODE, &[(5, 1)])]); + let vs = xbox::parse(&vs_blob).unwrap(); + let ps = xbox::parse(&ps_blob).unwrap(); + assert_eq!( + standalone_graphics_variants(&vs_blob, &vs, true, 4 | recomp::HEAP_WINDOWS), + vec![(recomp::pso::Stage::Vertex, 0, true, 4 | recomp::HEAP_WINDOWS)], + "duplicate FSSMs still warm the one runtime-selected VS key", + ); + assert_eq!( + standalone_graphics_variants(&ps_blob, &ps, false, 1), + vec![(recomp::pso::Stage::Pixel, 0, false, 1)], + "the PS key keeps the exact split/windows and the only knowable sampler base", + ); + let es_blob = sample(1, &[fssm(&CODE, &[(3, 0), (4, 0)])]); + let es = xbox::parse(&es_blob).unwrap(); + assert!(standalone_graphics_variants(&es_blob, &es, false, 1).is_empty(), "runtime only classifies the first hardware stage"); + } + #[test] fn record_hash_is_strict_hex() { assert_eq!(parse_record_hash("0x0123aB").unwrap(), 0x123AB); From 7273e250644e52f5d3beb0a4d76dd8806b2c50b0 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 07:10:58 +0300 Subject: [PATCH 072/265] Recompiler: prune unreachable direct-DXIL module values Compute transitive liveness for globals, declarations, and module constants from reachable instructions and metadata. Trace only live global initializers and aggregate elements, then compact the constant block through a stable old-to-new value map. This removes dead constants and prevents an unreachable aggregate from retaining otherwise-unused internal symbols while preserving idempotent serialization and reachable Phi semantics. GNU Windows-target cargo check passed here. Upstream validation includes native AMD wave64 and NVIDIA direct-DXIL GPU suites; Windows/MSVC and GPU execution were not repeated on this host. Adapted from PR #2640. Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/module.rs | 194 ++++++++++++++++++++++++------ 1 file changed, 159 insertions(+), 35 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d72ef6fc38..23345b83a1 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -827,37 +827,10 @@ impl Module { // are dropped. Value numbering follows that order. let (order, pos) = self.block_layout(); - // Global variables nothing references (e.g. an exchange array the code never - // needed) are left out: the validator rejects unused internal declarations. - // Likewise declarations of functions no longer called (after `optimize`). - let mut gused = vec![false; self.globals.len()]; - let mut fused: Vec = self.funcs.iter().map(|f| f.defined).collect(); - { - let mut mark = |v: Value| match v { - Value::Global(g) => gused[g as usize] = true, - Value::Func(f) => fused[f as usize] = true, - _ => {} - }; - for &b in &order { - for &i in &self.blocks[b] { - let op = &self.insts[i as usize].op; - if let Op::Call(f, _) = op { - mark(Value::Func(*f)); - } - op.for_each_operand(&mut mark); - } - } - for c in &self.consts { - if let ConstDef::Aggregate(_, e) = c { - e.iter().copied().for_each(&mut mark); - } - } - for m in &self.md { - if let MdDef::Val(_, v) = m { - mark(*v); - } - } - } + // Global variables, declarations, and module constants nothing references + // are left out: the validator rejects unused internal declarations, and + // pruning dead constants keeps BLOCK_CONSTANTS compact after `optimize`. + let (gused, fused, cused) = self.live_values(&order, &pos); let mut gmap: Vec> = vec![None; self.globals.len()]; let mut n_globals = 0u64; for (g, used) in gused.iter().enumerate() { @@ -876,7 +849,11 @@ impl Module { } } let fmap = &fmap; - let n_consts = self.consts.len() as u64; + let (mut cmap, mut n_consts) = (vec![None; self.consts.len()], 0u64); + for (c, &used) in cused.iter().enumerate() { + if used { cmap[c] = Some(n_consts); n_consts += 1; } + } + let cmap = &cmap; let const_base = n_globals + n_funcs; let inst_base = const_base + n_consts; @@ -897,7 +874,7 @@ impl Module { match v { Value::Global(g) => gmap[g as usize].expect("use of a dropped global"), Value::Func(f) => n_globals + fmap[f as usize].expect("use of a dropped function"), - Value::Const(c) => const_base + c as u64, + Value::Const(c) => const_base + cmap[c as usize].expect("use of a dropped constant"), Value::Inst(i) => inst_ids[i as usize].unwrap_or_else(|| { self.fail(format!("use of a void instruction %{i}")); 0 @@ -952,10 +929,10 @@ impl Module { } // Module-level constants. - if !self.consts.is_empty() { + if n_consts > 0 { w.enter_block(BLOCK_CONSTANTS); let mut cur_ty = None; - for c in &self.consts { + for c in self.consts.iter().enumerate().filter(|(i, _)| cused[*i]).map(|x| x.1) { let t = match c { ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, }; @@ -1036,6 +1013,51 @@ impl Module { matches!(self.types[t.0 as usize], TypeDef::Void) } + /// `(gused, fused, cused)` liveness over reachable blocks (`order`) and metadata. + fn live_values(&self, order: &[usize], pos: &[Option]) -> (Vec, Vec, Vec) { + let mut gused = vec![false; self.globals.len()]; + let mut fused: Vec = self.funcs.iter().map(|f| f.defined).collect(); + let mut cused = vec![false; self.consts.len()]; + let mut work = Vec::new(); + let mark = |v: Value, g: &mut [bool], f: &mut [bool], c: &mut [bool], w: &mut Vec| match v { + Value::Global(i) if !g[i as usize] => { g[i as usize] = true; w.push(v); } + Value::Func(i) => f[i as usize] = true, + Value::Const(i) if !c[i as usize] => { c[i as usize] = true; w.push(v); } + _ => {} + }; + for &b in order { + for &i in &self.blocks[b] { + match &self.insts[i as usize].op { + Op::Call(f, args) => { + mark(Value::Func(*f), &mut gused, &mut fused, &mut cused, &mut work); + args.iter().for_each(|&a| mark(a, &mut gused, &mut fused, &mut cused, &mut work)); + } + Op::Phi(inc) => for &(v, pred) in inc { + if pos.get(pred.0 as usize).copied().flatten().is_some() { + mark(v, &mut gused, &mut fused, &mut cused, &mut work); + } + }, + op => op.for_each_operand(|v| mark(v, &mut gused, &mut fused, &mut cused, &mut work)), + } + } + } + for m in &self.md { + if let MdDef::Val(_, v) = m { mark(*v, &mut gused, &mut fused, &mut cused, &mut work); } + } + while let Some(v) = work.pop() { + match v { + Value::Global(g) => if let Some(init) = self.globals[g as usize].init { + mark(init, &mut gused, &mut fused, &mut cused, &mut work); + }, + Value::Const(c) => if let ConstDef::Aggregate(_, elems) = &self.consts[c as usize] { + elems.iter().for_each(|&e| mark(e, &mut gused, &mut fused, &mut cused, &mut work)); + }, + _ => {} + } + } + (gused, fused, cused) + } + fn write_types(&self, w: &mut BitWriter) { w.enter_block(BLOCK_TYPE); w.record(TYPE_CODE_NUMENTRY, &[self.types.len() as u64]); @@ -1541,6 +1563,7 @@ impl Module { #[cfg(test)] mod tests { use super::*; + use crate::gpu::dxil::{container::Stage, shader::{self, Shader}, validate}; #[test] fn sign_extension_does_not_intern_unrelated_integer_types() { @@ -1569,4 +1592,105 @@ mod tests { if source == bit && module.int_width(ty) == Some(32))); assert!(matches!(second.op, Op::Cast(CastOp::SExt, Value::Inst(0), ty) if ty == i64)); } + + fn symtab_names(bc: &[u8]) -> Vec { + assert!(bc.starts_with(&[b'B', b'C', 0xC0, 0xDE])); + let (mut bit, mut w, mut blk, mut stack, mut out) = (32usize, 2u32, 0u32, Vec::new(), Vec::new()); + let bits = |bit: &mut usize, n: u32| (0..n).fold(0u64, |v, k| { let b = (bc[*bit / 8] >> (*bit % 8)) & 1; *bit += 1; v | ((b as u64) << k) }); + let vbr = |bit: &mut usize, n: u32| { + let (mut o, mut s, hi) = (0u64, 0u32, 1u64 << (n - 1)); + loop { let c = bits(bit, n); o |= (c & (hi - 1)) << s; if c & hi == 0 { return o; } s += n - 1; } + }; + while bit + w as usize <= bc.len() * 8 { + match bits(&mut bit, w) { + 0 => { bit = (bit + 31) & !31; if let Some((pw, pb)) = stack.pop() { w = pw; blk = pb; } else { break; } } + 1 => { let (id, nw) = (vbr(&mut bit, 8) as u32, vbr(&mut bit, 4) as u32); bit = ((bit + 31) & !31) + 32; stack.push((w, blk)); w = nw; blk = id; } + 3 => { + let (code, n) = (vbr(&mut bit, 6) as u32, vbr(&mut bit, 6) as usize); + let ops: Vec = (0..n).map(|_| vbr(&mut bit, 6)).collect(); + if blk == BLOCK_VALUE_SYMTAB && code == VST_CODE_ENTRY { out.push(String::from_utf8(ops[1..].iter().map(|&x| x as u8).collect()).unwrap()); } + } + other => panic!("unexpected abbrev {other}"), + } + } + out + } + + #[test] + fn unused_scalar_constants_produce_identical_bitcode() { + let build = |with_dead: bool| { + let mut m = Module::new(); + m.define_entry("main"); + let (entry, merge, i32) = (m.entry_block(), m.new_block(), m.i32()); + let (c_i, c_f, c_md) = (m.i32c(7), m.f32c(1.0f32.to_bits()), m.i32c(99)); + let _ = m.md_value(c_md); + let sum = m.bin(BinOp::Add, c_i, c_i); + let _ = m.fbin(BinOp::Add, c_f, c_f, fmf::NONE); + m.br(merge); m.set_block(merge); + let phi = m.phi(i32); m.add_incoming(phi, sum, entry); m.ret(); + let mut dead = Vec::new(); + if with_dead { + for k in 0..256u32 { dead.extend([m.i32c(10_000 + k), m.f32c((2.0f32 + k as f32).to_bits())]); } + let unreach = m.new_block(); m.set_block(unreach); + let (c_u, c_phi) = (m.i32c(0xDEAD_0001), m.i32c(0xDEAD_0002)); + let _ = m.bin(BinOp::Add, c_u, c_u); m.br(merge); + m.add_incoming(phi, c_phi, unreach); dead.extend([c_u, c_phi]); + } + (m, [c_i, c_f, c_md], dead) + }; + let ((mut clean, _, _), (mut noisy, live, dead)) = (build(false), build(true)); + let (order, pos) = noisy.block_layout(); let (_, _, cused) = noisy.live_values(&order, &pos); + for v in live { let Value::Const(c) = v else { unreachable!() }; assert!(cused[c as usize]); } + for v in dead { let Value::Const(c) = v else { unreachable!() }; assert!(!cused[c as usize]); } + assert_eq!(clean.try_to_bitcode(shader::TRIPLE, shader::DATALAYOUT).unwrap(), noisy.try_to_bitcode(shader::TRIPLE, shader::DATALAYOUT).unwrap()); + } + + #[test] + fn dead_aggregate_does_not_retain_unused_global_while_live_global_init_is_kept() { + let mut m = Module::new(); m.define_entry("main"); + let i32 = m.i32(); + let (inner_ty, p_i32) = (m.array(2, i32), m.ptr(i32, 0)); + let (outer_ty, dead_arr_ty) = (m.array(2, inner_ty), m.array(1, p_i32)); + let (a0, a1, a2, a3, z, d_val) = (m.i32c(11), m.i32c(22), m.i32c(33), m.i32c(44), m.i32c(0), m.i32c(77)); + let (r0, r1) = (m.aggregate(inner_ty, &[a0, a1]), m.aggregate(inner_ty, &[a2, a3])); + let live_init = m.aggregate(outer_ty, &[r0, r1]); + let g_live = m.global("live_tbl", outer_ty, 0, Some(live_init), true, 4); + let p = m.gep(g_live, &[z, z, z]); let _ = m.load(p, 4); m.ret(); + let g_dead_inner = m.global("dead_inner_sym", i32, 0, Some(d_val), true, 4); + let dead_agg = m.aggregate(dead_arr_ty, &[g_dead_inner]); + let g_dead = m.global("dead_outer_sym", dead_arr_ty, 0, Some(dead_agg), true, 4); + let (order, pos) = m.block_layout(); let (gused, _, cused) = m.live_values(&order, &pos); + let (Value::Global(gl), Value::Global(gd), Value::Global(gdi)) = (g_live, g_dead, g_dead_inner) else { unreachable!() }; + assert!(gused[gl as usize] && !gused[gd as usize] && !gused[gdi as usize], "globals: {gused:?}"); + for v in [a0, a1, a2, a3, r0, r1, live_init, z] { let Value::Const(c) = v else { unreachable!() }; assert!(cused[c as usize]); } + for v in [d_val, dead_agg] { let Value::Const(c) = v else { unreachable!() }; assert!(!cused[c as usize]); } + let bc = m.try_to_bitcode(shader::TRIPLE, shader::DATALAYOUT).unwrap(); + assert_eq!(bc, m.try_to_bitcode(shader::TRIPLE, shader::DATALAYOUT).unwrap()); + let names = symtab_names(&bc); + assert!(names.iter().any(|n| n == "live_tbl") && !names.iter().any(|n| n == "dead_outer_sym" || n == "dead_inner_sym"), "{names:?}"); + } + + #[test] + fn pruned_direct_dxil_shader_with_live_table_and_dead_constants_validates() { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let (uav, i32) = (s.raw_uav(0, 0), s.m.i32()); + let (at, p_i32) = (s.m.array(4, i32), s.m.ptr(i32, 0)); + let vals = [s.m.i32c(10), s.m.i32c(20), s.m.i32c(30), s.m.i32c(40)]; + let init = s.m.aggregate(at, &vals); let tbl = s.m.global("live_tbl", at, 0, Some(init), true, 4); + let tid = s.thread_id_in_group(0); + let (c0, c2, c3) = (s.m.i32c(0), s.m.i32c(2), s.m.i32c(3)); + let idx = s.m.bin(BinOp::And, tid, c3); let ptr = s.m.gep(tbl, &[c0, idx]); + let loaded = s.m.load(ptr, 4); let off = s.m.bin(BinOp::Shl, tid, c2); + s.raw_store(uav, off, &[loaded]); + for k in 0..64u32 { let _ = s.m.i32c(10_000 + k); } + let d0 = s.m.i32c(9999); let g_dead = s.m.global("dead_inner_tbl", i32, 0, Some(d0), true, 4); + let d_arr = s.m.array(1, p_i32); let _dead_agg = s.m.aggregate(d_arr, &[g_dead]); + let dxil = s.try_finish([1, 1, 1], None).expect("try_finish must succeed"); + assert!(dxil.len() >= 32 && &dxil[..4] == b"DXBC"); + if crate::gpu::recomp::dxc::create_instance().is_some() { + validate::validate(&dxil).expect("pruned DXIL shader must validate"); + let dis = validate::disassemble(&dxil).expect("disassemble pruned DXIL shader"); + assert!(dis.contains("@live_tbl") && !dis.contains("@dead_inner_tbl"), "unexpected globals:\n{dis}"); + } + } } From b077218f135e600281083d7b7eb8090cb979327f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 07:15:56 +0300 Subject: [PATCH 073/265] Recompiler: simplify direct DXIL frexp and alignbit helpers Lower frexp mantissa and exponent directly from exponent bits, avoiding driver-dependent float classification and integer/float round trips. Simplify alignbit with a constant fast path and select-free dynamic shifts whose individual counts remain in range. Adapted from #2641. Upstream reports direct-DXIL validation plus wave32 GPU parity on NVIDIA RTX 3060 and AMD RX 9070. Locally cross-checked only with the GNU Windows target; Windows GPU execution remains untested here. Part of #2508 Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/prelude.rs | 215 +++++++++++++++++++++++------ 1 file changed, 173 insertions(+), 42 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/prelude.rs b/crates/xcl/src/gpu/dxil/prelude.rs index 7a5e5b65c4..33369da2d2 100644 --- a/crates/xcl/src/gpu/dxil/prelude.rs +++ b/crates/xcl/src/gpu/dxil/prelude.rs @@ -78,42 +78,28 @@ impl Lw { let k = self.s.m.f32c(0x3F7F_FFFF); self.sel(ge, k, r) } - /// HLSL `frexp` as DXC lowers it: (mantissa, exponent as float). - fn frexp_dxc(&mut self, x: Value) -> (Value, Value) { - let i = self.bits(x); - let e = self.andc(i, 0x7F80_0000); - let mant = self.andc(i, 0x007F_FFFF); // DXC drops the sign - let e = self.addc(e, (-0x3F00_0000i32) as u32); - let e = self.ashrc(e, 23); - let mant = self.orc(mant, 0x3F00_0000); - let z = self.fc(0.0); - let nz = self.fcmp(Pred::FUNe, x, z); - let ef = self.sitof(e); - let ef = self.sel(nz, ef, z); - let mf = self.f(mant); - let mf = self.sel(nz, mf, z); - (mf, ef) - } - /// The ISA's mantissa keeps the input's sign (as `frexp_mant_d` does); DXC's `frexp` drops it. + /// The ISA's mantissa keeps the input's sign (as `frexp_mant_d` does); 0 / FTZ subnormal / Inf / NaN pass through. pub fn frexp_mant(&mut self, x: Value) -> Value { - let (m, _) = self.frexp_dxc(x); - let mb = self.bits(m); - let xb = self.bits(x); - let sign = self.andc(xb, 0x8000_0000); - let mb = self.or(mb, sign); - let m = self.f(mb); - let a = self.isinf(x); - let b = self.isnan(x); - let s = self.lor(a, b); - self.sel(s, x, m) + let i = self.bits(x); + let e_raw = self.andc(i, 0x7F80_0000); + let zero = self.cmpc(Pred::Eq, e_raw, 0); + let special = self.cmpc(Pred::Eq, e_raw, 0x7F80_0000); + let sign = self.andc(i, 0x8000_0000); + let norm = self.andc(i, 0x807F_FFFF); + let norm = self.orc(norm, 0x3F00_0000); + let mb = self.sel(zero, sign, norm); + let mb = self.sel(special, i, mb); + self.f(mb) } pub fn frexp_exp(&mut self, x: Value) -> Value { - let (_, e) = self.frexp_dxc(x); - let a = self.isinf(x); - let b = self.isnan(x); - let s = self.lor(a, b); - let ei = self.ftosi(e); - self.selc(s, 0, ei) + let i = self.bits(x); + let e_raw = self.andc(i, 0x7F80_0000); + let e = self.addc(e_raw, (-0x3F00_0000i32) as u32); + let e = self.ashrc(e, 23); + let zero = self.cmpc(Pred::Eq, e_raw, 0); + let special = self.cmpc(Pred::Eq, e_raw, 0x7F80_0000); + let zero_or_special = self.lor(zero, special); + self.selc(zero_or_special, 0, e) } pub fn frexp_exp_f32(&mut self, bits: Value, legacy_src: impl FnOnce(&mut Self) -> Value) -> Value { use super::lower_round::{F32_DENORM_INPUT_WRITTEN, VAR_F32_MODE}; @@ -302,15 +288,22 @@ impl Lw { self.ashrc(s, 8) } pub fn alignbit(&mut self, s0: Value, s1: Value, s: Value) -> Value { - let s = self.andc(s, 31); - let a = self.bin(BinOp::LShr, s1, s); - let k = self.c(32); - let t = self.sub(k, s); - let t = self.andc(t, 31); - let b = self.bin(BinOp::Shl, s0, t); - let r = self.or(a, b); - let z = self.cmpc(Pred::Eq, s, 0); - self.sel(z, s1, r) + if let Some(k) = self.s.m.const_u64(s) { + let sh = (k as u32) & 31; + if sh == 0 { + return s1; + } + let lo = self.lshrc(s1, sh); + let hi = self.shlc(s0, 32 - sh); + return self.or(hi, lo); + } + let sh = self.andc(s, 31); + let lo = self.bin(BinOp::LShr, s1, sh); + let k31 = self.c(31); + let inv = self.xor(sh, k31); + let s0_1 = self.shlc(s0, 1); + let hi = self.bin(BinOp::Shl, s0_1, inv); + self.or(hi, lo) } pub fn perm_b32(&mut self, s0: Value, s1: Value, sel: Value) -> Value { let mut r = self.c(0); @@ -927,4 +920,142 @@ mod fclass_const_tests { } } } + + #[test] + fn gpu_direct_frexp_avoids_special_float_and_int_float_roundtrip() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let mut code = Vec::new(); + code.extend(encode("V_FREXP_MANT_F32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 256)], None).unwrap()); + code.extend(encode("V_FREXP_EXP_I32_F32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 256)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let dxil = translate(&code, ko).expect("translate frexp"); + if crate::gpu::recomp::dxc::create_instance().is_some() { + validate::validate(&dxil).expect("validate frexp"); + let dis = validate::disassemble(&dxil).expect("disassemble frexp"); + assert!(!dis.contains("@dx.op.isSpecialFloat"), "unexpected isSpecialFloat:\n{dis}"); + assert!(!dis.contains("sitofp "), "unexpected sitofp:\n{dis}"); + assert!(!dis.contains("fptosi "), "unexpected fptosi:\n{dis}"); + assert!(!dis.contains("fcmp oeq"), "unexpected float zero-compare (driver FTZ dependent):\n{dis}"); + } + if runner::wave32_supported() != Ok(true) { + runner::skip_test("no wave32"); + return; + } + // (bits, expected_mant, expected_exp) under D3D12 FTZ; ±subnormal -> (±0.0, 0). + const CASES: [(u32, u32, i32); 12] = [ + (0x0000_0000, 0x0000_0000, 0), // +0.0 + (0x8000_0000, 0x8000_0000, 0), // -0.0 + (0x0000_0001, 0x0000_0000, 0), // +subnormal (FTZ) + (0x8040_0000, 0x8000_0000, 0), // -subnormal (FTZ) + (0x0080_0000, 0x3F00_0000, -125), // +min normal + (0xBF80_0000, 0xBF00_0000, 1), // -1.0 + (0x4060_0000, 0x3F60_0000, 2), // +3.5 + (0xC122_0000, 0xBF22_0000, 4), // -10.125 + (0x7F80_0000, 0x7F80_0000, 0), // +Inf + (0xFF80_0000, 0xFF80_0000, 0), // -Inf + (0x7F80_0001, 0x7F80_0001, 0), // +sNaN + (0xFFC0_1234, 0xFFC0_1234, 0), // -qNaN + ]; + let mut st = KernelState::default(); + for (lane, &(bits, _, _)) in CASES.iter().enumerate() { + st.vgpr[lane][0] = bits; + } + let r = runner::run(&dxil, &st, &[]).expect("GPU run frexp"); + for (lane, &(bits, want_m, want_e)) in CASES.iter().enumerate() { + assert_eq!(r.vgpr[lane][1], want_m, "frexp_mant lane {lane} bits={bits:#010x}"); + assert_eq!(r.vgpr[lane][2] as i32, want_e, "frexp_exp lane {lane} bits={bits:#010x}"); + } + } + + #[test] + fn gpu_direct_frexp_f16_avoids_special_float_and_matches_isa() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let mut code = Vec::new(); + code.extend(encode("V_FREXP_MANT_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", 256)], None).unwrap()); + code.extend(encode("V_FREXP_EXP_I16_F16", "ENC_VOP1", &[("VDST", 2), ("SRC0", 256)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let dxil = translate(&code, ko).expect("translate frexp_f16"); + if crate::gpu::recomp::dxc::create_instance().is_some() { + validate::validate(&dxil).expect("validate frexp_f16"); + let dis = validate::disassemble(&dxil).expect("disassemble frexp_f16"); + assert!(!dis.contains("@dx.op.isSpecialFloat"), "unexpected isSpecialFloat in f16:\n{dis}"); + assert!(!dis.contains("sitofp "), "unexpected sitofp in f16:\n{dis}"); + assert!(!dis.contains("fptosi "), "unexpected fptosi in f16:\n{dis}"); + assert!(!dis.contains("fcmp oeq"), "unexpected float zero-compare in f16:\n{dis}"); + } + if runner::wave32_supported() != Ok(true) { + runner::skip_test("no wave32"); + return; + } + // (f16_bits, expected_mant_f16 (None = NaN), expected_exp_i16) + const CASES: [(u16, Option, i16); 11] = [ + (0x0000, Some(0x0000), 0), // +0.0 + (0x8000, Some(0x8000), 0), // -0.0 + (0x0001, Some(0x3800), -23), // +min subnormal (2^-24 = 0.5 * 2^-23) + (0x8200, Some(0xB800), -14), // -subnormal (-2^-15 = -0.5 * 2^-14) + (0xBC00, Some(0xB800), 1), // -1.0 -> (-0.5, 1) + (0xC910, Some(0xB910), 4), // -10.125 -> (-0.6328125, 4) + (0x4200, Some(0x3A00), 2), // +3.0 -> (0.75, 2) + (0x7C00, Some(0x7C00), 0), // +Inf + (0xFC00, Some(0xFC00), 0), // -Inf + (0x7E00, None, 0), // +qNaN + (0xFE01, None, 0), // -qNaN + ]; + let mut st = KernelState::default(); + for (lane, &(bits, _, _)) in CASES.iter().enumerate() { + st.vgpr[lane][0] = bits as u32; + } + let r = runner::run(&dxil, &st, &[]).expect("GPU run frexp_f16"); + for (lane, &(bits, want_m, want_e)) in CASES.iter().enumerate() { + let got_m = (r.vgpr[lane][1] & 0xFFFF) as u16; + let got_e = (r.vgpr[lane][2] & 0xFFFF) as i16; + match want_m { + Some(m) => assert_eq!(got_m, m, "frexp_mant_f16 lane {lane} bits={bits:#06x}"), + None => assert!((got_m & 0x7C00) == 0x7C00 && (got_m & 0x03FF) != 0, "frexp_mant_f16 NaN lane {lane} bits={bits:#06x} got={got_m:#06x}"), + } + assert_eq!(got_e, want_e, "frexp_exp_i16_f16 lane {lane} bits={bits:#06x}"); + } + } + + #[test] + fn gpu_direct_alignbit_is_select_free_and_matches_isa() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let mut code = Vec::new(); + code.extend(encode("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 256), ("SRC1", 257), ("SRC2", 258)], None).unwrap()); + for (i, sh) in [0u64, 1, 13, 31, 32].into_iter().enumerate() { + code.extend(encode("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 4 + i as u64), ("SRC0", 256), ("SRC1", 257), ("SRC2", 128 + sh)], None).unwrap()); + } + code.extend(encode("V_ALIGNBYTE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 256), ("SRC1", 257), ("SRC2", 258)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let dxil = translate(&code, ko).expect("translate alignbit"); + if crate::gpu::recomp::dxc::create_instance().is_some() { + validate::validate(&dxil).expect("validate alignbit"); + let dis = validate::disassemble(&dxil).expect("disassemble alignbit"); + assert_eq!(dis.matches(" = select i1 ").count(), 7, "only the 7 EXEC-mask VGPR writes may use select:\n{dis}"); + assert_eq!(dis.matches("icmp eq i32 ").count(), 1, "only the lane-0 epilogue guard may use icmp eq:\n{dis}"); + assert!(!dis.contains("sub i32 32,"), "unexpected sub-32 shift workaround:\n{dis}"); + } + if runner::wave32_supported() != Ok(true) { + runner::skip_test("no wave32"); + return; + } + let ref_ab = |s0: u32, s1: u32, s: u32| ((((s0 as u64) << 32) | (s1 as u64)) >> (s & 31)) as u32; + for base in [0u32, 32, 0xFFFF_FFE0] { + let mut st = KernelState::default(); + for lane in 0..32usize { + st.vgpr[lane][0] = 0xA5C3_1E79u32.wrapping_add((lane as u32).wrapping_mul(0x0101_0101)); + st.vgpr[lane][1] = 0x1234_5678u32.wrapping_add((lane as u32).wrapping_mul(0x1020_3040)); + st.vgpr[lane][2] = base.wrapping_add(lane as u32); + } + let r = runner::run(&dxil, &st, &[]).expect("GPU run alignbit"); + for lane in 0..32usize { + let (s0, s1, s) = (st.vgpr[lane][0], st.vgpr[lane][1], st.vgpr[lane][2]); + assert_eq!(r.vgpr[lane][3], ref_ab(s0, s1, s), "dyn alignbit base={base:#x} lane={lane} s={s:#x}"); + for (i, sh) in [0u32, 1, 13, 31, 32].into_iter().enumerate() { + assert_eq!(r.vgpr[lane][4 + i], ref_ab(s0, s1, sh), "const alignbit sh={sh} lane={lane}"); + } + assert_eq!(r.vgpr[lane][9], ref_ab(s0, s1, (s & 3) * 8), "alignbyte base={base:#x} lane={lane} s={s:#x}"); + } + } + } } From c52ad7269acee0203c8e84bcba387521fcc26101 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:07:01 -0800 Subject: [PATCH 074/265] D3D12.X: model command queue retirement generations Introduce an inactive retirement state machine while preserving current production behavior. Retiring queues remain visible to every strong snapshot until an exact-generation completion mark is swept, and failed or unmarked retirement remains pinned. Return owners and completion markers from the registry before dropping either, so COM releases cannot occur under the registry lock. This is the behavior-neutral Stage B prerequisite for bounded queue retirement. Locally cross-checked with the GNU Windows target; Windows execution remains untested here. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/present.rs | 223 ++++++++++++++++++++++++--- 1 file changed, 205 insertions(+), 18 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index ad1feb5510..883ce4eadc 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -289,33 +289,137 @@ unsafe fn backbuffer_like(res: usize) -> Option { ok.then_some(d) } -struct OwnedQueues { - entries: Vec<(usize, T)>, +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub(super) struct QueueId { + raw: usize, + generation: u64, } -impl OwnedQueues { +impl QueueId { + #[allow(dead_code)] // Used by queue-cache invalidation in a later unit. + pub(super) fn raw(self) -> usize { + self.raw + } +} + +#[derive(Clone)] +#[allow(dead_code)] // Stage B marker: read by the retirement worker in a later unit. +pub(super) struct QueueRetirementMark { + pub(super) fence: ID3D12Fence, + pub(super) value: u64, +} + +enum Retiring { + Preparing, + Mark(M), + Failed, +} + +enum QueueState { + Active, + Retiring(Retiring), +} + +struct QueueEntry { + id: QueueId, + owner: T, + state: QueueState, +} + +struct OwnedQueues { + entries: Vec>, + next_generation: u64, +} + +impl OwnedQueues { const fn new() -> Self { - Self { entries: Vec::new() } + Self { entries: Vec::new(), next_generation: 1 } } /// Add the first owner for `key`. `make` is not called for a duplicate, so no temporary /// owner can be dropped while the registry lock is held. - fn ensure_with(&mut self, key: usize, make: impl FnOnce() -> Option) -> bool { - if self.entries.iter().any(|&(k, _)| k == key) { + fn ensure_with(&mut self, raw: usize, make: impl FnOnce() -> Option) -> Option { + if self.entries.iter().any(|entry| entry.id.raw == raw) { + return None; + } + let owner = make()?; + let id = QueueId { raw, generation: self.next_generation }; + self.next_generation = self.next_generation.wrapping_add(1).max(1); + self.entries.push(QueueEntry { id, owner, state: QueueState::Active }); + Some(id) + } + + fn snapshot(&self) -> Vec { + self.entries.iter().map(|entry| entry.owner.clone()).collect() + } + + fn active_id(&self, raw: usize) -> Option { + self.entries + .iter() + .find(|entry| entry.id.raw == raw && matches!(&entry.state, QueueState::Active)) + .map(|entry| entry.id) + } + + fn begin_retiring(&mut self, id: QueueId) -> bool { + let Some(entry) = self.entries.iter_mut().find(|entry| entry.id == id) else { return false }; + if !matches!(&entry.state, QueueState::Active) { return false; } - let Some(owner) = make() else { return false }; - self.entries.push((key, owner)); + entry.state = QueueState::Retiring(Retiring::Preparing); true } - fn snapshot(&self) -> Vec { - self.entries.iter().map(|(_, owner)| owner.clone()).collect() + fn mark_retiring(&mut self, id: QueueId, mark: M) -> Result<(), M> { + let Some(entry) = self.entries.iter_mut().find(|entry| entry.id == id) else { return Err(mark) }; + if !matches!(&entry.state, QueueState::Retiring(Retiring::Preparing)) { + return Err(mark); + } + entry.state = QueueState::Retiring(Retiring::Mark(mark)); + Ok(()) + } + + fn fail_retiring(&mut self, id: QueueId) -> bool { + let Some(entry) = self.entries.iter_mut().find(|entry| entry.id == id) else { return false }; + if !matches!(&entry.state, QueueState::Retiring(Retiring::Preparing)) { + return false; + } + entry.state = QueueState::Retiring(Retiring::Failed); + true + } + + /// Copy marks for completion checks after unlocking. + fn retirement_marks(&self) -> Vec<(QueueId, M)> + where + M: Clone, + { + self.entries + .iter() + .filter_map(|entry| match &entry.state { + QueueState::Retiring(Retiring::Mark(mark)) => Some((entry.id, mark.clone())), + _ => None, + }) + .collect() + } + + /// Remove entries whose marks were found complete outside the registry lock, and return + /// their owners for release after unlocking. + fn sweep(&mut self, completed: &[QueueId]) -> Vec<(T, M)> { + let (mut kept, mut gone) = (Vec::with_capacity(self.entries.len()), Vec::new()); + for entry in std::mem::take(&mut self.entries) { + match entry { + QueueEntry { id, owner, state: QueueState::Retiring(Retiring::Mark(mark)) } if completed.contains(&id) => { + gone.push((owner, mark)); + } + entry => kept.push(entry), + } + } + self.entries = kept; + gone } } /// Queues the title submitted work to. One process-lifetime owner per raw queue, as before. -static QUEUES: Mutex> = Mutex::new(OwnedQueues::new()); +static QUEUES: Mutex> = Mutex::new(OwnedQueues::new()); /// Strong snapshot of the queues the title submitted work to. Every AddRef happens while the /// registry is locked; callers own the returned references and drop them after the lock is gone. @@ -323,6 +427,41 @@ pub fn known_queues_held() -> Vec { QUEUES.lock().unwrap().snapshot() } +#[allow(dead_code)] // Stage B API: wired to queue Release in a later unit. +pub(super) fn begin_queue_retirement(raw: usize) -> Option { + let mut queues = QUEUES.lock().unwrap(); + let id = queues.active_id(raw)?; + queues.begin_retiring(id).then_some(id) +} + +#[allow(dead_code)] // Stage B API: wired to queue Release in a later unit. +pub(super) fn mark_queue_retirement(id: QueueId, mark: QueueRetirementMark) -> Result<(), QueueRetirementMark> { + let result = { + let mut queues = QUEUES.lock().unwrap(); + queues.mark_retiring(id, mark) + }; + result +} + +#[allow(dead_code)] // Stage B API: wired to queue Release in a later unit. +pub(super) fn fail_queue_retirement(id: QueueId) -> bool { + QUEUES.lock().unwrap().fail_retiring(id) +} + +#[allow(dead_code)] // Stage B API: completion is checked and owners are released in a later unit. +pub(super) fn queue_retirement_marks() -> Vec<(QueueId, QueueRetirementMark)> { + QUEUES.lock().unwrap().retirement_marks() +} + +#[allow(dead_code)] // Stage B API: returned owners must be dropped after this function unlocks. +pub(super) fn sweep_queue_retirements(completed: &[QueueId]) -> Vec { + let retired = { + let mut queues = QUEUES.lock().unwrap(); + queues.sweep(completed) + }; + retired.into_iter().map(|(owner, _mark)| owner).collect() +} + static EXECUTES: AtomicU64 = AtomicU64::new(0); /// (PresentX calls, ExecuteCommandLists calls) so far @@ -334,7 +473,7 @@ pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) { EXECUTES.fetch_add(1, Ordering::Relaxed); { let mut queues = QUEUES.lock().unwrap(); - queues.ensure_with(queue as usize, || ID3D12CommandQueue::from_raw_borrowed(&queue).cloned()); + let _ = queues.ensure_with(queue as usize, || ID3D12CommandQueue::from_raw_borrowed(&queue).cloned()); } super::late_release::drain_known(false); if !enabled() || IN_PRESENT.with(|c| c.get()) || PRESENTX.load(Ordering::Relaxed) { @@ -1502,10 +1641,10 @@ mod tests { #[test] fn owned_queue_registry_deduplicates_without_making_a_temporary_owner() { - let mut registry = OwnedQueues::new(); - assert!(registry.ensure_with(0xA, || Some(std::sync::Arc::new(1)))); - assert!(!registry.ensure_with(0xA, || -> Option> { panic!("duplicate owner was made") })); - assert!(registry.ensure_with(0xB, || Some(std::sync::Arc::new(2)))); + let mut registry: OwnedQueues, ()> = OwnedQueues::new(); + assert!(registry.ensure_with(0xA, || Some(std::sync::Arc::new(1))).is_some()); + assert!(registry.ensure_with(0xA, || -> Option> { panic!("duplicate owner was made") }).is_none()); + assert!(registry.ensure_with(0xB, || Some(std::sync::Arc::new(2))).is_some()); let values: Vec<_> = registry.snapshot().iter().map(|v| **v).collect(); assert_eq!(values, [1, 2]); } @@ -1514,8 +1653,8 @@ mod tests { fn owned_queue_snapshot_has_its_own_lifetime() { let owner = std::sync::Arc::new(()); let weak = std::sync::Arc::downgrade(&owner); - let mut registry = OwnedQueues::new(); - assert!(registry.ensure_with(0xA, || Some(owner))); + let mut registry: OwnedQueues, ()> = OwnedQueues::new(); + assert!(registry.ensure_with(0xA, || Some(owner)).is_some()); let snapshot = registry.snapshot(); drop(registry); assert!(weak.upgrade().is_some(), "the snapshot did not keep its owner alive"); @@ -1523,6 +1662,54 @@ mod tests { assert!(weak.upgrade().is_none(), "the caller did not release its snapshot owner"); } + #[test] + fn retiring_queue_stays_in_snapshots_until_its_mark_completes() { + let mut registry: OwnedQueues, u64> = OwnedQueues::new(); + let owner = std::sync::Arc::new(1); + let weak = std::sync::Arc::downgrade(&owner); + let id = registry.ensure_with(0xA, || Some(owner)).unwrap(); + assert!(registry.begin_retiring(id)); + assert_eq!(registry.snapshot().iter().map(|v| **v).collect::>(), [1]); + assert!(registry.retirement_marks().is_empty()); + assert!(registry.sweep(&[id]).is_empty(), "Preparing must remain pinned"); + assert!(registry.mark_retiring(id, 7).is_ok()); + assert_eq!(registry.retirement_marks(), [(id, 7)]); + assert!(registry.sweep(&[]).is_empty()); + assert_eq!(registry.snapshot().iter().map(|v| **v).collect::>(), [1]); + let gone = registry.sweep(&[id]); + assert_eq!(gone.iter().map(|(owner, mark)| (**owner, *mark)).collect::>(), [(1, 7)]); + assert!(registry.snapshot().is_empty()); + assert!(weak.upgrade().is_some(), "sweep dropped an owner instead of returning it"); + drop(gone); + assert!(weak.upgrade().is_none(), "the returned owner was not released by its caller"); + } + + #[test] + fn failed_retirement_is_permanently_pinned() { + let mut registry: OwnedQueues, u64> = OwnedQueues::new(); + let id = registry.ensure_with(0xA, || Some(std::sync::Arc::new(1))).unwrap(); + assert!(registry.begin_retiring(id)); + assert!(registry.fail_retiring(id)); + assert_eq!(registry.mark_retiring(id, 1), Err(1), "an uninstalled mark must be returned"); + assert!(!registry.begin_retiring(id)); + assert!(registry.retirement_marks().is_empty()); + assert!(registry.sweep(&[id]).is_empty()); + assert_eq!(registry.snapshot().iter().map(|v| **v).collect::>(), [1]); + } + + #[test] + fn reused_raw_queue_gets_a_new_generation() { + let mut registry: OwnedQueues, u64> = OwnedQueues::new(); + let old = registry.ensure_with(0xA, || Some(std::sync::Arc::new(1))).unwrap(); + assert!(registry.begin_retiring(old)); + assert!(registry.mark_retiring(old, 1).is_ok()); + drop(registry.sweep(&[old])); + let new = registry.ensure_with(0xA, || Some(std::sync::Arc::new(2))).unwrap(); + assert_ne!(old, new); + assert!(!registry.begin_retiring(old), "a stale generation matched the reused address"); + assert!(registry.begin_retiring(new)); + } + #[test] fn present_ring_overlaps_previous_frame_and_drains_cleanly() { let mut ring = PresentRing::new(PRESENT_SLOTS); From deb5fccf2afa0774c3a0dc1a19377e6bcc51fbe8 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:07:18 -0800 Subject: [PATCH 075/265] D3D12.X: memoize whole split-pipeline failures Retain deterministic whole-form build failures per exact immutable dispatch chain so repeated Dispatch and ExecuteIndirect calls do not re-enter the driver. Preserve success memoization and cap repeated ExecuteIndirect warnings. Treat E_OUTOFMEMORY as transient: suppress attempts for ten seconds, then serialize one retry and retain success. Recreating the chain receives a fresh outcome. Adapted from #2629. Locally cross-checked with the GNU Windows target; Windows execution and GPU smoke remain untested here. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 5 +- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 85 ++++++++++++++++--- 2 files changed, 77 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index d38a565993..ea4a481462 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -362,7 +362,10 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us Ok(Some(whole)) => list.SetPipelineState(&whole), Ok(None) => {} Err(e) => { - crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); + } count(DISPATCHES_SKIPPED); return; } diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 6fa76b4cbf..d7c0b603a3 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -39,32 +39,67 @@ struct PipelineBuilder { } impl PipelineBuilder { - unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Option { + unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Result { let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; let mut raw = std::ptr::null_mut(); let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), dxil, self.record, iid, &mut raw, ComputeBuild::Chain); - (hr >= 0 && !raw.is_null()).then(|| ID3D12PipelineState::from_raw(raw)) + if hr >= 0 && !raw.is_null() { Ok(ID3D12PipelineState::from_raw(raw)) } else { Err(hr) } } } +/// One exact chain's whole-form outcome. The owning `Chain` fixes device, DXIL, root signature, +/// flags and node; releasing/recreating the pipeline gets a fresh outcome. +struct WholeBuild { + result: OnceLock>, + retry_at: Mutex>, +} + +impl WholeBuild { + fn new() -> Self { + Self { result: OnceLock::new(), retry_at: Mutex::new(None) } + } + + fn get_or_build(&self, now: std::time::Instant, build: impl FnOnce() -> Result) -> Result { + if let Some(result) = self.result.get() { + return result.clone(); + } + let mut retry_at = self.retry_at.lock().unwrap(); + if let Some(result) = self.result.get() { + return result.clone(); + } + if retry_at.is_some_and(|at| now < at) { + return Err(crate::util::E_OUTOFMEMORY); + } + match build() { + Err(hr) if hr == crate::util::E_OUTOFMEMORY => { + *retry_at = Some(now + WHOLE_RETRY); + Err(hr) + } + result => { + let _ = self.result.set(result.clone()); + result + } + } + } +} + +/// A transient whole-form OOM is retried after memory has had time to drain. +const WHOLE_RETRY: std::time::Duration = std::time::Duration::from_secs(10); + struct Chain { builder: Arc, tail: Vec, words: u32, whole_code: Vec, - whole: OnceLock, - build_whole: Mutex<()>, + whole: WholeBuild, } impl Chain { unsafe fn whole(&self) -> Result { - if let Some(p) = self.whole.get() { return Ok(p.clone()); } - let _guard = self.build_whole.lock().unwrap(); - if let Some(p) = self.whole.get() { return Ok(p.clone()); } - let p = self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)).ok_or("whole compute pipeline")?; - let _ = self.whole.set(p.clone()); - Ok(p) + self.whole + .get_or_build(std::time::Instant::now(), || self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState))) + .map_err(|hr| if hr == crate::util::E_OUTOFMEMORY { "whole compute pipeline: out of memory".into() } else { format!("whole compute pipeline ({hr:#x})") }) } } @@ -91,7 +126,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let mut pieces = built.into_iter().collect::>>()?.into_iter(); let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, - whole_code: whole.to_vec(), whole: OnceLock::new(), build_whole: Mutex::new(()) }); + whole_code: whole.to_vec(), whole: WholeBuild::new() }); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -235,7 +270,7 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, #[cfg(test)] mod tests { - use super::{scratch_bytes, LEAST}; + use super::*; const MB: u64 = 1 << 20; @@ -284,4 +319,30 @@ mod tests { assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, None, 400 * MB, 384 * MB), (9 * MB, true)); assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, Some(MB), 400 * MB, 384 * MB), (9 * MB, true)); } + + #[test] + fn a_non_oom_whole_failure_is_final_only_for_that_chain() { + let at = std::time::Instant::now(); + let whole: WholeBuild = WholeBuild::new(); + let mut calls = 0; + assert_eq!(whole.get_or_build(at, || { calls += 1; Err(crate::util::E_FAIL) }), Err(crate::util::E_FAIL)); + assert_eq!(whole.get_or_build(at + WHOLE_RETRY, || { calls += 1; Ok(7) }), Err(crate::util::E_FAIL)); + assert_eq!(calls, 1, "the same immutable chain does not repeat a deterministic driver failure"); + + let rebuilt: WholeBuild = WholeBuild::new(); + assert_eq!(rebuilt.get_or_build(at, || Ok(7)), Ok(7), "a new chain after policy/cache changes still builds"); + } + + #[test] + fn a_whole_oom_is_throttled_then_retried() { + let at = std::time::Instant::now(); + let whole: WholeBuild = WholeBuild::new(); + let mut calls = 0; + assert_eq!(whole.get_or_build(at, || { calls += 1; Err(crate::util::E_OUTOFMEMORY) }), Err(crate::util::E_OUTOFMEMORY)); + assert_eq!(whole.get_or_build(at + WHOLE_RETRY / 2, || { calls += 1; Ok(7) }), Err(crate::util::E_OUTOFMEMORY)); + assert_eq!(calls, 1, "calls during the cooldown do not enter the driver"); + assert_eq!(whole.get_or_build(at + WHOLE_RETRY, || { calls += 1; Ok(7) }), Ok(7)); + assert_eq!(whole.get_or_build(at + WHOLE_RETRY * 2, || { calls += 1; Ok(8) }), Ok(7)); + assert_eq!(calls, 2, "the successful retry is retained"); + } } From 80bb4516c5bf55bb9c282babc6bc12c6668cd750 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:07:40 -0800 Subject: [PATCH 076/265] D3D12.X: default AMD driver-blob persistence off Record the selected runtime or precompile adapter vendor and conservatively disable persisted driver blobs after AMD is observed. AMD cached-PSO blobs can reference the driver-owned cache instead of containing self-sufficient code. XCL_PSO_DISK_CACHE=1 remains an explicit override; =0 disables persistence everywhere. NVIDIA, Intel, and WARP retain default-on behavior. Adapted from #2577. Locally cross-checked with the GNU Windows target; Windows execution remains untested here. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 2 +- crates/xcl/src/hle/d3d12x/real.rs | 53 ++++++++++++++++++++++++++++--- crates/xcl/src/shaders.rs | 3 +- 3 files changed, 52 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4b8eef90ad..99e3ac7c2d 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,7 @@ xcl inspect D:\Game\game.exe # the game's imports and what XCL has xcl run D:\Game [-- game arguments] # run xcl disasm [--hex] # RDNA2 disassembler (console containers too) xcl shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compile N -xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines # build compute pipelines and save driver blobs for the next run +xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines # build compute pipelines and save driver blobs for the next run (except by default on AMD) xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines --used-only # only the compute pipelines an earlier run of the title used xcl shaders D:\data\shaders.rpf --export-hlsl out --record-hash HEX # exact compute HLSL for investigation xcl shaders D:\data\shaders.rpf --measure-pso HEX --repeat 3 # cold driver PSO timing (cache disabled) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bdcdbf2412..e02da4e197 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -513,6 +513,7 @@ pub fn init() -> Result { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI: {e}"))?; let mut device: Option = None; let mut name = String::new(); + let mut vendor = 0x1414; // WARP is Microsoft's adapter let sel = crate::gpu::adapter::Selector::from_env_or(&cfg.d3d12_adapter); if sel != crate::gpu::adapter::Selector::Warp { let mut list = crate::gpu::adapter::candidates(&factory, &sel); @@ -523,6 +524,7 @@ pub fn init() -> Result { for (adapter, desc) in list { if let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) { device = Some(dev); + vendor = desc.VendorId; name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); break; } @@ -538,6 +540,7 @@ pub fn init() -> Result { d } }; + driver_cache::note_vendor(vendor); if debug { // the debug layer's messages into XCL's log (they otherwise go to a debugger only) if let Ok(q) = device.cast::() { @@ -4535,16 +4538,32 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL /// again. A blob whose build took `KEEP` or longer is written under the hash of its DXIL and /// its flags (`\driver\`) and read when a later run has none in memory; the /// driver refuses the blob of another driver, adapter or root signature (the file is dropped -/// and the program compiled as before). `XCL_PSO_DISK_CACHE=0`: off. +/// and the program compiled as before). Off by default on AMD; `XCL_PSO_DISK_CACHE=1` forces +/// it on, and `XCL_PSO_DISK_CACHE=0` turns it off everywhere. pub(crate) mod driver_cache { use std::path::{Path, PathBuf}; - use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; /// builds shorter than this are not worth a file const KEEP: std::time::Duration = std::time::Duration::from_millis(250); static HITS: AtomicU64 = AtomicU64::new(0); static STALE: AtomicU64 = AtomicU64::new(0); static STORED: AtomicU64 = AtomicU64::new(0); + static REFERENCE_BLOBS: AtomicBool = AtomicBool::new(false); + + /// AMD's cached-PSO blobs name entries in the driver's own cache instead of containing + /// self-sufficient code. They are not safe to carry across runs unless explicitly enabled. + pub fn note_vendor(vendor: u32) { + let references = reference_blob_vendor(vendor); + let was = REFERENCE_BLOBS.fetch_or(references, Ordering::Relaxed); + if references && !was && !enabled() { + crate::xlog_info!("D3D12.X: driver-blob disk cache off on AMD (XCL_PSO_DISK_CACHE=1: force on)"); + } + } + + fn reference_blob_vendor(vendor: u32) -> bool { + vendor == 0x1002 + } /// The file of the pipeline made from `dxil` with `flags`. pub fn name(dxil: &[u8], flags: i32) -> String { @@ -4563,9 +4582,21 @@ pub(crate) mod driver_cache { format!("gfx-{hash:016x}-{bytes:x}.pso") } + fn env_setting() -> Option { + static ON: std::sync::OnceLock> = std::sync::OnceLock::new(); + *ON.get_or_init(|| configured(std::env::var("XCL_PSO_DISK_CACHE").ok().as_deref())) + } + + fn configured(value: Option<&str>) -> Option { + value.map(|v| v.trim() != "0") + } + + fn enabled_with(setting: Option, reference_blobs: bool) -> bool { + setting.unwrap_or(!reference_blobs) + } + fn enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").map_or(true, |v| v.trim() != "0")) + enabled_with(env_setting(), REFERENCE_BLOBS.load(Ordering::Relaxed)) } pub fn path(dxil: &[u8], flags: i32) -> Option { @@ -4681,6 +4712,20 @@ pub(crate) mod driver_cache { assert!(name_for(&[0u8; 0x1234], 2, true).ends_with("-1234-2.chain.pso")); } + #[test] + fn disk_blobs_default_off_only_for_amd_and_can_be_overridden() { + assert!(reference_blob_vendor(0x1002)); + assert!(!reference_blob_vendor(0x10de)); // NVIDIA + assert!(!reference_blob_vendor(0x8086)); // Intel + assert!(!reference_blob_vendor(0x1414)); // WARP + + assert!(!enabled_with(None, true)); + assert!(enabled_with(None, false)); + assert!(enabled_with(configured(Some("1")), true)); + assert!(!enabled_with(configured(Some(" 0 ")), false)); + assert_eq!(configured(None), None); + } + #[test] fn a_kept_blob_is_read_back_and_a_refused_one_is_dropped() { let dir = std::env::temp_dir().join(format!("xcl-driver-cache-test-{}", std::process::id())); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index bfde971f5b..39e49d6a0e 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1416,8 +1416,9 @@ impl Pipelines { unsafe { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; let sel = crate::gpu::adapter::Selector::from_env_or("auto"); - let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?; + crate::hle::d3d12x::real::driver_cache::note_vendor(desc.VendorId); let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1); let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024); Ok(Pipelines { From 2f608f80ae497505c9179a0587213129ba284411 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:13:59 -0300 Subject: [PATCH 077/265] Recompiler: simplify direct-DXIL integer min and max Track conservative signed and unsigned i32 intervals through common SSA forms, then fold min/max identities, absorption, and non-overlapping bounds. This collapses translated clamp and med3 sequences after mem2reg without removing soundness guards for signed masks. Adapted from #2568. Upstream reports 573/573 DXIL validation, direct GPU parity across NVIDIA and AMD, and 133,484 fewer emitted bytes across the corpus. Locally cross-checked only with the GNU Windows target; Windows GPU execution remains untested here. Part of #2508 Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/module/opt.rs | 354 ++++++++++++++++++++++++++ 1 file changed, 354 insertions(+) diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 230a59f9f9..0210f5e74a 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -106,12 +106,195 @@ impl Module { } } + /// Conservative unsigned `[lo, hi]` value range of an `i32` value, up to `depth` steps deep. + fn unsigned_range_i32(&self, v: Value, depth: u8) -> (u32, u32) { + if let Some(c) = self.const_u64(v) { + let k = c as u32; + return (k, k); + } + if depth == 0 { + return (0, u32::MAX); + } + let Value::Inst(j) = v else { return (0, u32::MAX) }; + let d = depth - 1; + match &self.insts[j as usize].op { + Op::Bin(BinOp::And, x, y, 0) => match self.const_u64(*x).or_else(|| self.const_u64(*y)) { + Some(m) => (0, m as u32), + None => (0, u32::MAX), + }, + Op::Bin(BinOp::LShr, _, sh, 0) => match self.const_u64(*sh) { + Some(s) if s < 32 => (0, u32::MAX >> s), + _ => (0, u32::MAX), + }, + Op::Cast(CastOp::ZExt, inner, _) => match self.int_width(self.value_ty(*inner)) { + Some(iw) if iw < 32 => (0, (1u32 << iw) - 1), + _ => (0, u32::MAX), + }, + Op::Select(_, t, f) => { + let (lt, ht) = self.unsigned_range_i32(*t, d); + let (lf, hf) = self.unsigned_range_i32(*f, d); + (lt.min(lf), ht.max(hf)) + } + Op::Call(f, args) if args.len() == 3 && self.funcs[*f as usize].name == "dx.op.binary.i32" => { + match self.const_u64(args[0]) { + Some(39) => { + let (la, ha) = self.unsigned_range_i32(args[1], d); + let (lb, hb) = self.unsigned_range_i32(args[2], d); + (la.max(lb), ha.max(hb)) + } + Some(40) => { + let (la, ha) = self.unsigned_range_i32(args[1], d); + let (lb, hb) = self.unsigned_range_i32(args[2], d); + (la.min(lb), ha.min(hb)) + } + _ => (0, u32::MAX), + } + } + _ => (0, u32::MAX), + } + } + + /// Conservative signed `[lo, hi]` value range of an `i32` value, up to `depth` steps deep. + fn signed_range_i32(&self, v: Value, depth: u8) -> (i32, i32) { + if let Some(c) = self.const_u64(v) { + let k = c as u32 as i32; + return (k, k); + } + if depth == 0 { + return (i32::MIN, i32::MAX); + } + let Value::Inst(j) = v else { return (i32::MIN, i32::MAX) }; + let d = depth - 1; + match &self.insts[j as usize].op { + Op::Bin(BinOp::And, x, y, 0) => match self.const_u64(*x).or_else(|| self.const_u64(*y)) { + Some(m) if (m as u32) <= i32::MAX as u32 => (0, m as u32 as i32), + _ => (i32::MIN, i32::MAX), + }, + Op::Bin(BinOp::LShr, _, sh, 0) => match self.const_u64(*sh) { + Some(s) if (1..32).contains(&s) => (0, (u32::MAX >> s) as i32), + _ => (i32::MIN, i32::MAX), + }, + Op::Bin(BinOp::AShr, _, sh, 0) => match self.const_u64(*sh) { + Some(s) if (1..32).contains(&s) => (i32::MIN >> s, i32::MAX >> s), + _ => (i32::MIN, i32::MAX), + }, + Op::Cast(CastOp::ZExt, inner, _) => match self.int_width(self.value_ty(*inner)) { + Some(iw) if iw < 32 => (0, ((1u32 << iw) - 1) as i32), + _ => (i32::MIN, i32::MAX), + }, + Op::Cast(CastOp::SExt, inner, _) => match self.int_width(self.value_ty(*inner)) { + Some(iw) if (1..32).contains(&iw) => (-(1i32 << (iw - 1)), (1i32 << (iw - 1)) - 1), + _ => (i32::MIN, i32::MAX), + }, + Op::Select(_, t, f) => { + let (lt, ht) = self.signed_range_i32(*t, d); + let (lf, hf) = self.signed_range_i32(*f, d); + (lt.min(lf), ht.max(hf)) + } + Op::Call(f, args) if args.len() == 3 && self.funcs[*f as usize].name == "dx.op.binary.i32" => { + match self.const_u64(args[0]) { + Some(37) => { + let (la, ha) = self.signed_range_i32(args[1], d); + let (lb, hb) = self.signed_range_i32(args[2], d); + (la.max(lb), ha.max(hb)) + } + Some(38) => { + let (la, ha) = self.signed_range_i32(args[1], d); + let (lb, hb) = self.signed_range_i32(args[2], d); + (la.min(lb), ha.min(hb)) + } + _ => (i32::MIN, i32::MAX), + } + } + _ => (i32::MIN, i32::MAX), + } + } + + /// Simplifies `dx.op.binary.i32` integer min/max (`IMax=37`, `IMin=38`, `UMax=39`, `UMin=40`) + /// via operand identity, lattice absorption, and conservative `[lo, hi]` interval bounds. + fn simplify_int_minmax(&self, op_code: u64, a: Value, b: Value) -> Option { + let (is_signed, is_max, dual) = match op_code { + 37 => (true, true, 38u64), + 38 => (true, false, 37u64), + 39 => (false, true, 40u64), + 40 => (false, false, 39u64), + _ => return None, + }; + if a == b { + return Some(a); + } + // Lattice idempotence & absorption: min(min(x,y), x) = min(x,y), min(max(x,y), x) = x, etc. + for (cand, other) in [(a, b), (b, a)] { + if let Value::Inst(j) = cand { + if let Op::Call(f2, a2) = &self.insts[j as usize].op { + if a2.len() == 3 && self.funcs[*f2 as usize].name == "dx.op.binary.i32" { + let inner_op = self.const_u64(a2[0]); + if a2[1] == other || a2[2] == other { + if inner_op == Some(op_code) { + return Some(cand); + } + if inner_op == Some(dual) { + return Some(other); + } + } + } + } + } + } + if is_signed { + let (la, ha) = self.signed_range_i32(a, 4); + let (lb, hb) = self.signed_range_i32(b, 4); + if is_max { + if la >= hb { + return Some(a); + } + if lb >= ha { + return Some(b); + } + } else { + if ha <= lb { + return Some(a); + } + if hb <= la { + return Some(b); + } + } + } else { + let (la, ha) = self.unsigned_range_i32(a, 4); + let (lb, hb) = self.unsigned_range_i32(b, 4); + if is_max { + if la >= hb { + return Some(a); + } + if lb >= ha { + return Some(b); + } + } else { + if ha <= lb { + return Some(a); + } + if hb <= la { + return Some(b); + } + } + } + None + } + /// Cheap algebraic & constant simplification on already-resolved operands. fn simplify_op(&mut self, op: &Op, ty: Ty) -> Option { // Keep 64-bit instructions intact so Int64Ops / Doubles shader flags stay consistent. if matches!(self.types[ty.0 as usize], super::TypeDef::Int(64) | super::TypeDef::Double) { return None; } + if let Op::Call(f, args) = op { + if args.len() == 3 && self.funcs[*f as usize].name == "dx.op.binary.i32" { + if let Some(op_code) = self.const_u64(args[0]) { + return self.simplify_int_minmax(op_code, args[1], args[2]); + } + } + return None; + } match *op { Op::Select(c, t, f) => { if t == f { @@ -1402,3 +1585,174 @@ mod tests { assert!(m.uses_well_formed(&order)); } } + +#[cfg(test)] +mod int_minmax_tests { + use super::*; + use crate::gpu::dxil::{ + kernel::{self, KernelOptions}, + validate, + }; + use crate::gpu::rdna2::encode; + use crate::gpu::recomp::runner; + + #[test] + fn simplify_int_minmax_folds_bounds_absorption_and_clamps() { + let mut m = Module::new(); + m.define_entry("main"); + let entry = m.entry_block(); + let i32t = m.i32(); + let void = m.void(); + let src_ty = m.func_ty(i32t, &[]); + let sink_ty = m.func_ty(void, &[i32t]); + let bin_ty = m.func_ty(i32t, &[i32t, i32t, i32t]); + let src = m.declare("src", src_ty, FnAttrs::NoUnwind); + let sink = m.declare("sink", sink_ty, FnAttrs::NoUnwind); + let bin_fn = m.declare("dx.op.binary.i32", bin_ty, FnAttrs::ReadNone); + m.set_block(entry); + + let x = m.call(src, &[]); + let y = m.call(src, &[]); + let imax = m.i32c(37); + let imin = m.i32c(38); + let umax = m.i32c(39); + let umin = m.i32c(40); + let c0 = m.i32c(0); + let c16 = m.i32c(16); + let c255 = m.i32c(255); + let c100 = m.i32c(100); + let cneg = m.i32c((-10i32) as u32); + let cu_max = m.i32c(u32::MAX); + let ci_min = m.i32c(i32::MIN as u32); + let ci_max = m.i32c(i32::MAX as u32); + let mff = m.i32c(0xFF); + + // 1. Constant folding & identity/absorbing bounds. + let k_umin = m.call(bin_fn, &[umin, c255, c100]); + let k_imax = m.call(bin_fn, &[imax, cneg, c100]); + let umin_zero = m.call(bin_fn, &[umin, x, c0]); + let umax_zero = m.call(bin_fn, &[umax, x, c0]); + let umin_all = m.call(bin_fn, &[umin, x, cu_max]); + let imin_min = m.call(bin_fn, &[imin, x, ci_min]); + let imax_min = m.call(bin_fn, &[imax, x, ci_min]); + let imin_max = m.call(bin_fn, &[imin, x, ci_max]); + + // 2. Lattice idempotence & absorption. + let mxy = m.call(bin_fn, &[umin, x, y]); + let idemp = m.call(bin_fn, &[umin, mxy, x]); + let absorb = m.call(bin_fn, &[umax, mxy, x]); + + // 3. Range-based elision on masked byte (0..=255) and ashr16 (-32768..=32767). + let byte = m.bin(BinOp::And, x, mff); + let byte_imax0 = m.call(bin_fn, &[imax, byte, c0]); + let byte_umin255 = m.call(bin_fn, &[umin, byte, c255]); + let s16 = m.bin(BinOp::AShr, x, c16); + let c_i16_lo = m.i32c((-32768i32) as u32); + let c_i16_hi = m.i32c(32767); + let s16_lo = m.call(bin_fn, &[imax, s16, c_i16_lo]); + let s16_hi = m.call(bin_fn, &[imin, s16_lo, c_i16_hi]); + + // 4. Full 4-op med3_i32(x, 0, 255) collapses to 2 ops: imin(imax(x, 0), 255). + let p = m.call(bin_fn, &[imin, x, c0]); + let q = m.call(bin_fn, &[imax, x, c0]); + let r = m.call(bin_fn, &[imin, q, c255]); + let med = m.call(bin_fn, &[imax, p, r]); + + // 5. Soundness check: signed mask with bit 31 set MUST NOT fold imax(x & 0x8000_00FF, 0). + let m_sign = m.i32c(0x8000_00FF); + let signed_bits = m.bin(BinOp::And, x, m_sign); + let must_stay = m.call(bin_fn, &[imax, signed_bits, c0]); + + for v in [ + k_umin, + k_imax, + umin_zero, + umax_zero, + umin_all, + imin_min, + imax_min, + imin_max, + idemp, + absorb, + byte_imax0, + byte_umin255, + s16_hi, + med, + must_stay, + ] { + m.call(sink, &[v]); + } + m.ret(); + m.optimize(); + + let args: Vec = m.blocks[entry.0 as usize] + .iter() + .filter_map(|&i| match &m.insts[i as usize].op { + Op::Call(f, a) if *f == sink => Some(a[0]), + _ => None, + }) + .collect(); + assert_eq!(args.len(), 15); + assert_eq!(m.const_u64(args[0]), Some(100), "umin(255, 100) -> 100"); + assert_eq!(m.const_u64(args[1]), Some(100), "imax(-10, 100) -> 100"); + assert_eq!(m.const_u64(args[2]), Some(0), "umin(x, 0) -> 0"); + assert_eq!(args[3], x, "umax(x, 0) -> x"); + assert_eq!(args[4], x, "umin(x, u32::MAX) -> x"); + assert_eq!(m.const_u64(args[5]), Some(i32::MIN as u32 as u64), "imin(x, i32::MIN) -> i32::MIN"); + assert_eq!(args[6], x, "imax(x, i32::MIN) -> x"); + assert_eq!(args[7], x, "imin(x, i32::MAX) -> x"); + assert_eq!(args[8], mxy, "umin(umin(x, y), x) -> umin(x, y)"); + assert_eq!(args[9], x, "umax(umin(x, y), x) -> x"); + assert_eq!(args[10], byte, "imax(x & 0xFF, 0) -> x & 0xFF"); + assert_eq!(args[11], byte, "umin(x & 0xFF, 255) -> x & 0xFF"); + assert_eq!(args[12], s16, "clamp(ashr(x, 16), -32768, 32767) -> ashr(x, 16)"); + assert_eq!(args[13], r, "med3_i32(x, 0, 255) collapses to imin(imax(x, 0), 255)"); + assert_eq!(args[14], must_stay, "imax(x & 0x800000FF, 0) must not fold"); + } + + #[test] + fn med3_via_sgpr_bounds_collapses_and_matches_gpu() { + // Real RDNA2 pattern: upper bound loaded into an SGPR (becomes constant only after mem2reg), + // then fed into v_med3_i32 / v_med3_u32 in both bound orders. + let mut code = Vec::new(); + code.extend(encode("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 255)], Some(255)).unwrap()); + code.extend(encode("S_MOV_B32", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 128)], None).unwrap()); // 0 + // v2 = med3_i32(v0, s3=0, s2=255) -> 2 ops (down from 4) + code.extend(encode("V_MED3_I32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 256), ("SRC1", 3), ("SRC2", 2)], None).unwrap()); + // v3 = med3_i32(v0, s2=255, s3=0) -> 2 ops (reversed bounds, down from 4) + code.extend(encode("V_MED3_I32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 256), ("SRC1", 2), ("SRC2", 3)], None).unwrap()); + // v4 = med3_u32(v0, s3=0, s2=255) -> 1 op (umin(v0, 255), down from 4) + code.extend(encode("V_MED3_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 256), ("SRC1", 3), ("SRC2", 2)], None).unwrap()); + // v5 = med3_u32(v0, s3=0, v1) -> 1 op (umin(v0, v1), down from 4) + code.extend(encode("V_MED3_U32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 256), ("SRC1", 3), ("SRC2", 257)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let dxil = kernel::translate(&code, ko).expect("translate sgpr med3"); + validate::validate(&dxil).expect("validate sgpr med3"); + let dis = validate::disassemble(&dxil).expect("disasm sgpr med3"); + let calls = dis.matches("call i32 @dx.op.binary.i32(").count(); + assert_eq!(calls, 6, "expected 6 binary.i32 calls (2+2+1+1, down from 16), got {calls}:\n{dis}"); + + if !matches!(runner::wave32_supported(), Ok(true)) { + runner::skip_test("no wave32"); + return; + } + let v0s: [u32; 10] = [0, 1, 128, 255, 256, 1000, (-1i32) as u32, (-255i32) as u32, i32::MIN as u32, i32::MAX as u32]; + let v1s: [u32; 10] = [10, 0, 200, 100, 300, 50, u32::MAX, 42, 0x8000_0001, 500]; + let mut st = runner::KernelState::default(); + for l in 0..v0s.len() { + st.vgpr[l][0] = v0s[l]; + st.vgpr[l][1] = v1s[l]; + } + let r = runner::run(&dxil, &st, &[]).expect("GPU run sgpr med3"); + for l in 0..v0s.len() { + let (a, b) = (v0s[l], v1s[l]); + let want_clamp_i = (a as i32).clamp(0, 255) as u32; + assert_eq!(r.vgpr[l][2], want_clamp_i, "med3_i32(v0, 0, 255) lane {l}"); + assert_eq!(r.vgpr[l][3], want_clamp_i, "med3_i32(v0, 255, 0) lane {l}"); + assert_eq!(r.vgpr[l][4], a.min(255), "med3_u32(v0, 0, 255) lane {l}"); + assert_eq!(r.vgpr[l][5], a.min(b), "med3_u32(v0, 0, v1) lane {l}"); + } + } +} From 3e41723247a282f8fde00447dfc9dd2847dfb98f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:00:54 -0300 Subject: [PATCH 078/265] Recompiler: keep VALU carry arithmetic in i32 Lower add/subtract with carry or borrow using two i32 operations and unsigned comparisons. This removes unnecessary i64 widening and the Int64Ops feature from shaders that otherwise need only 32-bit arithmetic. Adapted from #2565. Upstream reports 573/573 DXIL validation and direct GPU parity across NVIDIA and AMD. Locally cross-checked only with the GNU Windows target; Windows GPU execution remains untested here. Part of #2508 Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/lower_valu.rs | 126 ++++++++++++++++++++++++-- 1 file changed, 118 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index 08e15a5580..7ac2b436f6 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -1040,16 +1040,19 @@ impl Lw { let cb = self.lane_of(l, h); let cin = self.u(cb); let (x, y) = if name == "v_subrev_co_ci_u32" { (b, a) } else { (a, b) }; - let (x6, y6, c6) = (self.zext64(x), self.zext64(y), self.zext64(cin)); - let w = if name == "v_add_co_ci_u32" { - let s = self.add(x6, y6); - self.add(s, c6) + let (t, carry) = if name == "v_add_co_ci_u32" { + let t0 = self.add(x, y); + let t = self.add(t0, cin); + let c0 = self.cmp(Pred::ULt, t0, x); + let c1 = self.cmp(Pred::ULt, t, t0); + (t, self.lor(c0, c1)) } else { - let s = self.sub(x6, y6); - self.sub(s, c6) + let t0 = self.sub(x, y); + let t = self.sub(t0, cin); + let c0 = self.cmp(Pred::ULt, x, y); + let c1 = self.cmp(Pred::ULt, t0, cin); + (t, self.lor(c0, c1)) }; - let (t, hi) = self.unpack64(w); - let carry = self.nz(hi); let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); self.write_mask(&sdst, carry); self.vwrite(d, &dst, t); @@ -1428,3 +1431,110 @@ impl Lw { } } } + +#[cfg(test)] +mod valu_carry_tests { + use super::super::kernel::{self, KernelOptions}; + use super::super::validate; + use crate::gpu::rdna2::encode; + use crate::gpu::recomp::runner; + + #[test] + fn valu_carry_ops_avoid_i64_and_match_gpu() { + let mut code = Vec::new(); + for &(name, enc, fields) in &[ + // v2 = v0 + v1 + cin(s0), carry -> s2 + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 2u64), ("SDST", 2), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)][..]), + // v3 = v0 - v1 - cin(s0), borrow -> s4 + ("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 3), ("SDST", 4), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)]), + // v4 = v1 - v0 - cin(s0), borrow -> s6 + ("V_SUBREV_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 4), ("SDST", 6), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)]), + ] { + code.extend(encode(name, enc, fields, None).unwrap_or_else(|e| panic!("{name}: {e}"))); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let dxil = kernel::translate(&code, ko).expect("translate valu carry ops"); + validate::validate(&dxil).expect("validate valu carry ops"); + let dis = validate::disassemble(&dxil).expect("disasm valu carry ops"); + assert!(!dis.contains("64-Bit integer"), "32-bit VALU carry ops must not require Int64Ops:\n{dis}"); + assert!(!dis.contains("zext i32"), "32-bit VALU carry ops must not widen to i64:\n{dis}"); + + if !matches!(runner::wave32_supported(), Ok(true)) { + runner::skip_test("no wave32"); + return; + } + // Boundary triples (x, y, cin) covering overflow/underflow with and without carry/borrow-in. + let cases: [(u32, u32, bool); 32] = [ + (0, 0, false), + (0, 0, true), + (0, 1, false), + (0, 1, true), + (1, 0, false), + (1, 0, true), + (1, 1, false), + (1, 1, true), + (u32::MAX, 0, false), + (u32::MAX, 0, true), + (u32::MAX, 1, false), + (u32::MAX, 1, true), + (0, u32::MAX, false), + (0, u32::MAX, true), + (u32::MAX, u32::MAX, false), + (u32::MAX, u32::MAX, true), + (u32::MAX - 1, 1, false), + (u32::MAX - 1, 1, true), + (0x7FFF_FFFF, 0x8000_0000, false), + (0x7FFF_FFFF, 0x8000_0000, true), + (0x8000_0000, 0x8000_0000, false), + (0x8000_0000, 0x8000_0000, true), + (0x8000_0000, 0x7FFF_FFFF, false), + (0x8000_0000, 0x7FFF_FFFF, true), + (2, 1, false), + (2, 1, true), + (1, 2, false), + (1, 2, true), + (0x1234_5678, 0xEDCB_A987, false), + (0x1234_5678, 0xEDCB_A987, true), + (0x1234_5678, 0xEDCB_A988, false), + (0x1234_5678, 0xEDCB_A988, true), + ]; + let mut st = runner::KernelState::default(); + let mut cin_mask = 0u32; + for (l, &(x, y, cin)) in cases.iter().enumerate() { + st.vgpr[l][0] = x; + st.vgpr[l][1] = y; + if cin { + cin_mask |= 1u32 << l; + } + } + st.sgpr[0] = cin_mask; + let r = runner::run(&dxil, &st, &[]).expect("GPU run valu carry ops"); + + let mut want_add_c = 0u32; + let mut want_sub_b = 0u32; + let mut want_subrev_b = 0u32; + for (l, &(x, y, cin)) in cases.iter().enumerate() { + let c = cin as u64; + let add64 = x as u64 + y as u64 + c; + assert_eq!(r.vgpr[l][2], add64 as u32, "add_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (add64 >> 32) != 0 { + want_add_c |= 1u32 << l; + } + let sub64 = (x as u64).wrapping_sub(y as u64).wrapping_sub(c); + assert_eq!(r.vgpr[l][3], sub64 as u32, "sub_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (sub64 >> 32) != 0 { + want_sub_b |= 1u32 << l; + } + let subrev64 = (y as u64).wrapping_sub(x as u64).wrapping_sub(c); + assert_eq!(r.vgpr[l][4], subrev64 as u32, "subrev_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (subrev64 >> 32) != 0 { + want_subrev_b |= 1u32 << l; + } + } + assert_eq!(r.sgpr[2], want_add_c, "add_co_ci carry-out mask"); + assert_eq!(r.sgpr[4], want_sub_b, "sub_co_ci borrow-out mask"); + assert_eq!(r.sgpr[6], want_subrev_b, "subrev_co_ci borrow-out mask"); + } +} From 4db26aec97060054460d86b3ee986ba557c105b0 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 19:55:07 -0300 Subject: [PATCH 079/265] Recompiler: simplify direct-DXIL bit masks and signed ffbh Build bitfield masks with wrapping shift/subtract identities, fold constant 64-bit scalar masks into i32 halves, and lower signed find-first-bit-high directly to FirstbitSHi. This removes branches, selects, and avoidable Int64Ops. Adapted from #2559. Upstream reports 573/573 DXIL validation and GPU parity across NVIDIA and AMD. Locally cross-checked only with the GNU Windows target; Windows GPU execution remains untested here. Part of #2508 Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/lower.rs | 189 ++++++++++++++++++++++++++----- 1 file changed, 161 insertions(+), 28 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 5034d31903..31d70ab897 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -1703,20 +1703,20 @@ impl Lw { } "s_bfm_b64" => { nz = false; - let wdt = self.andc(al, 63); - let off = self.andc(bl, 63); - let all = self.c64(u64::MAX); - let k64 = self.c(64); - let sh = self.sub(k64, wdt); - let sh = self.andc(sh, 63); - let sh = self.zext64(sh); - let m = self.bin(BinOp::LShr, all, sh); - let wz = self.cmpc(Pred::Eq, wdt, 0); - let z64 = self.c64(0); - let m = self.sel(wz, z64, m); - let off = self.zext64(off); - let r = self.bin(BinOp::Shl, m, off); - self.unpack64(r) + if let (Some(av), Some(bv)) = (self.s.m.const_u64(al), self.s.m.const_u64(bl)) { + let r = ((1u64 << (av & 63)).wrapping_sub(1)) << (bv & 63); + (self.c(r as u32), self.c((r >> 32) as u32)) + } else { + let wdt = self.andc(al, 63); + let off = self.andc(bl, 63); + let one = self.c64(1); + let w64 = self.zext64(wdt); + let bit = self.bin(BinOp::Shl, one, w64); + let m = self.sub(bit, one); + let o64 = self.zext64(off); + let r = self.bin(BinOp::Shl, m, o64); + self.unpack64(r) + } } "s_bfe_u64" | "s_bfe_i64" => { let v = self.pack64(al, ah); @@ -1804,22 +1804,22 @@ impl Lw { self.trunc32(h) } pub fn bfm(&mut self, a: Value, b: Value) -> Value { - let w = self.andc(a, 31); - let wz = self.cmpc(Pred::Eq, w, 0); - let k = self.c(32); - let s = self.sub(k, w); - let s = self.andc(s, 31); - let all = self.c(u32::MAX); - let m = self.bin(BinOp::LShr, all, s); - let m = self.selc(wz, 0, m); - self.shl(m, b) + let m = if let Some(av) = self.s.m.const_u64(a) { + self.c((1u32 << (av & 31)).wrapping_sub(1)) + } else { + let w = self.andc(a, 31); + let one = self.c(1); + let bit = self.bin(BinOp::Shl, one, w); + self.sub(bit, one) + }; + if let (Some(mv), Some(bv)) = (self.s.m.const_u64(m), self.s.m.const_u64(b)) { + self.c((mv as u32) << (bv & 31)) + } else { + self.shl(m, b) + } } pub fn ffbh_i(&mut self, v: Value) -> Value { - let z = self.c(0); - let neg = self.cmp(Pred::SLt, v, z); - let n = self.not(v); - let x = self.sel(neg, n, v); - self.lzcnt(x) + self.s.bit_count(BitCount::FirstbitSHi, v) } pub fn sbfe_u(&mut self, v: Value, c: Value) -> Value { let o = self.andc(c, 31); @@ -2194,3 +2194,136 @@ mod saveexec_tests { assert_eq!(r.scc, 1, "SCC = (final EXEC_LO != 0)"); } } + +#[cfg(test)] +mod bfm_ffbh_tests { + use super::super::kernel::{self, KernelOptions}; + use super::super::validate; + use crate::gpu::rdna2::encode; + use crate::gpu::recomp::runner; + + fn prog(insns: &[(&str, &str, &[(&str, u64)])]) -> Vec { + let mut code = Vec::new(); + for &(name, enc, fields) in insns { + code.extend(encode(name, enc, fields, None).unwrap_or_else(|e| panic!("{name}: {e}"))); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + code + } + + #[test] + fn bfm_and_ffbh_i_ir_and_gpu_parity() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + + // 1. Constant S_BFM_B64 folds with zero i64 ops and zero Int64Ops flag. + // Inline integers: 128 + k (k in 0..=64) => 160 = 32, 144 = 16, 128 = 0. + let const_bfm64 = prog(&[ + ("S_BFM_B64", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 160), ("SSRC1", 144)]), + ("S_BFM_B64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 128), ("SSRC1", 144)]), + ]); + let dxil_const64 = kernel::translate(&const_bfm64, ko).expect("translate const s_bfm_b64"); + validate::validate(&dxil_const64).expect("validate const s_bfm_b64"); + let dis_const64 = validate::disassemble(&dxil_const64).expect("disasm const s_bfm_b64"); + assert!(!dis_const64.contains("64-Bit integer"), "const s_bfm_b64 must not require Int64Ops:\n{dis_const64}"); + + // 2. V_FFBH_I32 / S_FLBIT_I32 lower directly to dx.op.unaryBits.i32(34, ...) (FirstbitSHi). + let ffbh_code = prog(&[ + ("V_FFBH_I32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 256)]), + ("S_FLBIT_I32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 0)]), + ]); + let dxil_ffbh = kernel::translate(&ffbh_code, ko).expect("translate ffbh_i"); + validate::validate(&dxil_ffbh).expect("validate ffbh_i"); + let dis_ffbh = validate::disassemble(&dxil_ffbh).expect("disasm ffbh_i"); + assert!(dis_ffbh.contains("call i32 @dx.op.unaryBits.i32(i32 34,"), "ffbh_i must emit FirstbitSHi:\n{dis_ffbh}"); + assert!(!dis_ffbh.contains("icmp slt"), "ffbh_i must not emit manual sign-bit branch/select:\n{dis_ffbh}"); + + // 3. Dynamic V_BFM_B32 / S_BFM_B32 / S_BFM_B64 lower without icmp/select. + let bfm_code = prog(&[ + ("V_BFM_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 256), ("SRC1", 257)]), + ("S_BFM_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 2), ("SSRC1", 3)]), + ("S_BFM_B64", "ENC_SOP2", &[("SDST", 6), ("SSRC0", 2), ("SSRC1", 3)]), + ]); + let dxil_bfm = kernel::translate(&bfm_code, ko).expect("translate dynamic bfm"); + validate::validate(&dxil_bfm).expect("validate dynamic bfm"); + let dis_bfm = validate::disassemble(&dxil_bfm).expect("disasm dynamic bfm"); + assert!(!dis_bfm.contains("select i32"), "bfm must not emit select:\n{dis_bfm}"); + assert!(!dis_bfm.contains("select i64"), "s_bfm_b64 must not emit select:\n{dis_bfm}"); + + // 4. GPU parity across edge cases. + if !matches!(runner::wave32_supported(), Ok(true)) { + runner::skip_test("no wave32"); + return; + } + // Constant s_bfm_b64 GPU check. + let r0 = runner::run(&dxil_const64, &runner::KernelState::default(), &[]).expect("run const s_bfm_b64"); + let want_const64 = ((1u64 << 32) - 1) << 16; + assert_eq!(r0.sgpr[0], want_const64 as u32); + assert_eq!(r0.sgpr[1], (want_const64 >> 32) as u32); + assert_eq!((r0.sgpr[2], r0.sgpr[3]), (0, 0)); + + // V_FFBH_I32 / S_FLBIT_I32 GPU check. + let ffbh_vals: [u32; 12] = [ + 0, + u32::MAX, + 1, + (-2i32) as u32, + 0x7FFF_FFFF, + 0x8000_0000, + 0x0000_0080, + 0xFFFF_FF7F, + 0x0001_0000, + 0xFFFE_FFFF, + 0x4000_0000, + 0xBFFF_FFFF, + ]; + let mut st_f = runner::KernelState::default(); + st_f.sgpr[0] = 0xFFFF_FF7F; + for (l, &v) in ffbh_vals.iter().enumerate() { + st_f.vgpr[l][0] = v; + } + let rf = runner::run(&dxil_ffbh, &st_f, &[]).expect("run ffbh_i"); + let ref_ffbh_i = |v: u32| -> u32 { + let x = if (v as i32) < 0 { !v } else { v }; + if x == 0 { u32::MAX } else { x.leading_zeros() } + }; + for (l, &v) in ffbh_vals.iter().enumerate() { + assert_eq!(rf.vgpr[l][1], ref_ffbh_i(v), "v_ffbh_i32({v:#010x})"); + } + assert_eq!(rf.sgpr[1], ref_ffbh_i(st_f.sgpr[0]), "s_flbit_i32"); + + // Dynamic V_BFM_B32 / S_BFM_B32 / S_BFM_B64 GPU check. + let pairs: [(u32, u32); 12] = [ + (0, 0), + (0, 17), + (1, 0), + (1, 31), + (16, 8), + (31, 0), + (31, 1), + (32, 0), + (35, 33), + (63, 0), + (63, 1), + (64, 15), + ]; + let mut st_b = runner::KernelState::default(); + for (l, &(w, o)) in pairs.iter().enumerate() { + st_b.vgpr[l][0] = w; + st_b.vgpr[l][1] = o; + } + for &(sw, so) in &[(0u32, 16u32), (31, 1), (32, 32), (63, 1), (64, 5)] { + st_b.sgpr[2] = sw; + st_b.sgpr[3] = so; + let rb = runner::run(&dxil_bfm, &st_b, &[]).expect("run bfm"); + for (l, &(w, o)) in pairs.iter().enumerate() { + let want32 = ((1u32 << (w & 31)).wrapping_sub(1)) << (o & 31); + assert_eq!(rb.vgpr[l][2], want32, "v_bfm_b32({w}, {o})"); + } + let want_s32 = ((1u32 << (sw & 31)).wrapping_sub(1)) << (so & 31); + assert_eq!(rb.sgpr[4], want_s32, "s_bfm_b32({sw}, {so})"); + let want_s64 = ((1u64 << (sw & 63)).wrapping_sub(1)) << (so & 63); + assert_eq!(rb.sgpr[6], want_s64 as u32, "s_bfm_b64 lo({sw}, {so})"); + assert_eq!(rb.sgpr[7], (want_s64 >> 32) as u32, "s_bfm_b64 hi({sw}, {so})"); + } + } +} From fba7de2b954ae8da4d09f03758c6f2b802d32781 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:14:04 -0800 Subject: [PATCH 080/265] D3D12.X: invalidate exact driver-cache file generations Retain the Windows file handle used to read each persisted driver blob. If the driver or offline precompiler rejects it, dispose that exact file object rather than a pathname another process may already have replaced. Open entries with read/delete sharing and OPEN_REPARSE_POINT, falling back to read-only and failing closed when exact-object deletion is unavailable. Preserve cache-I/O stall attribution and cover cross-process replacement and link safety. Adapted from #2614. Locally cross-checked with the GNU Windows target; Windows filesystem tests and execution remain untested here. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 178 +++++++++++++++++++++++++----- crates/xcl/src/shaders.rs | 11 +- 2 files changed, 159 insertions(+), 30 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bdcdbf2412..08efc7fb7d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4478,8 +4478,10 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) let disk = driver_cache::path_for(dxil, copy.Flags.0, mode == ComputeBuild::Chain); let from_disk = cached.is_none(); + let mut loaded = None; if from_disk { - cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + loaded = disk.as_deref().and_then(driver_cache::load); + cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); } if let Some(b) = &cached { copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; @@ -4498,7 +4500,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL // a blob the driver does not take (another root signature at the same address…): compiled forget_compute_blob(key); if from_disk { - driver_cache::note(false, disk.as_deref()); + driver_cache::note(false, loaded.take()); } if mode == ComputeBuild::CachedWhole { return (hr, in_driver, false); @@ -4521,7 +4523,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL driver_cache::keep(p, &b, in_driver); } } else if reused && from_disk { - driver_cache::note(true, None); + driver_cache::note(true, loaded.take()); } (hr, in_driver, reused) } @@ -4537,7 +4539,11 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL /// driver refuses the blob of another driver, adapter or root signature (the file is dropped /// and the program compiled as before). `XCL_PSO_DISK_CACHE=0`: off. pub(crate) mod driver_cache { + use std::io::Read; + use std::os::windows::fs::OpenOptionsExt; + use std::os::windows::io::AsRawHandle; use std::path::{Path, PathBuf}; + use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; /// builds shorter than this are not worth a file @@ -4580,22 +4586,77 @@ pub(crate) mod driver_cache { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(graphics_name(hash, bytes))) } - pub fn load(p: &Path) -> Option> { - let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); - std::fs::read(p).ok().filter(|b| !b.is_empty()) + /// Bytes read from one exact cache-file generation. Keeping its handle open lets a later + /// refusal dispose that file object without touching a replacement at the same pathname. + pub struct LoadedBlob { + bytes: Arc>, + /// `None` when the blob was readable but the cache entry could not be opened for deletion. + file: Option, + } + + impl LoadedBlob { + #[cfg(test)] + fn bytes(&self) -> &[u8] { &self.bytes } + pub fn shared(&self) -> Arc> { self.bytes.clone() } + + /// Remove the exact file object that supplied these bytes. If that operation is not + /// available, leave the stale entry rather than remove a pathname that may name another + /// process's newer replacement. + pub fn invalidate(self) -> bool { + use windows_sys::Win32::Storage::FileSystem::{ + FileDispositionInfoEx, SetFileInformationByHandle, + FILE_DISPOSITION_FLAG_DELETE, FILE_DISPOSITION_FLAG_POSIX_SEMANTICS, + FILE_DISPOSITION_INFO_EX, + }; + let Some(file) = self.file else { return false }; + let handle = file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE; + let ex = FILE_DISPOSITION_INFO_EX { Flags: FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS }; + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + unsafe { + SetFileInformationByHandle( + handle, + FileDispositionInfoEx, + (&ex as *const FILE_DISPOSITION_INFO_EX).cast(), + std::mem::size_of::() as u32, + ) != 0 + } + } + } + + pub fn load(p: &Path) -> Option { + use windows_sys::Win32::Foundation::GENERIC_READ; + use windows_sys::Win32::Storage::FileSystem::{ + DELETE, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, + }; + let open = |access| { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::OpenOptions::new() + .read(true) + .access_mode(access) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(p) + }; + let (mut file, invalidatable) = open(GENERIC_READ | DELETE).map(|f| (f, true)) + .or_else(|_| open(GENERIC_READ).map(|f| (f, false))).ok()?; + let mut bytes = Vec::new(); + { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + file.read_to_end(&mut bytes).ok()?; + } + (!bytes.is_empty()).then(|| LoadedBlob { bytes: Arc::new(bytes), file: invalidatable.then_some(file) }) } - /// A pipeline was made from a kept blob (`ok`), or the driver refused the blob: dropped. - pub fn note(ok: bool, p: Option<&Path>) { + /// A pipeline was made from a kept blob (`ok`), or the driver refused that exact blob: dropped. + pub fn note(ok: bool, loaded: Option) { if ok { let n = HITS.fetch_add(1, Ordering::Relaxed) + 1; if n.is_power_of_two() { crate::xlog_info!("D3D12.X: {n} compute pipelines made from the driver's blob of an earlier run (kept on disk)"); } } else { - if let Some(p) = p { - let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); - let _ = std::fs::remove_file(p); + if let Some(loaded) = loaded { + let _ = loaded.invalidate(); } if STALE.fetch_add(1, Ordering::Relaxed) == 0 { crate::xlog_info!("D3D12.X: a driver blob kept on disk was refused (another driver or adapter?) – such pipelines are compiled again"); @@ -4664,6 +4725,10 @@ pub(crate) mod driver_cache { mod tests { use super::*; + fn load_bytes(p: &Path) -> Option> { + load(p).map(|b| b.bytes().to_vec()) + } + struct Directory(PathBuf); impl Drop for Directory { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } @@ -4685,22 +4750,79 @@ pub(crate) mod driver_cache { fn a_kept_blob_is_read_back_and_a_refused_one_is_dropped() { let dir = std::env::temp_dir().join(format!("xcl-driver-cache-test-{}", std::process::id())); let p = dir.join("driver").join(name(b"program", 0)); - assert_eq!(load(&p), None, "nothing kept yet"); + assert_eq!(load_bytes(&p), None, "nothing kept yet"); assert!(!write(&p, &[]), "an empty blob is not kept"); keep(&p, &[1, 2, 3], std::time::Duration::from_millis(10)); - assert_eq!(load(&p), None, "a build of milliseconds is not kept"); + assert_eq!(load_bytes(&p), None, "a build of milliseconds is not kept"); keep(&p, &[1, 2, 3], std::time::Duration::from_secs(1)); - assert_eq!(load(&p).as_deref(), Some(&[1u8, 2, 3][..])); + assert_eq!(load_bytes(&p).as_deref(), Some(&[1u8, 2, 3][..])); // no half file under the temporary name assert_eq!(std::fs::read_dir(p.parent().unwrap()).unwrap().count(), 1); // the driver took the blob: it stays; it refused it: gone, the program is compiled again - note(true, Some(&p)); + note(true, load(&p)); assert!(p.exists()); - note(false, Some(&p)); - assert_eq!(load(&p), None); + note(false, load(&p)); + assert_eq!(load_bytes(&p), None); let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn an_older_process_cannot_remove_a_replacement_blob() { + const CHILD: &str = "XCL_DRIVER_CACHE_REPLACEMENT_CHILD"; + let bytes = b"same bytes in both generations"; + if let Some(path) = std::env::var_os(CHILD) { + assert!(write(&PathBuf::from(path), bytes), "replace the still-open old generation directly"); + return; + } + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-replace-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let p = dir.join("program.pso"); + // Identical bytes make pathname/content comparisons unable to distinguish the two + // generations: the open file object is the identity that must protect the second. + assert!(write(&p, bytes)); + let delayed_reader = load(&p).unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::real::driver_cache::tests::an_older_process_cannot_remove_a_replacement_blob", "--nocapture"]) + .env(CHILD, &p) + .output() + .unwrap(); + assert!( + output.status.success(), + "replacement process failed:\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!(delayed_reader.invalidate(), "the old generation can be disposed through its handle"); + assert_eq!(load_bytes(&p).as_deref(), Some(bytes.as_slice())); + } + + #[test] + fn a_blob_without_delete_access_fails_closed() { + let loaded = LoadedBlob { bytes: Arc::new(vec![1]), file: None }; + assert!(!loaded.invalidate()); + } + + #[test] + fn a_cache_symlink_never_disposes_its_target() { + use std::os::windows::fs::symlink_file; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-link-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let target = dir.join("outside.pso"); + let link = dir.join("cache.pso"); + std::fs::write(&target, b"not the cache entry").unwrap(); + if symlink_file(&target, &link).is_err() { + return; // creating symlinks can require Developer Mode or an elevated token + } + if let Some(loaded) = load(&link) { + let _ = loaded.invalidate(); + } + assert_eq!(std::fs::read(&target).unwrap(), b"not the cache entry"); + } + #[test] fn an_overlapping_writer_cannot_modify_the_published_blob() { use std::io::Write; @@ -4712,11 +4834,11 @@ pub(crate) mod driver_cache { let (_other_tmp, mut other) = create_staging_file(&p).unwrap(); let complete = b"complete second blob"; assert!(write(&p, complete)); - assert_eq!(load(&p).as_deref(), Some(complete.as_slice())); + assert_eq!(load_bytes(&p).as_deref(), Some(complete.as_slice())); // Resuming the older writer must not change a file already published by this // invocation, even when the older payload is shorter than the newer one. other.write_all(b"old").unwrap(); - assert_eq!(load(&p).as_deref(), Some(complete.as_slice()), "published bytes must not alias another writer's staging file"); + assert_eq!(load_bytes(&p).as_deref(), Some(complete.as_slice()), "published bytes must not alias another writer's staging file"); } #[test] @@ -4735,7 +4857,7 @@ pub(crate) mod driver_cache { file.write_all(b"ours").unwrap(); drop(file); std::fs::rename(&tmp, &p).unwrap(); - assert_eq!(load(&p).as_deref(), Some(b"ours".as_slice())); + assert_eq!(load_bytes(&p).as_deref(), Some(b"ours".as_slice())); assert_eq!(std::fs::read(&occupied).unwrap(), b"not ours"); } } @@ -5322,8 +5444,10 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const let mut cached = graphics_blob(gkey); let disk = driver_cache::graphics_path(gkey.0, gkey.1); let from_disk = cached.is_none(); + let mut loaded = None; if from_disk { - cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + loaded = disk.as_deref().and_then(driver_cache::load); + cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); } let build = create_graphics_pso_cached( &mut copy, @@ -5332,7 +5456,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const || { forget_graphics_blob(gkey); if from_disk { - driver_cache::note(false, disk.as_deref()); + driver_cache::note(false, loaded.take()); } }, |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some((ps_hash, has_cached)), f), @@ -5345,7 +5469,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const driver_cache::keep(p, &b, build.in_driver); } } else if build.reused && from_disk { - driver_cache::note(true, None); + driver_cache::note(true, loaded.take()); } if hr < 0 { note_translation_error(format!( @@ -6088,8 +6212,10 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let mut ccached = compute_blob(ckey); let cdisk = driver_cache::path(&tp.cs, 0); let cfrom_disk = ccached.is_none(); + let mut cloaded = None; if cfrom_disk { - ccached = cdisk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + cloaded = cdisk.as_deref().and_then(driver_cache::load); + ccached = cloaded.as_ref().map(driver_cache::LoadedBlob::shared); } if let Some(b) = &ccached { cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; @@ -6102,7 +6228,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: if hc < 0 && ccached.is_some() { forget_compute_blob(ckey); if cfrom_disk { - driver_cache::note(false, cdisk.as_deref()); + driver_cache::note(false, cloaded.take()); } cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); compute = std::ptr::null_mut(); @@ -6119,7 +6245,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: driver_cache::keep(p, &b, cin_driver); } } else if creused && cfrom_disk { - driver_cache::note(true, None); + driver_cache::note(true, cloaded.take()); } drop(_slot); if hc < 0 || compute.is_null() { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index bfde971f5b..ce062dba53 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1514,7 +1514,8 @@ impl Pipelines { } driver_cache::path_for(dxil, desc.Flags.0, chained) }); - let cached = path.as_deref().and_then(driver_cache::load); + let mut loaded = path.as_deref().and_then(driver_cache::load); + let cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes // tens of minutes and gigabytes; the pass finishes without it, and the runtime builds it @@ -1542,10 +1543,12 @@ impl Pipelines { }); // A stale blob is not a usable cache hit. Do not let its presence bypass the offline // size cap and start the expensive uncached driver compile. - if cached.is_some() && from_cache.is_none() && over_cap { - if let Some(path) = path.as_deref() { - let _ = std::fs::remove_file(path); + if cached.is_some() && from_cache.is_none() { + if let Some(loaded) = loaded.take() { + let _ = loaded.invalidate(); } + } + if cached.is_some() && from_cache.is_none() && over_cap { *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); self.capped.fetch_add(1, Ordering::Relaxed); From 9374675efc54943dd73033b0958b1be73a32f52d Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:16:14 -0800 Subject: [PATCH 081/265] D3D12.X: invalidate retired queue address caches Add an inactive Stage C coordinator that removes every audited raw-command-queue cache only after a future retirement mark completes. Cover allocation, copy scratch, CPU-write, late-release, sparse/VRAM, title-texture, presentation, and synchronization-graph state. Extract COM-bearing values under their subsystem lock and release them only after unlocking. In-flight batches retain independent fence clones, and the retirement registry remains untouched. No overlapping queue-retirement PR was found. Locally cross-checked with the GNU Windows target; Windows execution remains untested here. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 27 ++++++ crates/xcl/src/hle/d3d12x/cpu_writes.rs | 10 ++ crates/xcl/src/hle/d3d12x/late_release.rs | 10 ++ crates/xcl/src/hle/d3d12x/list_x.rs | 100 ++++++++++++++++++++ crates/xcl/src/hle/d3d12x/present.rs | 26 +++++ crates/xcl/src/hle/d3d12x/sparse.rs | 13 +++ crates/xcl/src/hle/d3d12x/title_textures.rs | 6 ++ crates/xcl/src/hle/d3d12x/vram.rs | 41 ++++++++ 8 files changed, 233 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 1eb06682f2..1ffd5bcf6c 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -80,6 +80,33 @@ unsafe impl Send for State {} static STATE: Mutex> = Mutex::new(None); +/// Remove completion caches for a retired queue before its raw address can be reused. This is +/// called only after its retirement mark completes; every removed COM fence drops unlocked. +pub(super) fn forget_queue(id: super::present::QueueId) { + let queue = id.raw(); + let gone = { + let mut state = STATE.lock().unwrap(); + let Some(state) = state.as_mut() else { return }; + let mut gone = Vec::new(); + if let Some((fence, _)) = state.fences.remove(&queue) { + gone.push(fence); + } + for backing in state.backings.values_mut() { + if let Some((fence, _)) = backing.marks.remove(&queue) { + gone.push(fence); + } + } + let lists: Vec<_> = state.last_submit.iter().filter_map(|(&list, submit)| (submit.queue == queue).then_some(list)).collect(); + for list in lists { + if let Some(submit) = state.last_submit.remove(&list) { + gone.push(submit.fence); + } + } + gone + }; + drop(gone); +} + pub(super) fn release_with_probe( add_ref: impl FnOnce(), mut release: impl FnMut() -> u32, diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index d4adeed93a..f9dd01ada3 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -50,6 +50,16 @@ unsafe impl Send for QueueFence {} static FENCES: Mutex>> = Mutex::new(None); +/// Forget a retired queue's cached fence before its address can be reused. Submitted jobs own +/// fence clones, so extracting this entry cannot let their writes run early. +pub(super) fn forget_queue(id: super::present::QueueId) { + let gone = { + let mut fences = FENCES.lock().unwrap(); + fences.as_mut().and_then(|fences| fences.remove(&id.raw())) + }; + drop(gone); +} + /// how long the worker waits for one submission before writing anyway (a removed device, a /// queue that never gets there) const WAIT_MS: u32 = 10_000; diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 864c1693f3..3988302dbf 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -86,6 +86,16 @@ impl Held { static HELD: Mutex> = Mutex::new(None); +/// Remove cached state for a retired queue before its final owner can be released. Sealed +/// batches own their fence clones, so they remain gated. The removed fence drops unlocked. +pub(super) fn forget_queue(id: super::present::QueueId) { + let gone = { + let mut held = HELD.lock().unwrap(); + held.as_mut().and_then(|held| held.fences.remove(&id.raw())) + }; + drop(gone); +} + /// Whether last releases are held (`XCL_LATE_RELEASE=0` turns it off). pub fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 4281d2e13c..095ced0d2d 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1119,6 +1119,46 @@ pub(super) fn on_queue_release(queue: usize) { } } +/// Remove every cached use of a retired raw queue address before it can be reused. This is later +/// than `on_queue_release`: the retirement marker has completed, so old sync edges are finished. +/// Cached COM fences are extracted and dropped after their locks are gone. +pub(super) fn forget_queue(id: super::present::QueueId) { + let queue = id.raw(); + let scratch_fences = { + let mut scratch = COPY_SCRATCH.lock().unwrap(); + let mut gone = Vec::new(); + if let Some((fence, _)) = scratch.fences.remove(&queue) { + gone.push(fence); + } + for allocation in scratch.active.values_mut() { + if let Some((fence, _)) = allocation.marks.remove(&queue) { + gone.push(fence); + } + } + for allocation in &mut scratch.released { + if let Some((fence, _)) = allocation.marks.remove(&queue) { + gone.push(fence); + } + } + gone + }; + drop(scratch_fences); + LIVE_QUEUES.lock().unwrap().retain(|info| info.queue != queue); + if let Some(lists) = LISTS.lock().unwrap().as_mut() { + for state in lists.values_mut() { + if state.last_queue == Some(queue) { + state.last_queue = None; + } + } + } + let removed_waits = SYNC_GRAPH.lock().unwrap().as_mut().map_or(0, |graph| graph.forget_queue(queue)); + if removed_waits != 0 { + ARMED_GPU_WAITS.fetch_sub(removed_waits, Ordering::AcqRel); + } + let internal_waits = INTERNAL_WAITS.lock().unwrap().as_mut().and_then(|waits| waits.remove(&queue)); + drop(internal_waits); +} + #[cfg(test)] thread_local! { /// Optional test interceptor for `try_native_depth_bias` so unit tests deterministically @@ -1507,6 +1547,28 @@ impl SyncGraph { *s += 1; *s } + + fn forget_queue(&mut self, queue: usize) -> usize { + self.queue_seq.remove(&queue); + let mut armed = 0; + for cell in self.cells.values_mut() { + if cell.recorded_last_queue == Some(queue) { + cell.recorded_last_queue = None; + } + if cell.submitted_queue == Some(queue) { + cell.submitted_queue = None; + } + let before = cell.armed_waits.len(); + cell.armed_waits.retain(|wait| wait.waiting_queue != queue); + armed += before - cell.armed_waits.len(); + cell.submitted_signals.retain(|signal| signal.queue != queue); + } + for fence in self.title_fences.values_mut() { + fence.waits.retain(|&(_, waiting_queue, _)| waiting_queue != queue); + fence.signals.retain(|signal| signal.queue != queue); + } + armed + } } static SYNC_GRAPH: Mutex> = Mutex::new(None); @@ -6077,6 +6139,44 @@ mod tests { assert_eq!(pick_queue(None, dev, D3D12_COMMAND_LIST_TYPE_DIRECT), None); } + #[test] + fn sync_graph_forgets_every_reference_to_a_retired_queue() { + let (gone, kept) = (0x9100usize, 0x9200usize); + let mut graph = SyncGraph::default(); + graph.queue_seq.insert(gone, 3); + graph.queue_seq.insert(kept, 4); + let mut cell = SyncCell { recorded_last_queue: Some(gone), submitted_queue: Some(gone), ..Default::default() }; + cell.armed_waits.push(ArmedGpuWait { + val: 1, + waiting_queue: gone, + waiting_queue_ty: 0, + wait_seq: 1, + armed_at: Instant::now(), + after_write64: false, + }); + cell.armed_waits.push(ArmedGpuWait { waiting_queue: kept, ..cell.armed_waits[0] }); + cell.submitted_signals.push(SubmittedSignal { val: 1, queue: gone, seq: 1 }); + cell.submitted_signals.push(SubmittedSignal { val: 2, queue: kept, seq: 2 }); + graph.cells.insert(0x1000, cell); + graph.title_fences.insert( + 0x2000, + TitleFenceSync { + waits: vec![(1, gone, 1), (2, kept, 2)], + signals: vec![SubmittedSignal { val: 1, queue: gone, seq: 1 }, SubmittedSignal { val: 2, queue: kept, seq: 2 }], + }, + ); + + assert_eq!(graph.forget_queue(gone), 1); + assert!(!graph.queue_seq.contains_key(&gone) && graph.queue_seq.contains_key(&kept)); + let cell = &graph.cells[&0x1000]; + assert_eq!((cell.recorded_last_queue, cell.submitted_queue), (None, None)); + assert_eq!(cell.armed_waits.iter().map(|wait| wait.waiting_queue).collect::>(), [kept]); + assert_eq!(cell.submitted_signals.iter().map(|signal| signal.queue).collect::>(), [kept]); + let title = &graph.title_fences[&0x2000]; + assert_eq!(title.waits.iter().map(|&(_, queue, _)| queue).collect::>(), [kept]); + assert_eq!(title.signals.iter().map(|signal| signal.queue).collect::>(), [kept]); + } + #[test] fn depth_bias_state_tracks_fallback_and_clear() { let l = 0x9000_0001usize as *mut c_void; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 883ce4eadc..c8cca7b7c9 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -462,6 +462,32 @@ pub(super) fn sweep_queue_retirements(completed: &[QueueId]) -> Vec> = Mutex::new(None); /// (a list's `Reset`, with `XCL_DRED=1` on every start): the two then waited for each other. static QUEUE: Mutex> = Mutex::new(None); +/// Remove raw queue-address state before a retired queue's final owner is released. Retired tile +/// batches own fence clones independently; the cached queue and fence drop after unlocking. +pub(super) fn forget_queue(id: super::present::QueueId) { + let gone = { + let mut state = STATE.lock().unwrap(); + state.as_mut().and_then(|state| { + state.waited.remove(&id.raw()); + state.queue_fences.remove(&id.raw()) + }) + }; + drop(gone); +} + /// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY` pub fn pool_bytes() -> (usize, usize) { let g = lock_state(); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d44a31152d..d4cb78d172 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1098,6 +1098,12 @@ unsafe impl Send for QueueUploads {} static ON_QUEUE: Mutex> = Mutex::new(BTreeMap::new()); +/// Drop completed uploads cached for a retired title queue after releasing the cache lock. +pub(super) fn forget_queue(id: super::present::QueueId) { + let gone = ON_QUEUE.lock().unwrap().remove(&id.raw()); + drop(gone); +} + const IN_FLIGHT_BYTES: u64 = 512 << 20; unsafe fn title_queue_for(dev: &ID3D12Device, title: Option<&ID3D12CommandQueue>) -> Option { diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index a58d38acbb..ec6c2c1d7a 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1143,6 +1143,11 @@ impl RetireQueue { let pruned = stale.into_iter().filter_map(|k| self.fences.remove(&k).map(|(f, _)| f)).collect(); (done, pruned) } + + /// In-flight batches own their marks; only the address-keyed reusable fence is removed. + fn forget_queue(&mut self, queue: usize) -> Option { + self.fences.remove(&queue).map(|(fence, _)| fence) + } } unsafe impl Send for RetireQueue {} @@ -1150,6 +1155,28 @@ unsafe impl Send for RetireQueue {} static RETIRE: Mutex>>> = Mutex::new(None); static RETIRING_BATCHES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// Remove raw queue-address state before a retired queue's final owner can be released. Fence +/// objects are extracted from both locks and dropped afterward; retirement batches keep clones. +pub(super) fn forget_queue(id: super::present::QueueId) { + let queue = id.raw(); + { + let mut pages = PAGES.lock().unwrap(); + for pages in pages.values_mut().flatten() { + pages.waited.remove(&queue); + } + } + let gone = { + let mut retire = RETIRE.lock().unwrap(); + retire + .as_mut() + .into_iter() + .flat_map(|devices| devices.values_mut()) + .filter_map(|queues| queues.forget_queue(queue)) + .collect::>() + }; + drop(gone); +} + /// Collect all known live command queues belonging to `dev_key` (deduplicated by raw ptr). unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueue>) -> Vec<(usize, ID3D12CommandQueue)> { let (mut seen, mut out) = (HashSet::new(), Vec::new()); @@ -1713,6 +1740,20 @@ mod tests { assert_eq!(rq.retire_with(vec![303], None, &[] as &[(usize, usize)], mk, |_, _, _| true), vec![303]); } + #[test] + fn forgetting_queue_cache_preserves_inflight_batch_marks() { + use std::sync::{atomic::AtomicU64, Arc}; + let mut rq = RetireQueue::>::new(); + assert!(rq + .retire_with(vec![101], None, &[(7, 7usize)], || Some(Arc::new(AtomicU64::new(0))), |_, _, _| true) + .is_empty()); + let cached = rq.fences[&7].0.clone(); + let gone = rq.forget_queue(7).expect("cached queue fence"); + assert!(Arc::ptr_eq(&gone, &cached) && !rq.fences.contains_key(&7)); + assert_eq!(rq.batches.len(), 1); + assert!(Arc::strong_count(&cached) >= 3, "the in-flight batch lost its own fence clone"); + } + #[test] fn gpu_retire_queue_holds_heap_until_blocked_queue_passes_mark() { let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); From 0aa153537dd6aadf99584427508db1d68308cbb7 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:19:52 -0800 Subject: [PATCH 082/265] Recompiler: make heap-window load and store guards branchless Reserve null raw-UAV descriptors after the memory-window slots. Redirect ordinary out-of-layout loads and stores with a descriptor select, while retaining explicit guards for atomics whose return values require defined handling. Keep runtime and GPU-test heaps on the same descriptor ABI and add a deterministic accessor-shape test. Adapted as the behavior-independent half of #2554; its upstream RTX 4090 investigation attributes about six seconds of a large cold compile to the duplicated guard branches. Locally cross-checked with the GNU Windows target; Windows GPU execution remains untested here. Assisted-by: Claude Code (model not disclosed) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/emit.rs | 41 ++++++++++++++++++----- crates/xcl/src/gpu/recomp/mod.rs | 5 +++ crates/xcl/src/gpu/recomp/runner.rs | 14 ++++++-- crates/xcl/src/hle/d3d12x/console_heap.rs | 23 ++++++++++--- 4 files changed, 69 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 2f817a809f..ee2acf3647 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5831,15 +5831,28 @@ fn method_switch(windows: u32, w: &str, ret: &str, name: &str, args: &str, def: fn mem_accessors(windows: u32, heap: Option<&str>) -> String { let mut s = String::new(); if let Some(coherent) = heap { - // one access: window k is descriptor MEM_HEAP_BASE + k; an `xcl_w` outside the windows - // does what the switch's `default` does + // Redirect ordinary out-of-window loads/stores to null raw UAVs without a divergent + // branch. Atomics keep the guard because their out parameter must be set to zero. + let buf = |nul: u32| format!( + "{{ bool xcl_o = xcl_w >= {windows}u; {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex(select(xcl_o, {nul}u, {}u + xcl_w))]; ", + super::MEM_HEAP_BASE + ); let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + xcl_w)]", super::MEM_HEAP_BASE); - let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] if (xcl_w >= {windows}u) {{ return uint4(0u, 0u, 0u, 0u); }} XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}"); + let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {}return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}", buf(super::MEM_NULL_LOAD)); for (ret, name, params, args, def) in mem_methods() { - let r = if ret == "void" { "" } else { "return " }; - // (the switch's `break` leaves the accessor) - let outside = def.replace("break;", "return;"); - let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ [branch] if (xcl_w >= {windows}u) {{ {outside} }} XCL_MW; {r}m.{name}({args}); }}"); + if name.starts_with("Load") || name.starts_with("Store") { + let nul = if name.starts_with("Store") { super::MEM_NULL_STORE } else { super::MEM_NULL_LOAD }; + let call = if name.starts_with("Store") { + format!("m.{name}(a, {});", &args[3..]) + } else { + format!("return m.{name}(a);") + }; + let _ = writeln!(s, "{ret} xcl_m{name}({params}) {}{}}}", buf(nul), call); + } else { + let r = if ret == "void" { "" } else { "return " }; + let outside = def.replace("break;", "return;"); + let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ [branch] if (xcl_w >= {windows}u) {{ {outside} }} XCL_MW; {r}m.{name}({args}); }}"); + } } return s; } @@ -6718,7 +6731,19 @@ uint fclass64(double f) { #[cfg(test)] mod tests { - use super::{PRELUDE, PRELUDE_MEM}; + use super::{mem_accessors, PRELUDE, PRELUDE_MEM}; + + #[test] + fn heap_window_loads_and_stores_use_null_descriptors_without_branches() { + let h = mem_accessors(4, Some("globallycoherent ")); + let load = format!("select(xcl_o, {}u,", super::super::MEM_NULL_LOAD); + let store = format!("select(xcl_o, {}u,", super::super::MEM_NULL_STORE); + assert!(h.contains(&load), "load accessor did not select the null-load UAV:\n{h}"); + assert!(h.contains(&store), "store accessor did not select the null-store UAV:\n{h}"); + assert!(h.contains("xcl_mInterlockedAdd(uint a, uint v, out uint o) { [branch] if"), "atomic guard was removed:\n{h}"); + assert!(!h.contains("xcl_mLoad(uint a) { [branch]"), "ordinary load kept a divergent guard:\n{h}"); + assert!(!h.contains("xcl_mStore(uint a, uint v) { [branch]"), "ordinary store kept a divergent guard:\n{h}"); + } #[test] fn format_helpers_select_uint4_components_without_runtime_indexing() { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 6f7e1a1440..b5c1a14237 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -81,6 +81,11 @@ mod link_tests; /// (`console_heap::null_views`). pub const MEM_HEAP_BASE: u32 = 4; +/// Null raw-UAV descriptors just after all window slots. Heap-window loads outside the active +/// layout read zero from `MEM_NULL_LOAD`; stores are redirected to `MEM_NULL_STORE` and dropped. +pub const MEM_NULL_LOAD: u32 = MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32; +pub const MEM_NULL_STORE: u32 = MEM_NULL_LOAD + 1; + /// Flag in a memory-windows count (`pso::mem_windows`, the translation caches' keys): /// `Options::heap_windows`. `translate` takes it out of `mem_windows`. pub const HEAP_WINDOWS: u32 = 0x100; diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 34b5c65201..f738b41485 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1532,7 +1532,7 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result Result, Some(&raw_window_uav(size as u64)), h); } + for idx in [super::MEM_NULL_LOAD, super::MEM_NULL_STORE] { + let mut h = dh.GetCPUDescriptorHandleForHeapStart(); + h.ptr += idx as usize * inc; + dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(4)), h); + } list.SetDescriptorHeaps(&[Some(dh.clone())]); list.SetComputeRootSignature(&gpu.rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); @@ -1783,7 +1788,7 @@ fn dispatch_with( let dh: ID3D12DescriptorHeap = dev .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - NumDescriptors: super::MEM_HEAP_BASE + win_count as u32, + NumDescriptors: (super::MEM_HEAP_BASE + win_count as u32).max(super::MEM_NULL_STORE + 1), Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }) @@ -1794,6 +1799,11 @@ fn dispatch_with( h.ptr += (super::MEM_HEAP_BASE as usize + k) * inc; dev.CreateUnorderedAccessView(&mem_buf, None::<&ID3D12Resource>, Some(&raw_window_uav(mem_bytes)), h); } + for idx in [super::MEM_NULL_LOAD, super::MEM_NULL_STORE] { + let mut h = dh.GetCPUDescriptorHandleForHeapStart(); + h.ptr += idx as usize * inc; + dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(4)), h); + } list.SetDescriptorHeaps(&[Some(dh.clone()), Some(bound._heaps[1].clone())]); list.SetComputeRootSignature(rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 81ce117ed0..cd78056644 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -169,16 +169,18 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { } }; crate::xlog_info!("console descriptor heaps: one shader-visible PC heap of {cap} view descriptors for all of them"); - null_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + null_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, inc); + null_window_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, inc); *g = Some(Global { dev: dev.clone(), cpu: heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, gpu: heap.GetGPUDescriptorHandleForHeapStart().ptr, - inc: dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + inc, heap, cap, - // the memory windows' raw UAVs (`set_window_views`) come first - next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, + // the memory windows and their two out-of-range null UAVs come first + next: crate::gpu::recomp::MEM_NULL_STORE + 1, free: Vec::new(), }); } @@ -210,6 +212,19 @@ unsafe fn null_views(dev: &ID3D12Device, cpu: u64, inc: u32) { } } +/// Null raw UAVs used by heap-window accessors for out-of-layout loads and stores. +unsafe fn null_window_views(dev: &ID3D12Device, cpu: u64, inc: u32) { + for idx in [crate::gpu::recomp::MEM_NULL_LOAD, crate::gpu::recomp::MEM_NULL_STORE] { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + idx as u64 * inc as u64) as usize }; + dev.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&crate::gpu::recomp::runner::raw_window_uav(4)), + at, + ); + } +} + static WINDOW_VIEWS_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Whether the memory windows could not be put in the shared heap (`set_window_views`): From 972f66ec38f96a6f16f603af6c1c100144d926de Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:21:24 -0800 Subject: [PATCH 083/265] D3D12.X: publish submitted texture-write provenance Capture registered texture destinations in immutable per-segment effects and publish them only after the native submission gate accepts that physical segment. Reset, discarded, failed, and unsent split continuations cannot mark a texture. Track registration generations, writer-queue incarnations, monotonic GPU epochs, and known destination subresources without activating readback or synchronization. Preserve pre-submit lazy-level mapping preparation. Locally cross-checked with the GNU Windows target; Windows execution remains untested here. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 79 ++++++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 182 +++++++++++++++++--- 2 files changed, 226 insertions(+), 35 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 4281d2e13c..45efdd50e6 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -748,6 +748,8 @@ struct ListState { /// Sparse-window `(va, bytes)` ranges written by memory ops (`Write32/64`, `Fill*`, /// `CopyMemoryToMemoryX`, timestamps) to copy back to the CPU view after execution. sparse_writes: Vec<(usize, usize)>, + /// Writes into title textures produced by this physical segment. + texture_writes: Vec, /// Non-timestamp 64-bit `(va, value)` writes recorded by `Write64BitValue{Bottom,Top}OfPipeX` /// so `ExecuteCommandLists` / `KickoffX` can signal per-address GPU fences for cross-queue /// `Wait64BitValueX` without blocking the submitter thread on the CPU. @@ -867,6 +869,7 @@ impl ListState { struct KickoffEffects { waits: Vec, sparse_writes: Vec<(usize, usize)>, + texture_writes: Vec, write64_signals: Vec<(u64, u64)>, cpu_writes: Vec, } @@ -875,6 +878,7 @@ fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { let effects = KickoffEffects { waits: std::mem::take(&mut state.pending_waits), sparse_writes: state.clear_sparse_writes(), + texture_writes: std::mem::take(&mut state.texture_writes), write64_signals: state.clear_write64_signals(), cpu_writes: std::mem::take(&mut state.cpu_writes), }; @@ -976,12 +980,14 @@ impl SplitCarry { #[derive(Clone, Copy)] struct QueueInfo { queue: usize, + id: super::title_textures::WriterQueueId, device: usize, ty: D3D12_COMMAND_LIST_TYPE, } static LISTS: Mutex>> = Mutex::new(None); static LIVE_QUEUES: Mutex> = Mutex::new(Vec::new()); +static NEXT_QUEUE_ID: AtomicU64 = AtomicU64::new(0); /// Number of lists with recorded sparse-window memory writes (fast-path guard for post-execute readback). static SPARSE_WRITE_LISTS: AtomicUsize = AtomicUsize::new(0); /// Number of lists with recorded non-timestamp `Write64BitValue*` signals (fast-path guard). @@ -998,6 +1004,7 @@ pub(super) struct SegmentEffects { write_producers: RecordedWriteProducers, write64_signals: Vec<(u64, u64)>, sparse_writes: Vec<(usize, usize)>, + texture_writes: Vec, cpu_writes: Vec, } @@ -1032,6 +1039,7 @@ impl SubmissionPlan { write_producers: s.segment_write_producers.clone(), write64_signals: s.write64_signals.clone(), sparse_writes: s.sparse_writes.clone(), + texture_writes: s.texture_writes.clone(), cpu_writes: s.cpu_writes.clone(), }) .unwrap_or_default() @@ -1100,7 +1108,16 @@ pub fn on_queue_create(queue: usize, device: usize, ty: D3D12_COMMAND_LIST_TYPE) } let mut g = LIVE_QUEUES.lock().unwrap(); g.retain(|q| q.queue != queue); - g.push(QueueInfo { queue, device, ty }); + g.push(QueueInfo { queue, id: new_queue_id(queue), device, ty }); +} + +fn new_queue_id(raw: usize) -> super::title_textures::WriterQueueId { + let generation = NEXT_QUEUE_ID.fetch_add(1, Ordering::Relaxed).wrapping_add(1).max(1); + super::title_textures::WriterQueueId { raw, generation } +} + +fn queue_identity(raw: usize) -> Option { + LIVE_QUEUES.lock().unwrap().iter().find(|q| q.queue == raw).map(|q| q.id) } /// Remove a released command queue so `KickoffX` never submits to a dead queue. @@ -1221,6 +1238,7 @@ pub(super) fn clear_segment_state(list: usize) { s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); + s.texture_writes.clear(); s.cpu_writes.clear(); s.predication = None; s.pred_in_state = false; @@ -1350,7 +1368,7 @@ pub(super) unsafe fn note_queue_for_lists(queue: usize, lists: &[*mut c_void]) { } else { 0 }; - g.push(QueueInfo { queue, device: dev_raw, ty }); + g.push(QueueInfo { queue, id: new_queue_id(queue), device: dev_raw, ty }); } } } @@ -1377,6 +1395,11 @@ fn note_write(list: usize, producer: WriteProducer, va: u64, size: u64) { LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(producer, va, size); } +fn note_texture_write(list: usize, res: usize, subresource: u32) { + let Some(write) = super::title_textures::capture_gpu_write(res, subresource) else { return }; + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().texture_writes.push(write); +} + // --------------------------------------------------------------------------------------- // per-address GPU fence bridge for monotonic 64-bit Write64BitValue* -> Wait64BitValueX // --------------------------------------------------------------------------------------- @@ -2444,6 +2467,10 @@ pub(super) fn submission_plan(lists: &[*mut c_void]) -> SubmissionPlan { /// Publish the effects of an already-submitted chunk in the same order as the legacy consumers. unsafe fn submit_segment_effects(queue: *mut c_void, effects: &[SegmentEffects], needs_cpu_completion: bool) -> Option { + let texture_writes: Vec<_> = effects.iter().flat_map(|e| e.texture_writes.iter().copied()).collect(); + if let Some(id) = queue_identity(queue as usize) { + super::title_textures::publish_gpu_writes(id, &texture_writes); + } let write64_signals: Vec<(u64, u64)> = effects.iter().flat_map(|e| e.write64_signals.iter().copied()).collect(); signal_write64_pairs(queue, &write64_signals); @@ -3808,10 +3835,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let effects = match preclose_effects { Some(effects) => effects, None => LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).map(take_kickoff_effects).unwrap_or(KickoffEffects { - waits: Vec::new(), sparse_writes: Vec::new(), write64_signals: Vec::new(), cpu_writes: Vec::new(), + waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), write64_signals: Vec::new(), cpu_writes: Vec::new(), }), }; - let KickoffEffects { waits, sparse_writes, write64_signals, cpu_writes } = effects; + let KickoffEffects { waits, sparse_writes, texture_writes, write64_signals, cpu_writes } = effects; if let Some(wrapper) = super::title_list::wrapper_of(this) { record_deferred(wrapper); } @@ -3861,6 +3888,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let current_submitted = gate.submit(q_raw, &one, || {}, || exec(q_raw, 1, one.as_ptr())); if current_submitted { copy_scratch_submitted(q_raw, &one); + if let Some(id) = queue_identity(q_raw as usize) { + super::title_textures::publish_gpu_writes(id, &texture_writes); + } signal_write64_pairs(q_raw, &write64_signals); // what ran is in the textures' states; the list records anew after its Reset below super::title_textures::submitted(&one); @@ -3907,6 +3937,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); + s.texture_writes.clear(); s.cpu_writes.clear(); s.bindings = bindings_copy; } @@ -4610,6 +4641,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); + s.texture_writes.clear(); s.cpu_writes.clear(); s.predication = None; s.pred_in_state = false; @@ -4809,7 +4841,12 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds if let Some(d) = dst.as_ref() { let r: usize = transmute_copy(&d.pResource); super::present::note_use(r, super::present::USE_COPY); - super::title_textures::note_gpu_write(r); + let sub = if d.Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX { + d.Anonymous.SubresourceIndex + } else { + D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES + }; + note_texture_write(this as usize, r, sub); if super::present::trace_frame() { if let Some(va) = super::title_textures::address(r) { static N: AtomicU64 = AtomicU64::new(0); @@ -5005,7 +5042,7 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v /// are copied as their own bytes (the PC resources also hold what lies before them) pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) { super::present::note_use(dst, super::present::USE_COPY); - super::title_textures::note_gpu_write(dst); + note_texture_write(this as usize, dst, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); if super::present::trace_frame() { trace_watched_copy("CopyResource", dst, src); } @@ -5601,6 +5638,7 @@ mod tests { ListState { write64_signals: vec![(0x1000 + i as u64, 10 + i as u64)], sparse_writes: vec![(0x2000 + i, 4 + i)], + texture_writes: vec![super::super::title_textures::GpuWrite { res: 0x2500 + i, generation: 20 + i as u64, subresource: i as u32 }], cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x3000 + i, vec![i as u32])], ..Default::default() }, @@ -5621,6 +5659,7 @@ mod tests { for (i, effects) in plan.effects.iter().enumerate() { assert_eq!(effects.write64_signals, vec![(0x1000 + i as u64, 10 + i as u64)]); assert_eq!(effects.sparse_writes, vec![(0x2000 + i, 4 + i)]); + assert_eq!(effects.texture_writes, vec![super::super::title_textures::GpuWrite { res: 0x2500 + i, generation: 20 + i as u64, subresource: i as u32 }]); match effects.cpu_writes.as_slice() { [super::super::cpu_writes::Write::Immediate(va, words)] => assert_eq!((*va, words.as_slice()), (0x3000 + i, &[i as u32][..])), _ => panic!("unexpected CPU write snapshot"), @@ -5628,6 +5667,19 @@ mod tests { } } + #[test] + fn queue_identity_changes_when_a_raw_address_is_reused() { + let raw = 0x7ffe_1801usize; + on_queue_create(raw, 0x2000, D3D12_COMMAND_LIST_TYPE_DIRECT); + let first = queue_identity(raw).unwrap(); + on_queue_release(raw); + on_queue_create(raw, 0x2000, D3D12_COMMAND_LIST_TYPE_DIRECT); + let second = queue_identity(raw).unwrap(); + assert_eq!((first.raw, second.raw), (raw, raw)); + assert_ne!(first.generation, second.generation); + on_queue_release(raw); + } + #[test] fn submission_plan_is_isolated_from_reset_and_rerecord() { let list = 0x7ffe_2001usize as *mut c_void; @@ -5638,6 +5690,7 @@ mod tests { pending_waits: vec![old_wait], write64_signals: vec![(0x4000, 4)], sparse_writes: vec![(0x5000, 8)], + texture_writes: vec![super::super::title_textures::GpuWrite { res: 0x5500, generation: 4, subresource: 2 }], cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x6000, vec![4])], ..Default::default() }; @@ -5653,6 +5706,7 @@ mod tests { state.pending_waits = vec![PendingWait { value: 9, ..old_wait }]; state.write64_signals = vec![(0x4000, 9)]; state.sparse_writes = vec![(0x7000, 16)]; + state.texture_writes = vec![super::super::title_textures::GpuWrite { res: 0x7500, generation: 9, subresource: 3 }]; state.cpu_writes = vec![super::super::cpu_writes::Write::Immediate(0x8000, vec![9])]; state.written_ranges.clear(); state.segment_write_producers.clear(); @@ -5663,6 +5717,7 @@ mod tests { assert_eq!(effects.waits, vec![old_wait]); assert_eq!(effects.write64_signals, vec![(0x4000, 4)]); assert_eq!(effects.sparse_writes, vec![(0x5000, 8)]); + assert_eq!(effects.texture_writes, vec![super::super::title_textures::GpuWrite { res: 0x5500, generation: 4, subresource: 2 }]); assert!(effects.producer_overlaps(WriteProducer::InSegmentGpu, 0x4100, 8)); assert!(effects.producer_overlaps(WriteProducer::CpuAfterSegment, 0x4200, 8)); assert!(!effects.producer_overlaps(WriteProducer::CpuAfterSegment, 0x4300, 8)); @@ -5850,6 +5905,7 @@ mod tests { allocator: 0xa110, list_type: Some(D3D12_COMMAND_LIST_TYPE_COMPUTE), pending_waits: vec![wait], + texture_writes: vec![super::super::title_textures::GpuWrite { res: 0x4800, generation: 2, subresource: 0 }], cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x5000, vec![1])], ..Default::default() }; @@ -5862,7 +5918,7 @@ mod tests { let state = &g.as_ref().unwrap()[&list]; assert_eq!(state.allocator, 0, "KickoffX must take its allocator-unknown no-op path"); assert_eq!(state.list_type, Some(D3D12_COMMAND_LIST_TYPE_DIRECT)); - assert!(state.pending_waits.is_empty() && state.cpu_writes.is_empty() && state.segment_write_producers.is_empty()); + assert!(state.pending_waits.is_empty() && state.texture_writes.is_empty() && state.cpu_writes.is_empty() && state.segment_write_producers.is_empty()); g.as_mut().unwrap().remove(&list); } @@ -5886,6 +5942,7 @@ mod tests { let wait = PendingWait { va: 0x4000, width: 8, comparison: 7, value: 1, mask: u64::MAX, after_write64: false }; let mut state = ListState { pending_waits: vec![wait], + texture_writes: vec![super::super::title_textures::GpuWrite { res: 0x4800, generation: 3, subresource: 1 }], cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x5000, vec![1])], ..Default::default() }; @@ -5893,14 +5950,16 @@ mod tests { assert!(take_kickoff_effects_before_close(&mut state, true).is_none()); assert_eq!(state.pending_waits, vec![wait]); + assert_eq!(state.texture_writes.len(), 1); assert_eq!(state.cpu_writes.len(), 1); assert!(state.written_ranges.overlaps(WriteProducer::CpuAfterSegment, 0x5000, 4)); assert!(state.segment_write_producers.overlaps(WriteProducer::CpuAfterSegment, 0x5000, 4)); let effects = take_kickoff_effects_before_close(&mut state, false).unwrap(); assert_eq!(effects.waits, vec![wait]); + assert_eq!(effects.texture_writes.len(), 1); assert_eq!(effects.cpu_writes.len(), 1); - assert!(state.pending_waits.is_empty() && state.cpu_writes.is_empty()); + assert!(state.pending_waits.is_empty() && state.texture_writes.is_empty() && state.cpu_writes.is_empty()); assert!(state.written_ranges.is_empty() && state.segment_write_producers.is_empty()); } @@ -5959,6 +6018,7 @@ mod tests { pending_waits: vec![PendingWait { va: 0xd440, width: 8, comparison: 7, value: 5, mask: u64::MAX, after_write64: false }], write64_signals: vec![(0xe550, 6)], sparse_writes: vec![(0xf660, 8)], + texture_writes: vec![super::super::title_textures::GpuWrite { res: 0xf770, generation: 5, subresource: 0 }], bindings: Bindings { heaps: vec![0x1010, 0x2020], topology: Some(4), stencil: Some(9), ..Default::default() }, ..Default::default() }; @@ -5993,11 +6053,12 @@ mod tests { assert_eq!(continued.bindings.stencil, Some(9)); assert!(continued.written_ranges.overlaps(WriteProducer::InSegmentGpu, 0x3010, 4)); assert!(continued.segment_write_producers.is_empty(), "a continuation has not produced the carried ranges"); - assert!(continued.pending_waits.is_empty() && continued.write64_signals.is_empty() && continued.sparse_writes.is_empty()); + assert!(continued.pending_waits.is_empty() && continued.write64_signals.is_empty() && continued.sparse_writes.is_empty() && continued.texture_writes.is_empty()); assert!(continued.cpu_writes.is_empty() && continued.deferred.is_none() && continued.own_alloc.is_none()); assert_eq!(state.pending_waits.len(), 1, "effects remain on the closed segment"); assert_eq!(state.write64_signals, vec![(0xe550, 6)]); assert_eq!(state.sparse_writes, vec![(0xf660, 8)]); + assert_eq!(state.texture_writes.len(), 1); assert!(state.segment_write_producers.overlaps(WriteProducer::InSegmentGpu, 0x3010, 4)); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d44a31152d..2b9ee64a22 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -41,6 +41,28 @@ extern "system" { /// (device, address its bytes are read from, layout, states) of an upload type Upload = (usize, usize, Arc, Vec); +/// One incarnation of a title command queue. The raw address alone can be reused after release. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct WriterQueueId { + pub(super) raw: usize, + pub(super) generation: u64, +} + +/// A GPU write captured while a physical command-list segment is recorded. Its registration +/// generation prevents a late/replayed segment from marking a new object at a reused address. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct GpuWrite { + pub(super) res: usize, + pub(super) generation: u64, + pub(super) subresource: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct GpuWriter { + epoch: u64, + queue: WriterQueueId, +} + struct Entry { device: usize, /// the title's address of the texture @@ -61,12 +83,15 @@ struct Entry { /// the title's GPU work wrote it (CopyTextureRegion into it): its CPU view is stale from /// then on and no longer uploaded gpu_written: bool, + /// Last submitted GPU writer: one for the whole resource while uniform, otherwise one per + /// subresource in D3D12 order. Empty until a tracked write is submitted. + gpu_writers: Vec>, /// backed by shared `vram::Pages` tiles (overlapping placements share video memory) placed: bool, /// tiles were unmapped after a different-range placement superseded this texture unmapped: bool, - /// monotonic registration order (newest wins when uncovering shadowed textures) - seq: u64, + /// monotonic registration generation (newest wins when uncovering shadowed textures) + generation: u64, } /// textures waiting for their first upload @@ -86,7 +111,7 @@ struct Table { shadowed_by_va: BTreeMap<(usize, usize), usize>, /// Largest byte span currently in `shadowed` (bounds range queries) max_shadowed_size: usize, - next_seq: u64, + next_generation: u64, } impl Table { @@ -97,7 +122,7 @@ impl Table { shadowed: BTreeMap::new(), shadowed_by_va: BTreeMap::new(), max_shadowed_size: 0, - next_seq: 0, + next_generation: 0, } } @@ -219,8 +244,8 @@ impl Table { } } } - self.next_seq += 1; - entry.seq = self.next_seq; + self.next_generation = self.next_generation.wrapping_add(1).max(1); + entry.generation = self.next_generation; if entry.pending { pending_delta += 1; } @@ -247,7 +272,7 @@ impl Table { let mut cands: Vec<(u64, usize, usize, usize)> = self .shadowed_overlaps(va, end) .into_iter() - .filter_map(|(sva, sres, send)| self.shadowed.get(&sres).map(|e| (e.seq, sres, sva, send))) + .filter_map(|(sva, sres, send)| self.shadowed.get(&sres).map(|e| (e.generation, sres, sva, send))) .collect(); cands.sort_unstable_by(|a, b| b.0.cmp(&a.0)); let mut to_remap = Vec::new(); @@ -385,9 +410,10 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, states: vec![state], pending: true, gpu_written: false, + gpu_writers: Vec::new(), placed: super::vram::is_placed_texture(res as usize), unmapped: false, - seq: 0, + generation: 0, }; let to_unmap = { let mut t = TEXTURES.lock().unwrap(); @@ -457,13 +483,9 @@ fn recheck_source(e: &mut Entry) -> bool { true } -/// The title's GPU work writes texture `res` (a copy into it): on the console the memory then -/// holds what the GPU wrote; here the CPU's view of it is stale, so it is not uploaded again -/// (a CPU write elsewhere on its pages – a neighbour, an allocator's header – would upload the -/// stale view over the copy: Fortnite's font atlas is zeros in memory, its glyphs are copied in -/// by the GPU). The first upload, if still pending, stays: it runs before the title's submit -/// that copies. -pub fn note_gpu_write(res: usize) { +/// Prepare a recorded GPU write and capture the current registration generation. Lazy level +/// mappings must exist before submission; provenance itself is published only after submission. +pub(super) fn capture_gpu_write(res: usize, subresource: u32) -> Option { if super::vram::level_pages() { // (a texture whose levels get their pages one by one: all of them before the GPU's write) let p = res as *mut c_void; @@ -473,23 +495,46 @@ pub fn note_gpu_write(res: usize) { } } } - let mut marked = false; + let t = TEXTURES.lock().unwrap(); + let e = t.by_res.get(&res).or_else(|| t.shadowed.get(&res))?; + Some(GpuWrite { res, generation: e.generation, subresource }) +} + +/// Publish writes from command-list segments that the native submission gate accepted. On the +/// console their memory now belongs to the GPU result, so its stale CPU view is not uploaded. +pub(super) fn publish_gpu_writes(queue: WriterQueueId, writes: &[GpuWrite]) { + if writes.is_empty() { + return; + } + let mut newly_written = Vec::new(); { let mut t = TEXTURES.lock().unwrap(); - if let Some(e) = t.get_mut(res) { + for &write in writes { + let Some(e) = t.get_mut(write.res).filter(|e| e.generation == write.generation) else { continue }; + let n = subresource_count(&e.tex); + if write.subresource != D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES && !(n <= 1 && write.subresource == 0) && write.subresource as usize >= n { + continue; + } + let epoch = NEXT_GPU_EPOCH.fetch_add(1, Ordering::Relaxed) + 1; + let writer = GpuWriter { epoch, queue }; + apply_gpu_writer(&mut e.gpu_writers, n, write.subresource, writer); if !e.gpu_written { e.gpu_written = true; GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); - marked = true; + newly_written.push(write.res); } } } - if marked { - STREAM_RECHECK.lock().unwrap().remove(&res); + if !newly_written.is_empty() { + let mut recheck = STREAM_RECHECK.lock().unwrap(); + for res in newly_written { + recheck.remove(&res); + } } } static GPU_WRITTEN: AtomicU64 = AtomicU64::new(0); +static NEXT_GPU_EPOCH: AtomicU64 = AtomicU64::new(0); /// The textures kept in step whose memory `[va, va + len)` overlaps (PC texture, its address). pub fn overlapping(va: usize, len: usize) -> Vec<(usize, usize)> { @@ -629,6 +674,25 @@ fn subresource_count(tex: &xg::Texture) -> usize { tex.texels().map_or(1, |s| s.array as usize * s.chain.levels.len()) } +/// Apply one writer to all subresources or one known subresource. The representation mirrors +/// `states`: one value while uniform, one per subresource while they differ. +fn apply_gpu_writer(writers: &mut Vec>, n: usize, sub: u32, writer: GpuWriter) { + if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES || (n <= 1 && sub == 0) { + *writers = vec![Some(writer)]; + return; + } + let k = sub as usize; + if writers.is_empty() { + *writers = vec![None; n]; + } else if writers.len() != n { + *writers = vec![writers[0]; n]; + } + writers[k] = Some(writer); + if writers.iter().all(|&w| w == Some(writer)) { + writers.truncate(1); + } +} + /// `states` (one for all `n` subresources, or one each) after a transition of subresource `sub` /// (or all of them) to `after`; a subresource the texture does not have is ignored. fn apply_transition(states: &mut Vec, n: usize, sub: u32, after: D3D12_RESOURCE_STATES) { @@ -1915,7 +1979,7 @@ mod tests { d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); d[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); let tex = Arc::new(xg::Texture::new(&d).unwrap()); - let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, placed: false, unmapped: false, seq: 0 }; + let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, gpu_writers: Vec::new(), placed: false, unmapped: false, generation: 0 }; assert_eq!(e.src, cpu + 0x2_0000); assert!(!recheck_source(&mut e), "nothing changed yet"); assert_eq!(kernelx::MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, at); @@ -1994,6 +2058,68 @@ mod tests { assert_eq!(one, vec![D3D12_RESOURCE_STATE_COPY_SOURCE]); } + #[test] + fn submitted_gpu_writes_keep_generation_queue_epoch_and_subresource() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 2, 3, 28, 0x105)).unwrap()); + let res = 0x7E57_1000_1000usize; + let entry = |tex: &Arc| Entry { + device: 0, + va: 0x7E57_1000_0000, + src: 0x7E57_1000_0000, + in_gpu_view: false, + tex: Arc::clone(tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written: false, + gpu_writers: Vec::new(), + placed: false, + unmapped: false, + generation: 0, + }; + let generation = { + let mut t = TEXTURES.lock().unwrap(); + t.insert(res, entry(&tex)); + t.by_res[&res].generation + }; + let first = GpuWrite { res, generation, subresource: 2 }; + let q1 = WriterQueueId { raw: 0x1000, generation: 7 }; + publish_gpu_writes(q1, &[first]); + let first_epoch = { + let t = TEXTURES.lock().unwrap(); + let e = &t.by_res[&res]; + assert!(e.gpu_written); + assert_eq!(e.gpu_writers.len(), 6); + assert!(e.gpu_writers.iter().enumerate().all(|(i, w)| (i == 2) == w.is_some())); + let w = e.gpu_writers[2].unwrap(); + assert_eq!(w.queue, q1); + w.epoch + }; + + let q2 = WriterQueueId { raw: 0x2000, generation: 9 }; + publish_gpu_writes(q2, &[GpuWrite { res, generation, subresource: 4 }]); + { + let t = TEXTURES.lock().unwrap(); + let e = &t.by_res[&res]; + assert_eq!(e.gpu_writers[2].unwrap().queue, q1); + let last = e.gpu_writers[4].unwrap(); + assert_eq!(last.queue, q2); + assert!(last.epoch > first_epoch); + } + + // Reusing the resource address creates another registration generation: a captured + // effect from the old object must not mark it. + { + let mut t = TEXTURES.lock().unwrap(); + t.remove(res); + t.insert(res, entry(&tex)); + assert_ne!(t.by_res[&res].generation, generation); + } + publish_gpu_writes(q1, &[first]); + assert!(!TEXTURES.lock().unwrap().by_res[&res].gpu_written); + TEXTURES.lock().unwrap().remove(res); + } + /// A texture kept in step: the title's transitions count once their list is submitted, in /// submission order, each time it is; a Reset forgets them; other resources are not noted. #[test] @@ -2013,7 +2139,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, placed: false, unmapped: false, seq: 0 }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, gpu_writers: Vec::new(), placed: false, unmapped: false, generation: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().by_res.get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); @@ -2195,9 +2321,10 @@ mod tests { states: vec![D3D12_RESOURCE_STATE_COMMON], pending, gpu_written: false, + gpu_writers: Vec::new(), placed, unmapped: false, - seq: 0, + generation: 0, }; let mut tbl = Table::new(); // Two adjacent placed 16 KiB textures + one placed 64 KiB texture after them. @@ -2605,9 +2732,10 @@ mod tests { states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, + gpu_writers: Vec::new(), placed: false, unmapped: false, - seq: 0, + generation: 0, }; let e_gpu = Entry { device: 0, @@ -2618,9 +2746,10 @@ mod tests { states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, + gpu_writers: Vec::new(), placed: false, unmapped: false, - seq: 0, + generation: 0, }; { let mut t = TEXTURES.lock().unwrap(); @@ -2801,7 +2930,8 @@ mod tests { } // what the GPU writes needs pages under all of the texture: the first one's mip 0 gets // the pages of its address, which hold what the second one's upload put there - note_gpu_write(small.as_raw() as usize); + let write = capture_gpu_write(small.as_raw() as usize, ALL).unwrap(); + publish_gpu_writes(WriterQueueId { raw: queue.as_raw() as usize, generation: 1 }, &[write]); assert_eq!(dev_pages() - p0, (all as usize) << 16, "the same pages"); assert!(read_sub(&small, 0) == want[0].data, "a GPU-written texture has pages under all its levels"); std::ptr::write_bytes((at + top) as *mut u8, 0, size - top); From 3fd55dfffa16c5e11df13b4e21b6901e45ef12a9 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:58:59 +0100 Subject: [PATCH 084/265] DirectStorage: wake waiters from ordered completion events Implement IDStorageQueueX1::EnqueueSetEvent as an ordered queue marker. The queue owns a restricted duplicate handle until every earlier request retires, then signals it; Close safely discards pending markers. Adapted from #2569 with sequential auto-submit, parallel retirement ordering, caller-handle lifetime, and Close coverage. Upstream reports full Windows suite and retail smoke coverage. Locally cross-checked with the GNU Windows target; Windows event execution remains untested here. Assisted-by: Codex (GPT-6.2 Sol) Assisted-by: Codex (GPT-5.6-sol) --- README.md | 2 +- crates/xcl/src/hle/dstorage.rs | 30 +++++- crates/xcl/src/hle/dstorage/parallel_tests.rs | 102 +++++++++++++++++- 3 files changed, 126 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 99e3ac7c2d..8957cb3789 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif | **kernelx** | ✅ | title memory (budget from MicrosoftGame.Config, physical pages), threads on the PC's processors, modules, OS / console info | unit + end-to-end tests | | **Memory** | ✅ | title graphics memory shared by CPU and GPU without copies, up to 16 GB (4 GiB windows) | GPU tests: loads, stores and atomics across windows | | **File system** | ✅ | console paths (`GAME:`, `G:`, `D:` …) → the game folder; writes go to an overlay, the game folder is never modified; the console's drives: `S:\` (persistent local storage) and `T:\` (temp) in the title's data folder; free disk space answered for console paths | end-to-end: the test title's folder stays byte-identical; PLS and free space through the real call path | -| **DirectStorage** | ✅ | the console's DirectStorage queues: file and memory sources, zlib, and BCPack – the console's texture compression – for BC1, BC3, BC4, BC5, BC6H and BC7 (BC2 and the hardware swizzle are refused) | unit tests on synthetic streams; retail BCPack chunks of all six modes byte-identical with a reference decoder (`XCL_SAMPLE_BCPACK`) | +| **DirectStorage** | ✅ | the console's DirectStorage queues: file and memory sources, queued event notifications, zlib, and BCPack – the console's texture compression – for BC1, BC3, BC4, BC5, BC6H and BC7 (BC2 and the hardware swizzle are refused) | unit tests on synthetic streams; retail BCPack chunks of all six modes byte-identical with a reference decoder (`XCL_SAMPLE_BCPACK`) | diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 9972f2e538..7a416ddfe5 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -18,7 +18,8 @@ //! * queue: QueryInterface, AddRef, Release, EnqueueRequest, EnqueueStatus(array, index), //! EnqueueSignal(fence, value), Submit, CancelRequestsWithTag(mask, value), Close, //! GetErrorEvent, RetrieveErrorRecord (0x290 bytes), Query (0x1C: the desc, then empty -//! slots u16 @0x18 and requests until the automatic submit u16 @0x1A), then 6 more, +//! slots u16 @0x18 and requests until the automatic submit u16 @0x1A), then the X1 +//! EnqueueSetEvent(handle) method and 5 more, //! * file: QueryInterface, AddRef, Release, Close, GetHandle, 2 unknown, GetId, then 4 more; //! status array: QueryInterface, AddRef, Release, IsComplete(index), GetHResult(index), //! then 5 more. @@ -26,8 +27,9 @@ //! Each queue has a worker thread: submitted requests run in order (file reads through the //! VFS like the title's own, memory copies, zlib, BCPack where `hle::bcpack` rebuilds the //! blocks of the mode), a status entry gets the first failure of the requests since the -//! previous one, a signal sets the fence from the CPU. Methods not listed are logged and -//! answer E_NOTIMPL; BCPack BC2 and modes above 7, and the hardware swizzle, are refused. +//! previous one, a signal sets the fence from the CPU, and an event signals a Win32 waiter. +//! Unlisted methods log and answer E_NOTIMPL. BCPack BC2, modes above 7, and the hardware +//! swizzle are refused. #![allow(non_snake_case)] @@ -36,7 +38,7 @@ mod parallel; use std::ffi::c_void; use std::os::windows::fs::FileExt; -use std::os::windows::io::AsRawHandle; +use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; use std::collections::BTreeMap; use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; @@ -45,7 +47,7 @@ use serde::{Deserialize, Serialize}; use windows_sys::core::GUID; use windows_sys::Win32::Foundation::{CloseHandle, DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE}; use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; -use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent}; +use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent, EVENT_MODIFY_STATE}; use crate::util::{HRESULT, S_OK}; @@ -1033,6 +1035,7 @@ enum Entry { Status(Arc, u32), /// a fence (one reference held) and the value it gets Signal(FenceRef, u64), + SetEvent(OwnedHandle), #[cfg(test)] /// Test-only barrier to hold the worker deterministically while testing submitted-batch cancellation. Gate(Arc), @@ -1197,6 +1200,9 @@ impl QueueInner { Entry::Signal(fence, value) => unsafe { fence.signal(value); }, + Entry::SetEvent(event) => unsafe { + SetEvent(event.as_raw_handle()); + }, #[cfg(test)] Entry::Gate(b) => { b.wait(); @@ -1274,6 +1280,7 @@ fn queue_vtbl() -> &'static [usize] { queue_get_error_event as usize, queue_retrieve_error_record as usize, queue_query as usize, + queue_enqueue_set_event as usize, // IDStorageQueueX1 ], 18, ) @@ -1439,6 +1446,19 @@ unsafe extern "system" fn queue_enqueue_signal(p: *mut c_void, fence: *mut c_voi q.enqueue(Entry::Signal(FenceRef(fence as usize), value)); } +unsafe extern "system" fn queue_enqueue_set_event(p: *mut c_void, event: HANDLE) { + let q = queue(p); + if q.closed.load(Ordering::Acquire) || event.is_null() { + return; + } + // Retain a separate handle until the marker reaches the worker or is discarded. + let mut duplicate = std::ptr::null_mut(); + let me = GetCurrentProcess(); + if DuplicateHandle(me, event, me, &mut duplicate, EVENT_MODIFY_STATE, 0, 0) != 0 { + q.enqueue(Entry::SetEvent(OwnedHandle::from_raw_handle(duplicate))); + } +} + unsafe extern "system" fn queue_submit(p: *mut c_void) { let q = queue(p); if !q.closed.load(Ordering::Acquire) { diff --git a/crates/xcl/src/hle/dstorage/parallel_tests.rs b/crates/xcl/src/hle/dstorage/parallel_tests.rs index 5d5214e4fb..23632eb1eb 100644 --- a/crates/xcl/src/hle/dstorage/parallel_tests.rs +++ b/crates/xcl/src/hle/dstorage/parallel_tests.rs @@ -2,11 +2,14 @@ use super::super::*; use super::*; use std::io::Write; use std::os::windows::ffi::OsStrExt; +use std::os::windows::io::{FromRawHandle, OwnedHandle}; use std::panic::{self, AssertUnwindSafe}; use std::path::PathBuf; use std::ptr::null_mut; use std::thread; use std::time::{Duration, Instant}; +use windows_sys::Win32::Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT}; +use windows_sys::Win32::System::Threading::WaitForSingleObject; const TIMEOUT: Duration = Duration::from_secs(5); const TEST_BUDGET: usize = 1024 * 1024; @@ -109,11 +112,15 @@ struct TestQueue(*mut c_void); impl TestQueue { fn new(pool: Option>, hook: Option) -> Self { + Self::with_desc(64, &IID_QUEUE, pool, hook) + } + + fn with_desc(capacity: u16, iid: &GUID, pool: Option>, hook: Option) -> Self { let mut desc = [0; 0x18]; - desc[8..10].copy_from_slice(&64u16.to_le_bytes()); + desc[8..10].copy_from_slice(&capacity.to_le_bytes()); let mut raw = null_mut(); assert_eq!( - unsafe { factory_create_queue(null_mut(), desc.as_ptr(), &IID_QUEUE, &mut raw) }, + unsafe { factory_create_queue(null_mut(), desc.as_ptr(), iid, &mut raw) }, S_OK ); let queue = Self(raw); @@ -137,6 +144,14 @@ impl TestQueue { unsafe { queue_enqueue_status(self.0, status.0, slot) }; } + fn enqueue_set_event(&self, event: &OwnedHandle) { + unsafe { + let vtable = *(self.0 as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, HANDLE) = std::mem::transmute(*vtable.add(12)); + enqueue(self.0, event.as_raw_handle()); + } + } + fn submit(&self) { unsafe { queue_submit(self.0) }; } @@ -262,6 +277,89 @@ fn await_later_preparation(events: &mpsc::Receiver) { } } +fn completion_event() -> OwnedHandle { + let event = unsafe { CreateEventW(null_mut(), 1, 0, null_mut()) }; + assert!(!event.is_null()); + unsafe { OwnedHandle::from_raw_handle(event) } +} + +#[test] +fn completion_event_auto_submits_a_half_full_sequential_queue() { + with_deadline(|| { + let payload = vec![0x7b; 48 * 1024]; + let file = TestFile::compressed(&[&payload]); + let mut output = vec![0x5d; payload.len()]; + let queue = TestQueue::with_desc(6, &IID_QUEUE_X1, None, None); + let status = TestStatus::new(1); + let event = completion_event(); + unsafe { queue.enqueue(&file.request(0, output.as_mut_ptr() as usize, 1)) }; + queue.status(&status, 0); + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 0) }, WAIT_TIMEOUT); + queue.enqueue_set_event(&event); + + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 2_000) }, WAIT_OBJECT_0); + assert_eq!(status.result(0), S_OK); + assert_eq!(output, payload); + }); +} + +#[test] +fn completion_event_waits_for_parallel_retirement_and_keeps_its_handle() { + with_deadline(|| { + let payload = vec![0x4d; 48 * 1024]; + let file = TestFile::compressed(&[&payload]); + let mut output = vec![0; payload.len()]; + let mut failed = vec![0x72; payload.len()]; + let pool = test_pool(2, TEST_BUDGET); + let (gate, milestones, release) = gated_hook(TestEvent::BeforeDecode(1)); + let last_retired = Arc::new(AtomicU64::new(0)); + let retired = Arc::clone(&last_retired); + let hook = Arc::new(move |event| { + if let TestEvent::Retired(seq) = event { + retired.store(seq, Ordering::Release); + } + gate(event); + }); + let queue = TestQueue::with_desc(64, &IID_QUEUE_X1, Some(pool), Some(hook)); + let status = TestStatus::new(1); + let event = completion_event(); + let observer = event.try_clone().unwrap(); + + let mut short = file.request(0, failed.as_mut_ptr() as usize, 2); + short[0x30..0x34].copy_from_slice(&(file.chunks[0].1 + 1).to_le_bytes()); + unsafe { + queue.enqueue(&file.request(0, output.as_mut_ptr() as usize, 1)); + queue.enqueue(&short); + } + queue.enqueue_set_event(&event); + queue.status(&status, 0); + queue.submit(); + + assert_eq!(receive(&milestones), TestEvent::BeforeDecode(1)); + let early_wait = unsafe { WaitForSingleObject(observer.as_raw_handle(), 0) }; + drop(event); + release.send(()).unwrap(); + assert_eq!(early_wait, WAIT_TIMEOUT); + assert_eq!(unsafe { WaitForSingleObject(observer.as_raw_handle(), 2_000) }, WAIT_OBJECT_0); + assert_eq!(last_retired.load(Ordering::Acquire), 2); + assert_eq!(status.wait(0), E_END_OF_FILE); + assert_eq!(output, payload); + assert!(failed.iter().all(|&byte| byte == 0x72)); + }); +} + +#[test] +fn completion_event_close_discards_the_pending_marker() { + let queue = TestQueue::with_desc(64, &IID_QUEUE_X1, None, None); + let event = completion_event(); + queue.enqueue_set_event(&event); + assert_eq!(queue.inner().pending.lock().unwrap().entries.len(), 1); + unsafe { queue_close(queue.0) }; + + assert!(queue.inner().pending.lock().unwrap().entries.is_empty()); + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 0) }, WAIT_TIMEOUT); +} + #[test] fn parallel_out_of_order_completion_retires_fifo() { with_deadline(|| { From 4ca5c6fea99e5178783c985d0ee2f5a11712f34f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:25:45 -0800 Subject: [PATCH 085/265] D3D12.X: persist slow driver blobs past the RAM cap Capture and persist the exact successful uncached pipeline result whose driver build crossed the slow threshold, even when bounded RAM-cache admission fails. Same-key builders reserve capture/publication, and disk-path turns prevent distinct RAM identities from racing one pathname. Publish disk before RAM visibility, remember cap-refused persisted keys, clear that marker on cached-blob rejection, and preserve exact-generation invalidation plus AMD default-off policy. Adapted from #2574 after prerequisites #2577 and #2614. Locally cross-checked with the GNU Windows target; Windows filesystem and driver execution remain untested here. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 3 + crates/xcl/src/hle/d3d12x/real.rs | 321 ++++++++++++++++++++++++------ 2 files changed, 258 insertions(+), 66 deletions(-) diff --git a/README.md b/README.md index 99e3ac7c2d..07b1a07226 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder toolchain are unchanged; `XCL_TRANSLATED_CACHE=0` disables that disk cache. Loading a cached shader without split pieces reuses the file buffer, avoiding a second payload-sized allocation. +- XCL saves an eligible driver blob when its pipeline takes at least 250 ms to build, even + after the bounded in-memory blob cache fills. This is off by default on AMD; + `XCL_PSO_DISK_CACHE=1` forces it on, and `XCL_PSO_DISK_CACHE=0` disables it elsewhere. - Direct compute dispatches can split large programs into pipelines built in parallel. `XCL_DIRECT_SPLIT_INSTRUCTIONS` sets the target instructions per piece (default 12500, zero disables splitting). Loops stay in one piece. A strongly connected component over the diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e624be31e9..285b976eba 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4499,6 +4499,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL Some((record, cached.is_some())), || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), ); + let mut persist_took = in_driver; if hr < 0 && cached.is_some() { // a blob the driver does not take (another root signature at the same address…): compiled forget_compute_blob(key); @@ -4518,13 +4519,12 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL ); hr = retried; in_driver += took; + persist_took = took; } let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; if hr >= 0 && !reused { - keep_compute_blob(key, *ppv, dxil.len()); - if let (Some(p), Some(b)) = (disk.as_deref(), compute_blob(key)) { - driver_cache::keep(p, &b, in_driver); - } + keep_driver_blob(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, key, dxil.len(), disk.as_deref(), persist_took, + || read_pso_cached_blob(*ppv)); } else if reused && from_disk { driver_cache::note(true, loaded.take()); } @@ -4547,7 +4547,7 @@ pub(crate) mod driver_cache { use std::os::windows::fs::OpenOptionsExt; use std::os::windows::io::AsRawHandle; use std::path::{Path, PathBuf}; - use std::sync::Arc; + use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; /// builds shorter than this are not worth a file @@ -4556,6 +4556,7 @@ pub(crate) mod driver_cache { static STALE: AtomicU64 = AtomicU64::new(0); static STORED: AtomicU64 = AtomicU64::new(0); static REFERENCE_BLOBS: AtomicBool = AtomicBool::new(false); + static ACTIVE_KEEPS: Mutex>> = Mutex::new(None); /// AMD's cached-PSO blobs name entries in the driver's own cache instead of containing /// self-sufficient code. They are not safe to carry across runs unless explicitly enabled. @@ -4742,16 +4743,51 @@ pub(crate) mod driver_cache { ok } - /// Keep `blob`, of a build that took `took`, for the next run. - pub fn keep(p: &Path, blob: &[u8], took: std::time::Duration) { - if took >= KEEP && write(p, blob) { - let n = STORED.fetch_add(1, Ordering::Relaxed) + 1; - if n.is_power_of_two() { - crate::xlog_info!("D3D12.X: {n} driver blobs kept on disk for the next run (this one: {} ms, {} KB)", took.as_millis(), blob.len() >> 10); + /// Exclusive publication turn for one pathname within this process. Different in-memory + /// identities can share a disk key (notably compute root-signature pointers), so reserve the + /// pathname before capturing bytes as well as reserving the in-memory key. + pub(super) struct KeepTurn(PathBuf, std::time::Duration); + + impl KeepTurn { + pub(super) fn new(p: &Path, took: std::time::Duration) -> Option { + if took < KEEP { + return None; + } + let mut active = ACTIVE_KEEPS.lock().unwrap(); + active.get_or_insert_with(std::collections::HashSet::new).insert(p.to_owned()).then(|| Self(p.to_owned(), took)) + } + + pub(super) fn store(&self, blob: &[u8]) -> bool { + if write(&self.0, blob) { + let n = STORED.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: {n} driver blobs kept on disk for the next run (this one: {} ms, {} KB)", self.1.as_millis(), blob.len() >> 10); + } + true + } else { + false } } } + impl Drop for KeepTurn { + fn drop(&mut self) { + if let Some(active) = ACTIVE_KEEPS.lock().unwrap().as_mut() { + active.remove(&self.0); + } + } + } + + /// Keep `blob`, of a build that took `took`, for the next run. + #[cfg(test)] + pub fn keep(p: &Path, blob: &[u8], took: std::time::Duration) -> bool { + if let Some(turn) = KeepTurn::new(p, took) { + turn.store(blob) + } else { + false + } + } + #[cfg(test)] mod tests { use super::*; @@ -4765,6 +4801,122 @@ pub(crate) mod driver_cache { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } + #[test] + fn a_slow_blob_is_saved_after_the_memory_cache_fills() { + use super::super::{keep_driver_blob, DriverBlobs, COMPUTE_BLOB_MIN_DXIL}; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-full-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let path = dir.join("late.pso"); + let cache = DriverBlobs::new(); + keep_driver_blob(&cache, 4, 1u64, COMPUTE_BLOB_MIN_DXIL, None, KEEP, || Some(b"full".to_vec())); + keep_driver_blob(&cache, 4, 2u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || Some(b"late".to_vec())); + let guard = cache.blobs.lock().unwrap(); + let (map, total) = guard.as_ref().unwrap(); + assert_eq!((map.len(), *total), (1, 4)); + assert_eq!(map[&1].as_slice(), b"full"); + drop(guard); + assert_eq!(load_bytes(&path).as_deref(), Some(b"late".as_slice())); + } + + #[test] + fn concurrent_same_key_builders_publish_only_the_reserved_result() { + use super::super::{keep_driver_blob, DriverBlobs, COMPUTE_BLOB_MIN_DXIL}; + use std::sync::atomic::{AtomicUsize, Ordering}; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-race-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let path = dir.join("same.pso"); + let cache = Arc::new(DriverBlobs::new()); + let entered = Arc::new(std::sync::Barrier::new(2)); + let release = Arc::new(std::sync::Barrier::new(2)); + let reads = Arc::new(AtomicUsize::new(0)); + let worker = { + let (cache, entered, release, reads, path) = (cache.clone(), entered.clone(), release.clone(), reads.clone(), path.clone()); + std::thread::spawn(move || keep_driver_blob(&cache, 0, 7u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || { + reads.fetch_add(1, Ordering::Relaxed); + entered.wait(); + release.wait(); + Some(b"reserved".to_vec()) + })) + }; + entered.wait(); + keep_driver_blob(&cache, 0, 7u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP * 2, || { + reads.fetch_add(1, Ordering::Relaxed); + Some(b"duplicate".to_vec()) + }); + release.wait(); + worker.join().unwrap(); + assert_eq!(reads.load(Ordering::Relaxed), 1); + assert_eq!(load_bytes(&path).as_deref(), Some(b"reserved".as_slice())); + // The cap refused RAM admission, but a later duplicate still cannot replace the + // generation whose own duration and bytes were published. + keep_driver_blob(&cache, 0, 7u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP * 3, + || Some(b"later".to_vec())); + assert_eq!(load_bytes(&path).as_deref(), Some(b"reserved".as_slice())); + } + + #[test] + fn different_memory_keys_cannot_race_the_same_disk_path() { + use super::super::{keep_driver_blob, DriverBlobs, COMPUTE_BLOB_MIN_DXIL}; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-path-race-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let path = dir.join("shared.pso"); + let cache = Arc::new(DriverBlobs::new()); + let entered = Arc::new(std::sync::Barrier::new(2)); + let release = Arc::new(std::sync::Barrier::new(2)); + let worker = { + let (cache, entered, release, path) = (cache.clone(), entered.clone(), release.clone(), path.clone()); + std::thread::spawn(move || keep_driver_blob(&cache, 0, 1u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || { + entered.wait(); + release.wait(); + Some(b"path owner".to_vec()) + })) + }; + entered.wait(); + keep_driver_blob(&cache, 0, 2u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, + || Some(b"contender".to_vec())); + release.wait(); + worker.join().unwrap(); + assert_eq!(load_bytes(&path).as_deref(), Some(b"path owner".as_slice())); + } + + #[test] + fn capture_failure_can_retry_and_rejection_can_replace_the_generation() { + use super::super::{keep_driver_blob, DriverBlobs, COMPUTE_BLOB_MIN_DXIL}; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-retry-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let path = dir.join("retry.pso"); + let cache = DriverBlobs::new(); + keep_driver_blob(&cache, 0, 9u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || None); + keep_driver_blob(&cache, 0, 9u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || Some(b"old".to_vec())); + assert_eq!(load_bytes(&path).as_deref(), Some(b"old".as_slice())); + cache.forget(9); + keep_driver_blob(&cache, 0, 9u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || Some(b"fresh".to_vec())); + assert_eq!(load_bytes(&path).as_deref(), Some(b"fresh".as_slice())); + } + + #[test] + fn a_duplicate_duration_is_not_charged_to_an_existing_blob() { + use super::super::{keep_driver_blob, DriverBlobs, COMPUTE_BLOB_MIN_DXIL}; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-duration-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let path = dir.join("duration.pso"); + let cache = DriverBlobs::new(); + keep_driver_blob(&cache, 16, 3u64, COMPUTE_BLOB_MIN_DXIL, None, KEEP, || Some(b"first".to_vec())); + keep_driver_blob(&cache, 16, 3u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP * 2, + || panic!("an existing blob must not be recaptured")); + assert!(!path.exists(), "another builder's duration must not persist the first builder's bytes"); + } + #[test] fn a_file_is_named_after_its_dxil_and_flags() { assert_eq!(name(b"abc", 0), name(b"abc", 0)); @@ -4908,9 +5060,62 @@ pub(crate) mod driver_cache { } } +/// A bounded set of driver blobs plus capture/publication ownership for duplicate builders. +struct DriverBlobs { + blobs: Mutex>>, usize)>>, + keeping: Mutex, HashSet)>>, +} + +impl DriverBlobs { + const fn new() -> Self { + Self { blobs: Mutex::new(None), keeping: Mutex::new(None) } + } + + fn get(&self, key: K) -> Option>> { + self.blobs.lock().unwrap().as_ref().and_then(|(map, _)| map.get(&key).cloned()) + } + + fn reserve(&self, key: K) -> bool { + if self.get(key).is_some() { + return false; + } + let mut guard = self.keeping.lock().unwrap(); + let (active, persisted) = guard.get_or_insert_with(|| (HashSet::new(), HashSet::new())); + !persisted.contains(&key) && active.insert(key) + } + + fn finish(&self, key: K, blob: Option>>, limit: usize, persisted: bool) { + if let Some(blob) = blob { + let mut guard = self.blobs.lock().unwrap(); + let (map, total) = guard.get_or_insert_with(|| (HashMap::new(), 0)); + if !map.contains_key(&key) && blob.len() <= limit.saturating_sub(*total) { + *total += blob.len(); + map.insert(key, blob); + } + } + let mut guard = self.keeping.lock().unwrap(); + let (active, stored) = guard.as_mut().unwrap(); + active.remove(&key); + if persisted { + stored.insert(key); + } + } + + fn forget(&self, key: K) { + if let Some((map, total)) = self.blobs.lock().unwrap().as_mut() { + if let Some(blob) = map.remove(&key) { + *total -= blob.len(); + } + } + if let Some((_, persisted)) = self.keeping.lock().unwrap().as_mut() { + persisted.remove(&key); + } + } +} + /// The driver's compiled form of translated compute programs (`GetCachedBlob`), /// by (DXIL hash, root signature, flags), up to `COMPUTE_BLOBS_MAX` bytes in all. -static COMPUTE_BLOBS: Mutex>>, usize)>> = Mutex::new(None); +static COMPUTE_BLOBS: DriverBlobs<(u64, usize, i32)> = DriverBlobs::new(); const COMPUTE_BLOBS_MAX: usize = 512 << 20; /// smaller programs compile in milliseconds: not kept const COMPUTE_BLOB_MIN_DXIL: usize = 16 << 10; @@ -4923,15 +5128,11 @@ fn compute_blob_key(dxil: &[u8], rs: usize, flags: i32) -> (u64, usize, i32) { } fn compute_blob(key: (u64, usize, i32)) -> Option>> { - COMPUTE_BLOBS.lock().unwrap().as_ref().and_then(|(m, _)| m.get(&key).cloned()) + COMPUTE_BLOBS.get(key) } fn forget_compute_blob(key: (u64, usize, i32)) { - if let Some((m, total)) = COMPUTE_BLOBS.lock().unwrap().as_mut() { - if let Some(b) = m.remove(&key) { - *total -= b.len(); - } - } + COMPUTE_BLOBS.forget(key); } #[cfg(test)] @@ -4995,16 +5196,16 @@ mod compute_blob_tests { other[999] = 8; assert_ne!(key, super::compute_blob_key(&other, 0x1000, 0)); { - let mut g = super::COMPUTE_BLOBS.lock().unwrap(); + let mut g = super::COMPUTE_BLOBS.blobs.lock().unwrap(); let (m, total) = g.get_or_insert_with(|| (super::HashMap::new(), 0)); m.insert(key, std::sync::Arc::new(vec![1, 2, 3])); *total += 3; } assert_eq!(super::compute_blob(key).as_deref().map(|v| v.len()), Some(3)); - let before = super::COMPUTE_BLOBS.lock().unwrap().as_ref().unwrap().1; + let before = super::COMPUTE_BLOBS.blobs.lock().unwrap().as_ref().unwrap().1; super::forget_compute_blob(key); assert!(super::compute_blob(key).is_none()); - assert_eq!(super::COMPUTE_BLOBS.lock().unwrap().as_ref().unwrap().1, before - 3); + assert_eq!(super::COMPUTE_BLOBS.blobs.lock().unwrap().as_ref().unwrap().1, before - 3); } } @@ -5031,51 +5232,39 @@ unsafe fn read_pso_cached_blob(pso: *mut c_void) -> Option> { (!bytes.is_empty()).then_some(bytes) } -/// The driver's blob of the PSO just built (works on both adopted title PSOs and raw PC compute -/// passes owned by `TwoPassPso`). -unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) { - if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || compute_blob(key).is_some() { +/// Offer the exact result and duration of one successful build to the bounded RAM cache and, +/// when slow, the disk cache. One same-key owner captures and publishes at a time: another +/// completed builder cannot charge its duration to these bytes or overwrite them afterward. +fn keep_driver_blob( + cache: &DriverBlobs, limit: usize, key: K, dxil_len: usize, + disk: Option<&std::path::Path>, took: std::time::Duration, read: impl FnOnce() -> Option>, +) { + if dxil_len < COMPUTE_BLOB_MIN_DXIL || !cache.reserve(key) { return; } - let Some(bytes) = read_pso_cached_blob(pso) else { return }; - let mut g = COMPUTE_BLOBS.lock().unwrap(); - let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if bytes.is_empty() || *total + bytes.len() > COMPUTE_BLOBS_MAX { + let keep_turn = disk.and_then(|path| driver_cache::KeepTurn::new(path, took)); + let Some(bytes) = read().filter(|bytes| !bytes.is_empty()) else { + cache.finish(key, None, limit, false); return; - } - *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); + }; + let blob = std::sync::Arc::new(bytes); + // Publish to disk before exposing the blob through RAM: a concurrent consumer cannot reject + // this generation while its staging file is being renamed into place. + let persisted = keep_turn.as_ref().is_some_and(|turn| turn.store(&blob)); + cache.finish(key, Some(blob), limit, persisted); } /// The driver's compiled form of translated graphics pipelines (`GetCachedBlob`), /// keyed by `(full_state_and_shader_hash, total_dxil_bytes)`, up to `GRAPHICS_BLOBS_MAX`. -static GRAPHICS_BLOBS: Mutex>>, usize)>> = Mutex::new(None); +static GRAPHICS_BLOBS: DriverBlobs<(u64, usize)> = DriverBlobs::new(); const GRAPHICS_BLOBS_MAX: usize = 256 << 20; fn graphics_blob(key: (u64, usize)) -> Option>> { - GRAPHICS_BLOBS.lock().unwrap().as_ref().and_then(|(m, _)| m.get(&key).cloned()) + GRAPHICS_BLOBS.get(key) } fn forget_graphics_blob(key: (u64, usize)) { - if let Some((m, total)) = GRAPHICS_BLOBS.lock().unwrap().as_mut() { - if let Some(b) = m.remove(&key) { - *total -= b.len(); - } - } -} - -unsafe fn keep_graphics_blob(key: (u64, usize), pso: *mut c_void, dxil_len: usize) { - if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || graphics_blob(key).is_some() { - return; - } - let Some(bytes) = read_pso_cached_blob(pso) else { return }; - let mut g = GRAPHICS_BLOBS.lock().unwrap(); - let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if bytes.is_empty() || *total + bytes.len() > GRAPHICS_BLOBS_MAX { - return; - } - *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); + GRAPHICS_BLOBS.forget(key); } /// Deterministic FNV-1a digest of every field in a translated PC graphics PSO (shaders, static @@ -5283,7 +5472,7 @@ mod graphics_blob_tests { |label, has_cached, f| { let hr = f(); attempts.push((label.to_string(), has_cached, hr)); - (hr, std::time::Duration::from_millis(1)) + (hr, std::time::Duration::from_millis(if has_cached { 300 } else { 2 })) }, |c| { // Driver rejects the stale CachedPSO, and accepts the fresh compile with rect GS intact. @@ -5300,6 +5489,8 @@ mod graphics_blob_tests { assert_eq!(stale_evicted, 1); assert!(!build.reused); assert!(build.cache_eligible, "fresh compile with rect GS intact should be cached"); + assert_eq!(build.built_in_driver, std::time::Duration::from_millis(2), + "a rejected cache lookup must not make a fast fresh build eligible for persistence"); assert!(!copy.GS.pShaderBytecode.is_null(), "stale cached blob must not strip rect GS"); assert!(copy.CachedPSO.pCachedBlob.is_null()); assert_eq!(attempts.len(), 2); @@ -5365,7 +5556,7 @@ mod graphics_blob_tests { struct GraphicsPsoBuild { hr: HRESULT, - in_driver: std::time::Duration, + built_in_driver: std::time::Duration, reused: bool, cache_eligible: bool, } @@ -5384,7 +5575,7 @@ fn create_graphics_pso_cached( // discarded first so the uncached retry compiles with `copy.GS` intact. let (hr, in_driver) = run("graphics", true, &mut || create(copy)); if hr >= 0 { - return GraphicsPsoBuild { hr, in_driver, reused: true, cache_eligible: false }; + return GraphicsPsoBuild { hr, built_in_driver: in_driver, reused: true, cache_eligible: false }; } on_stale_cache(); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); @@ -5392,7 +5583,7 @@ fn create_graphics_pso_cached( let dropped_rect_gs = rect_gs && copy.GS.pShaderBytecode.is_null(); return GraphicsPsoBuild { hr: retried, - in_driver: in_driver + took, + built_in_driver: took, reused: false, cache_eligible: retried >= 0 && !dropped_rect_gs, }; @@ -5401,7 +5592,7 @@ fn create_graphics_pso_cached( let dropped_rect_gs = rect_gs && copy.GS.pShaderBytecode.is_null(); GraphicsPsoBuild { hr, - in_driver, + built_in_driver: in_driver, reused: false, cache_eligible: hr >= 0 && !dropped_rect_gs, } @@ -5509,10 +5700,8 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const ); let hr = build.hr; if build.cache_eligible { - keep_graphics_blob(gkey, *ppv, bytes); - if let (Some(p), Some(b)) = (disk.as_deref(), graphics_blob(gkey)) { - driver_cache::keep(p, &b, build.in_driver); - } + keep_driver_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, gkey, bytes, disk.as_deref(), build.built_in_driver, + || read_pso_cached_blob(*ppv)); } else if build.reused && from_disk { driver_cache::note(true, loaded.take()); } @@ -6270,6 +6459,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let (mut hc, mut cin_driver) = driver_compile_identified("compute pass", tp.cs.len(), false, None, || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); + let mut cpersist_took = cin_driver; if hc < 0 && ccached.is_some() { forget_compute_blob(ckey); if cfrom_disk { @@ -6282,13 +6472,12 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: }); hc = retried; cin_driver += took; + cpersist_took = took; } let creused = hc >= 0 && ccached.is_some() && cdesc.CachedPSO.CachedBlobSizeInBytes != 0; if hc >= 0 && !creused && !compute.is_null() { - keep_compute_blob(ckey, compute, tp.cs.len()); - if let (Some(p), Some(b)) = (cdisk.as_deref(), compute_blob(ckey)) { - driver_cache::keep(p, &b, cin_driver); - } + keep_driver_blob(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, ckey, tp.cs.len(), cdisk.as_deref(), cpersist_took, + || read_pso_cached_blob(compute)); } else if creused && cfrom_disk { driver_cache::note(true, cloaded.take()); } From 0540a23c2c1a0b93c39de50d3c3bbe717b842e15 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:26:30 -0800 Subject: [PATCH 086/265] D3D12.X: retire released command queues after their final marker Own title queues from creation, atomically transition a registry-only queue to Retiring, exclude it from every internal signal and submission producer, and enqueue a final fence marker. Marker/API/worker failure pins the owner permanently. A worker sweeps exact completed generations, invalidates every audited raw-address cache, and only then drops the final registry owner. Pre-transition active snapshots delay retirement; retiring queues remain visible only to all-state ownership and diagnostics. No overlapping queue-retirement PR was found. Locally cross-checked with the GNU Windows target; Windows runtime and GPU execution remain untested here. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/device_x.rs | 1 + crates/xcl/src/hle/d3d12x/late_release.rs | 2 +- crates/xcl/src/hle/d3d12x/list_x.rs | 10 +- crates/xcl/src/hle/d3d12x/present.rs | 202 +++++++++++++++++--- crates/xcl/src/hle/d3d12x/real.rs | 4 +- crates/xcl/src/hle/d3d12x/sparse.rs | 2 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 3 + crates/xcl/src/hle/d3d12x/vram.rs | 2 +- 8 files changed, 196 insertions(+), 30 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 9bfae21fcf..ab1f7ab20c 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -78,6 +78,7 @@ pub(super) unsafe extern "system" fn create_command_queue_x(this: *mut c_void, d let d = if desc.is_null() { [0; 4] } else { pc_queue_desc(desc.read_unaligned()) }; let hr = real::dev_create_command_queue(this, d.as_ptr() as usize, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::present::track_queue(*ppv as usize); super::list_x::on_queue_create(*ppv as usize, this as usize, D3D12_COMMAND_LIST_TYPE(d[0] as i32)); } hr diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 3988302dbf..74ed1fbd0a 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -138,7 +138,7 @@ pub unsafe fn drain_known(seal_now: bool) { if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { return; } - let mut queues = super::present::known_queues_held(); + let mut queues = super::present::active_queues_held(); queues.extend(super::sparse::queue()); queues.extend(super::title_textures::upload_queues()); let gone = match HELD.lock().unwrap().as_mut() { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 095ced0d2d..64815e4ccc 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1109,6 +1109,11 @@ pub(super) fn on_queue_release(queue: usize) { scratch.fences.remove(&queue); scratch.collect_released(); drop(scratch); + stop_queue_submissions(queue); +} + +/// Stop non-owning internal users (notably `KickoffX`) from selecting a retiring queue. +pub(super) fn stop_queue_submissions(queue: usize) { LIVE_QUEUES.lock().unwrap().retain(|q| q.queue != queue); if let Some(m) = LISTS.lock().unwrap().as_mut() { for s in m.values_mut() { @@ -3818,6 +3823,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { }; (s.allocator, q) }; + let Some(queue_pin) = super::present::pin_queue_for_internal_work(queue) else { + return warn(&ERR, "KickoffX", format_args!("selected queue is retiring; deferring to Close + ExecuteCommandLists")); + }; let wrapper = super::title_list::wrapper_of(this); let standby = if let Some(wrapper) = wrapper { let Some(dev) = dev.as_ref() else { @@ -3878,7 +3886,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { record_deferred(wrapper); } - let q_raw = queue as *mut c_void; + let q_raw = queue_pin.as_raw(); super::title_textures::refresh(q_raw); type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index c8cca7b7c9..5c70cbc3a7 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -19,7 +19,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU64, Ordering}; -use std::sync::{Mutex, Once, OnceLock}; +use std::sync::{mpsc, Mutex, Once, OnceLock}; use std::time::{Duration, Instant}; use windows::core::{Interface, HSTRING, PCSTR, PCWSTR}; @@ -353,11 +353,12 @@ impl OwnedQueues { self.entries.iter().map(|entry| entry.owner.clone()).collect() } - fn active_id(&self, raw: usize) -> Option { + fn active_snapshot(&self) -> Vec { self.entries .iter() - .find(|entry| entry.id.raw == raw && matches!(&entry.state, QueueState::Active)) - .map(|entry| entry.id) + .filter(|entry| matches!(&entry.state, QueueState::Active)) + .map(|entry| entry.owner.clone()) + .collect() } fn begin_retiring(&mut self, id: QueueId) -> bool { @@ -369,6 +370,15 @@ impl OwnedQueues { true } + fn begin_retiring_if(&mut self, raw: usize, ready: impl FnOnce(&T) -> bool) -> Option<(QueueId, T)> { + let entry = self.entries.iter_mut().find(|entry| entry.id.raw == raw && matches!(&entry.state, QueueState::Active))?; + if !ready(&entry.owner) { + return None; + } + entry.state = QueueState::Retiring(Retiring::Preparing); + Some((entry.id, entry.owner.clone())) + } + fn mark_retiring(&mut self, id: QueueId, mark: M) -> Result<(), M> { let Some(entry) = self.entries.iter_mut().find(|entry| entry.id == id) else { return Err(mark) }; if !matches!(&entry.state, QueueState::Retiring(Retiring::Preparing)) { @@ -403,12 +413,12 @@ impl OwnedQueues { /// Remove entries whose marks were found complete outside the registry lock, and return /// their owners for release after unlocking. - fn sweep(&mut self, completed: &[QueueId]) -> Vec<(T, M)> { + fn sweep(&mut self, completed: &[QueueId]) -> Vec<(QueueId, T, M)> { let (mut kept, mut gone) = (Vec::with_capacity(self.entries.len()), Vec::new()); for entry in std::mem::take(&mut self.entries) { match entry { QueueEntry { id, owner, state: QueueState::Retiring(Retiring::Mark(mark)) } if completed.contains(&id) => { - gone.push((owner, mark)); + gone.push((id, owner, mark)); } entry => kept.push(entry), } @@ -421,17 +431,62 @@ impl OwnedQueues { /// Queues the title submitted work to. One process-lifetime owner per raw queue, as before. static QUEUES: Mutex> = Mutex::new(OwnedQueues::new()); +/// Keep the registry owner from queue creation onward, so non-owning users such as `KickoffX` +/// can pin it safely even before the title's first ordinary submission. +pub(super) unsafe fn track_queue(raw: usize) { + let mut queues = QUEUES.lock().unwrap(); + let _ = queues.ensure_with(raw, || ID3D12CommandQueue::from_raw_borrowed(&(raw as *mut c_void)).cloned()); +} + /// Strong snapshot of the queues the title submitted work to. Every AddRef happens while the /// registry is locked; callers own the returned references and drop them after the lock is gone. pub fn known_queues_held() -> Vec { QUEUES.lock().unwrap().snapshot() } +/// Strong snapshot of queues which can still accept internal signals/submissions. +pub(super) fn active_queues_held() -> Vec { + QUEUES.lock().unwrap().active_snapshot() +} + +pub(super) fn queue_accepts_internal_work(raw: usize) -> bool { + QUEUES + .lock() + .unwrap() + .entries + .iter() + .find(|entry| entry.id.raw == raw) + .is_none_or(|entry| matches!(&entry.state, QueueState::Active)) +} + +pub(super) unsafe fn pin_queue_for_internal_work(raw: usize) -> Option { + let queues = QUEUES.lock().unwrap(); + if let Some(entry) = queues.entries.iter().find(|entry| entry.id.raw == raw) { + return matches!(&entry.state, QueueState::Active).then(|| entry.owner.clone()); + } + ID3D12CommandQueue::from_raw_borrowed(&(raw as *mut c_void)).cloned() +} + #[allow(dead_code)] // Stage B API: wired to queue Release in a later unit. -pub(super) fn begin_queue_retirement(raw: usize) -> Option { - let mut queues = QUEUES.lock().unwrap(); - let id = queues.active_id(raw)?; - queues.begin_retiring(id).then_some(id) +pub(super) unsafe fn begin_queue_retirement(raw: usize) -> Option<(QueueId, ID3D12CommandQueue)> { + let this = raw as *mut c_void; + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(this, 1)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(this, 2)); + loop { + let mut queues = QUEUES.lock().unwrap(); + if !queues.entries.iter().any(|entry| entry.id.raw == raw && matches!(&entry.state, QueueState::Active)) { + return None; + } + let refs_with_probe = add_ref(this); + let retirement = queues.begin_retiring_if(raw, |_| refs_with_probe == 2); + drop(queues); + let refs = release(this); + if retirement.is_some() || refs != 1 { + return retirement; + } + // The last pre-transition snapshot dropped while the probe was held; retry because its + // hooked Release could not observe the registry-only count hidden by our probe. + } } #[allow(dead_code)] // Stage B API: wired to queue Release in a later unit. @@ -454,19 +509,19 @@ pub(super) fn queue_retirement_marks() -> Vec<(QueueId, QueueRetirementMark)> { } #[allow(dead_code)] // Stage B API: returned owners must be dropped after this function unlocks. -pub(super) fn sweep_queue_retirements(completed: &[QueueId]) -> Vec { +pub(super) fn sweep_queue_retirements(completed: &[QueueId]) -> Vec<(QueueId, ID3D12CommandQueue)> { let retired = { let mut queues = QUEUES.lock().unwrap(); queues.sweep(completed) }; - retired.into_iter().map(|(owner, _mark)| owner).collect() + retired.into_iter().map(|(id, owner, mark)| { + drop(mark); + (id, owner) + }).collect() } -/// Remove every cache keyed by this queue's raw address after its retirement mark completes and -/// before the final owner is released. No callee holds one subsystem lock while taking another. -#[allow(dead_code)] // Stage C seam: called by the retirement worker in a later unit. -pub(super) fn invalidate_queue_caches(id: QueueId) { - let raw = id.raw(); +fn quiesce_queue(raw: usize) { + super::list_x::stop_queue_submissions(raw); let candidate = { let mut candidate = CANDIDATE.lock().unwrap(); candidate.is_some_and(|(queue, _)| queue == raw).then(|| candidate.take().unwrap().1) @@ -475,6 +530,18 @@ pub(super) fn invalidate_queue_caches(id: QueueId) { let mut presenter = PRESENTER.lock().unwrap(); presenter.as_ref().is_some_and(|p| p.queue == raw).then(|| presenter.take().unwrap()) }; + if let Some(resource) = candidate { + unsafe { release(resource) }; + } + drop(presenter); +} + +/// Remove every cache keyed by this queue's raw address after its retirement mark completes and +/// before the final owner is released. No callee holds one subsystem lock while taking another. +#[allow(dead_code)] // Stage C seam: called by the retirement worker in a later unit. +pub(super) fn invalidate_queue_caches(id: QueueId) { + let raw = id.raw(); + quiesce_queue(raw); super::list_x::forget_queue(id); super::alloc_pool::forget_queue(id); super::cpu_writes::forget_queue(id); @@ -482,10 +549,68 @@ pub(super) fn invalidate_queue_caches(id: QueueId) { super::sparse::forget_queue(id); super::title_textures::forget_queue(id); super::vram::forget_queue(id); - if let Some(resource) = candidate { - unsafe { release(resource) }; +} + +fn retirement_worker() -> Option<&'static mpsc::Sender<()>> { + static WORKER: OnceLock>> = OnceLock::new(); + WORKER + .get_or_init(|| { + let (tx, rx) = mpsc::channel(); + std::thread::Builder::new() + .name("xcl-queue-retirement".to_string()) + .spawn(move || { + while rx.recv().is_ok() { + loop { + let marks = queue_retirement_marks(); + if marks.is_empty() { + break; + } + let completed: Vec<_> = marks + .iter() + .filter_map(|(id, mark)| (unsafe { mark.fence.GetCompletedValue() } >= mark.value).then_some(*id)) + .collect(); + drop(marks); + for (id, owner) in sweep_queue_retirements(&completed) { + invalidate_queue_caches(id); + drop(owner); + } + if completed.is_empty() { + std::thread::sleep(Duration::from_millis(10)); + } + } + } + }) + .ok() + .map(|_| tx) + }) + .as_ref() +} + +/// The hooked Release found that only the registry owner remains. Atomically verify that fact, +/// stop internal submissions, and place the final completion marker. Any marker failure pins the +/// registry owner permanently, so its raw address cannot be reused with stale cache state. +pub(super) unsafe fn retire_released_queue(raw: usize) { + let Some((id, queue)) = begin_queue_retirement(raw) else { return }; + quiesce_queue(raw); + let mark = (|| { + let mut dev: Option = None; + queue.GetDevice(&mut dev).ok()?; + let fence = dev?.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()?; + queue.Signal(&fence, 1).ok()?; + Some(QueueRetirementMark { fence, value: 1 }) + })(); + let Some(mark) = mark else { + let _ = fail_queue_retirement(id); + return; + }; + if let Err(mark) = mark_queue_retirement(id, mark) { + let _ = fail_queue_retirement(id); + drop(mark); + return; + } + if let Some(worker) = retirement_worker() { + let _ = worker.send(()); } - drop(presenter); } static EXECUTES: AtomicU64 = AtomicU64::new(0); @@ -497,10 +622,7 @@ pub fn activity() -> (u64, u64) { pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) { EXECUTES.fetch_add(1, Ordering::Relaxed); - { - let mut queues = QUEUES.lock().unwrap(); - let _ = queues.ensure_with(queue as usize, || ID3D12CommandQueue::from_raw_borrowed(&queue).cloned()); - } + track_queue(queue as usize); super::late_release::drain_known(false); if !enabled() || IN_PRESENT.with(|c| c.get()) || PRESENTX.load(Ordering::Relaxed) { return; @@ -1225,6 +1347,7 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, let Some((queue, res)) = *candidate else { return }; (queue, vec![(res, None)], guard) }; + let Some(_queue_pin) = pin_queue_for_internal_work(queue) else { return }; let resolved: Vec<(ID3D12Resource, D3D12_RESOURCE_DESC, [f32; 4])> = raw_planes .into_iter() .filter_map(|(res, rect)| { @@ -1703,7 +1826,7 @@ mod tests { assert!(registry.sweep(&[]).is_empty()); assert_eq!(registry.snapshot().iter().map(|v| **v).collect::>(), [1]); let gone = registry.sweep(&[id]); - assert_eq!(gone.iter().map(|(owner, mark)| (**owner, *mark)).collect::>(), [(1, 7)]); + assert_eq!(gone.iter().map(|(gone_id, owner, mark)| (*gone_id, **owner, *mark)).collect::>(), [(id, 1, 7)]); assert!(registry.snapshot().is_empty()); assert!(weak.upgrade().is_some(), "sweep dropped an owner instead of returning it"); drop(gone); @@ -1736,6 +1859,35 @@ mod tests { assert!(registry.begin_retiring(new)); } + #[test] + fn held_submission_snapshot_delays_atomic_retirement() { + let mut registry: OwnedQueues, u64> = OwnedQueues::new(); + let id = registry.ensure_with(0xA, || Some(std::sync::Arc::new(1))).unwrap(); + let held = registry.active_snapshot(); + assert!(registry.begin_retiring_if(0xA, |owner| std::sync::Arc::strong_count(owner) == 1).is_none()); + assert_eq!(registry.active_snapshot().len(), 1, "failed preflight changed Active state"); + drop(held); + let (retiring, token) = registry + .begin_retiring_if(0xA, |owner| std::sync::Arc::strong_count(owner) == 1) + .expect("registry became sole owner"); + assert_eq!(retiring, id); + assert_eq!(*token, 1); + } + + #[test] + fn preparing_queue_is_visible_but_cannot_repopulate_submission_cache() { + let mut registry: OwnedQueues, u64> = OwnedQueues::new(); + registry.ensure_with(0xA, || Some(std::sync::Arc::new(1))).unwrap(); + let (_, token) = registry.begin_retiring_if(0xA, |_| true).unwrap(); + assert_eq!(registry.snapshot().len(), 1, "retirement lost its diagnostic owner"); + assert!(registry.active_snapshot().is_empty(), "a post-transition producer acquired the queue"); + let mut cache = vec![0xA]; + cache.clear(); + cache.extend(registry.active_snapshot().into_iter().map(|_| 0xA)); + assert!(cache.is_empty(), "an inactive producer repopulated invalidated state"); + drop(token); + } + #[test] fn present_ring_overlaps_previous_frame_and_drains_cleanly() { let mut ring = PresentRing::new(PRESENT_SLOTS); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e624be31e9..ba6da47387 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7266,6 +7266,8 @@ unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { let n = f(this); if n == 0 { super::list_x::on_queue_release(this as usize); + } else if n == 1 { + super::present::retire_released_queue(this as usize); } n } @@ -7588,7 +7590,7 @@ pub fn drain_gpu() { unsafe { // a fence per queue (they finish in any order) let mut fences = Vec::new(); - for q in super::present::known_queues_held() { + for q in super::present::active_queues_held() { let submit = || { let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) .map_err(|e| fence::api_error(dev, "CreateFence", e))?; diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 9fe7a18640..cbbd82b11f 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1458,7 +1458,7 @@ impl State { unsafe fn sync_known_queues(&mut self) -> bool { let mut ok = true; - for q in super::present::known_queues_held() { + for q in super::present::active_queues_held() { if !self.queue_fences.contains_key(&(q.as_raw() as usize)) { ok &= self.note_queue(&q); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d4cb78d172..d7640091ff 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1108,6 +1108,9 @@ const IN_FLIGHT_BYTES: u64 = 512 << 20; unsafe fn title_queue_for(dev: &ID3D12Device, title: Option<&ID3D12CommandQueue>) -> Option { let q = title?; + if !super::present::queue_accepts_internal_work(q.as_raw() as usize) { + return None; + } if q.GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT { return None; } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index ec6c2c1d7a..8d39240c49 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1187,7 +1187,7 @@ unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueu out.push((key, q)); } }; - for q in super::present::known_queues_held() { + for q in super::present::active_queues_held() { add(q); } for q in extra.into_iter().cloned().chain(super::title_textures::upload_queues()).chain(super::sparse::queue()) { From 24ffb0e736824bb3c1cd5a1e07b300e607c575be Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:29:25 -0800 Subject: [PATCH 087/265] D3D12.X: retain metadata for GPU-owned textures Keep exact single-sample colour render-target and UAV layouts in the title texture table without scheduling CPU uploads. This preserves address generations and submitted-write provenance needed by a later, ordered reverse-layout readback path while rejecting layouts that require conversion or unsupported metadata handling.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/device_x.rs | 6 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 195 +++++++++++++++++++- 2 files changed, 189 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 9bfae21fcf..568c13fdc9 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1186,8 +1186,10 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, if super::vram::gpu_owned(flags) { if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, console_bytes, riid, ppv) { if hr >= 0 && !(*ppv).is_null() { - if let Some(bytes) = console_bytes { - super::title_textures::retire_overlapping(va as usize, bytes as usize); + if super::title_textures::register_gpu_owned(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)).is_err() { + if let Some(bytes) = console_bytes { + super::title_textures::retire_overlapping(va as usize, bytes as usize); + } } real::note_title_address(*ppv as usize, va as usize); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 17ac3667de..1c2f69f145 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -86,6 +86,9 @@ struct Entry { /// Last submitted GPU writer: one for the whole resource while uniform, otherwise one per /// subresource in D3D12 order. Empty until a tracked write is submitted. gpu_writers: Vec>, + /// CPU memory is the source of this texture and must be watched/uploaded. False for a + /// GPU-owned UAV/render target retained only for future coherency readback. + cpu_backed: bool, /// backed by shared `vram::Pages` tiles (overlapping placements share video memory) placed: bool, /// tiles were unmapped after a different-range placement superseded this texture @@ -336,6 +339,7 @@ static TEXTURES: Mutex = Mutex::new(Table::new()); static REFRESH: Mutex<()> = Mutex::new(()); static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0); static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static CPU_TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// cached `watch_ranges` keyed by `(sparse::mapped_gen, TEXTURES_GEN, graphics_reservations_gen)` static WATCH_CACHE: Mutex>)>> = Mutex::new(None); /// the queue uploads go to, per device @@ -344,7 +348,12 @@ static UPLOADS: AtomicU64 = AtomicU64::new(0); /// Number of textures kept in title memory and uploads done so far. pub fn counts() -> (usize, u64) { - (TEXTURES.lock().unwrap().by_res.len(), UPLOADS.load(Ordering::Relaxed)) + (TEXTURES_LEN.load(Ordering::Relaxed), UPLOADS.load(Ordering::Relaxed)) +} + +fn update_lengths(t: &Table) { + TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + CPU_TEXTURES_LEN.store(t.by_res.values().filter(|e| e.cpu_backed).count(), Ordering::Relaxed); } /// Whether a non-depth render target / UAV texture is small enough to be a CPU-filled glyph or UI @@ -411,6 +420,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, pending: true, gpu_written: false, gpu_writers: Vec::new(), + cpu_backed: true, placed: super::vram::is_placed_texture(res as usize), unmapped: false, generation: 0, @@ -419,7 +429,86 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, let mut t = TEXTURES.lock().unwrap(); let (delta, unmap_ptrs) = t.insert(res as usize, e); adjust_pending(delta); - TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + update_lengths(&t); + clone_resources(&unmap_ptrs) + }; + for r in &to_unmap { + super::vram::unmap_superseded(r); + } + TEXTURES_GEN.fetch_add(1, Ordering::Release); + Ok(()) +} + +/// Validate and retain the console layout of a GPU-owned UAV/render target. Depth/stencil, +/// MSAA, format-promoted resources, and multiple texel planes are deliberately unsupported: +/// their PC bytes cannot be tiled back into the console layout without conversion/metadata. +fn gpu_owned_layout(desc: &[u8; 0x38], pc: &D3D12_RESOURCE_DESC) -> Result { + let u = |o: usize| u32::from_le_bytes(desc[o..o + 4].try_into().unwrap()); + let flags = u(0x30); + if flags & 2 != 0 || flags & 5 == 0 { + return Err("not a supported colour render target / UAV".into()); + } + if (pc.Flags.0 as u32) & 5 == 0 { + return Err("not GPU-writable on the PC".into()); + } + if u(0x24) != 1 || pc.SampleDesc.Count != 1 { + return Err("a multisampled texture".into()); + } + if u(0x20) != pc.Format.0 as u32 { + return Err("a console format promoted on the PC".into()); + } + if u(0) != pc.Dimension.0 as u32 || u64::from_le_bytes(desc[0x10..0x18].try_into().unwrap()) != pc.Width || u(0x18) != pc.Height { + return Err("a PC resource shape different from its console layout".into()); + } + let tex = xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?; + let surfaces = tex.planes.iter().filter(|p| matches!(&p.kind, xg::PlaneKind::Surface(_))).count(); + let s = tex.texels().filter(|_| surfaces == 1).ok_or("not exactly one supported texel plane")?; + let layers = if s.depth > 0 { s.depth } else { s.array }; + if s.chain.levels.is_empty() + || pc.MipLevels as usize != s.chain.levels.len() + || pc.DepthOrArraySize as u32 != layers + || tex.size() == 0 + || usize::try_from(tex.size()).is_err() + { + return Err("console and PC subresources differ".into()); + } + Ok(tex) +} + +/// Register metadata for a successfully created GPU-owned placement. No COM reference is kept; +/// the resource's final Release removes this generation before its raw address can be reused. +pub(super) unsafe fn register_gpu_owned( + device: *mut c_void, + res: *mut c_void, + va: usize, + desc: &[u8; 0x38], + state: D3D12_RESOURCE_STATES, +) -> Result<(), String> { + let resource = ID3D12Resource::from_raw_borrowed(&res).ok_or("no resource")?; + let tex = gpu_owned_layout(desc, &resource.GetDesc())?; + let size = usize::try_from(tex.size()).map_err(|_| "texture size does not fit the title address space")?; + va.checked_add(size).ok_or("texture address range overflows")?; + let src = mirror_source(va); + let e = Entry { + device: device as usize, + va, + src, + in_gpu_view: crate::hle::kernelx::mirrors::source(va).is_some(), + tex: Arc::new(tex), + states: vec![state], + pending: false, + gpu_written: true, + gpu_writers: Vec::new(), + cpu_backed: false, + placed: true, + unmapped: false, + generation: 0, + }; + let to_unmap = { + let mut t = TEXTURES.lock().unwrap(); + let (delta, unmap_ptrs) = t.insert(res as usize, e); + adjust_pending(delta); + update_lengths(&t); clone_resources(&unmap_ptrs) }; for r in &to_unmap { @@ -468,7 +557,7 @@ fn recheck_gpu_view_sources() { /// `e`'s source again (a texture in a GPU view): when it changed, `e` reads the new one and is /// uploaded at the next submit. Whether it changed. fn recheck_source(e: &mut Entry) -> bool { - if !e.in_gpu_view { + if !e.cpu_backed || !e.in_gpu_view { return false; } let src = mirror_source(e.va); @@ -569,7 +658,7 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { unmap_ptrs.extend(u3); } adjust_pending(delta); - TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + update_lengths(&t); (retired, clone_resources(&unmap_ptrs)) }; for r in &to_unmap { @@ -588,7 +677,7 @@ pub fn forget(res: usize) { let mut t = TEXTURES.lock().unwrap(); let (removed, delta, remap_ptrs) = t.remove(res); adjust_pending(delta); - TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + update_lengths(&t); (removed, unsafe { clone_resources(&remap_ptrs) }) }; for r in &to_remap { @@ -741,7 +830,14 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { // write-watched regions) only when the set of textures, tiles, or reservations changed. let mut regions = u.watch_regions(); regions.extend(crate::hle::kernelx::graphics_reservations()); - let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().by_res.values().map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); + let mut wanted: Vec<(usize, usize)> = TEXTURES + .lock() + .unwrap() + .by_res + .values() + .filter(|e| e.cpu_backed) + .map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)) + .collect(); wanted.extend(super::sparse::mapped_ranges()); let computed = Arc::new(watch_ranges(®ions, wanted)); *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); @@ -795,7 +891,7 @@ unsafe fn take_written(base: usize, size: usize, buf: &mut [*mut c_void], dirty: unsafe fn refresh_once(queue: *mut c_void) { let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); - if !sparse && TEXTURES_LEN.load(Ordering::Relaxed) == 0 { + if !sparse && CPU_TEXTURES_LEN.load(Ordering::Relaxed) == 0 { return; } recheck_gpu_view_sources(); @@ -836,7 +932,7 @@ unsafe fn refresh_once(queue: *mut c_void) { }; let (mut with, mut without) = (0, 0); let mut shown = 0; - for e in t.by_res.values() { + for e in t.by_res.values().filter(|e| e.cpu_backed) { let c = content(e); if c > 0 { with += 1 } else { without += 1 } if c > 0 && shown < 4 { @@ -871,6 +967,9 @@ unsafe fn refresh_once(queue: *mut c_void) { t.by_res .iter_mut() .filter(|(_, e)| { + if !e.cpu_backed { + return false; + } if e.pending { return true; } @@ -1985,7 +2084,7 @@ mod tests { d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); d[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); let tex = Arc::new(xg::Texture::new(&d).unwrap()); - let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, gpu_writers: Vec::new(), placed: false, unmapped: false, generation: 0 }; + let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }; assert_eq!(e.src, cpu + 0x2_0000); assert!(!recheck_source(&mut e), "nothing changed yet"); assert_eq!(kernelx::MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, at); @@ -2043,6 +2142,44 @@ mod tests { const ALL: u32 = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; static TEST_LOCK: Mutex<()> = Mutex::new(()); + #[test] + fn gpu_owned_metadata_accepts_exact_colour_layouts_only() { + let desc = console_desc(3, 64, 64, 2, 3, 28, 0x105); + let with_flags = |mut d: [u8; 0x38], flags: u32| { + d[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + d + }; + let pc = |d: &[u8; 0x38]| unsafe { + std::ptr::read_unaligned(super::super::device_x::pc_resource_desc(d).as_ptr() as *const D3D12_RESOURCE_DESC) + }; + + let uav = with_flags(desc, 4); + let tex = gpu_owned_layout(&uav, &pc(&uav)).expect("single-plane UAV layout"); + assert_eq!(subresource_count(&tex), 6); + + let rt = with_flags(console_desc(3, 128, 128, 1, 1, 28, 0x105), 1); + let tex = gpu_owned_layout(&rt, &pc(&rt)).expect("render target with non-texel CMASK metadata"); + assert_eq!(tex.planes.len(), 2); + assert_eq!(subresource_count(&tex), 1); + + let depth = with_flags(desc, 2); + assert!(gpu_owned_layout(&depth, &pc(&depth)).is_err()); + let msaa = { + let mut d = with_flags(desc, 1); + d[0x24..0x28].copy_from_slice(&4u32.to_le_bytes()); + d + }; + assert!(gpu_owned_layout(&msaa, &pc(&msaa)).is_err()); + let promoted = with_flags(console_desc(3, 64, 64, 1, 1, 67, 0x105), 1); + assert_ne!(u32::from_le_bytes(promoted[0x20..0x24].try_into().unwrap()), pc(&promoted).Format.0 as u32); + assert!(gpu_owned_layout(&promoted, &pc(&promoted)).is_err()); + let planar = with_flags(console_desc(3, 64, 64, 1, 1, 45, 0x105), 1); + assert!(gpu_owned_layout(&planar, &pc(&planar)).is_err()); + let mut wrong_shape = pc(&uav); + wrong_shape.MipLevels -= 1; + assert!(gpu_owned_layout(&uav, &wrong_shape).is_err()); + } + /// One state while every subresource has it, one each while they differ. #[test] fn transitions_per_subresource_and_back_to_one_state() { @@ -2079,6 +2216,7 @@ mod tests { pending: false, gpu_written: false, gpu_writers: Vec::new(), + cpu_backed: true, placed: false, unmapped: false, generation: 0, @@ -2145,7 +2283,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, gpu_writers: Vec::new(), placed: false, unmapped: false, generation: 0 }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().by_res.get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); @@ -2328,6 +2466,7 @@ mod tests { pending, gpu_written: false, gpu_writers: Vec::new(), + cpu_backed: true, placed, unmapped: false, generation: 0, @@ -2719,6 +2858,40 @@ mod tests { assert_ne!(hm, he, "end-slice write must change fingerprint"); } + #[test] + fn gpu_owned_alias_generations_restore_the_previous_address_owner() { + let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); + let entry = |cpu_backed: bool| Entry { + device: 0, + va: 0x20_0000, + src: 0x20_0000, + in_gpu_view: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written: !cpu_backed, + gpu_writers: Vec::new(), + cpu_backed, + placed: !cpu_backed, + unmapped: false, + generation: 0, + }; + let mut t = Table::new(); + t.insert(1, entry(true)); + let cpu_generation = t.by_res[&1].generation; + t.insert(2, entry(false)); + let first_gpu_generation = t.by_res[&2].generation; + assert!(t.shadowed.contains_key(&1)); + t.insert(3, entry(false)); + assert!(t.shadowed.contains_key(&2)); + assert!(t.by_res[&3].generation > first_gpu_generation && first_gpu_generation > cpu_generation); + + t.remove(3); + assert!(t.by_res.contains_key(&2), "the previous exact-range GPU alias returns"); + t.remove(2); + assert!(t.by_res.get(&1).is_some_and(|e| e.cpu_backed && e.generation == cpu_generation)); + } + #[test] fn stream_recheck_schedule_catches_late_writes_and_resets_milestones() { let desc = console_desc(3, 256, 256, 1, 1, 28, 0x109); // 256 KiB RGBA8 @@ -2739,6 +2912,7 @@ mod tests { pending: false, gpu_written: false, gpu_writers: Vec::new(), + cpu_backed: true, placed: false, unmapped: false, generation: 0, @@ -2753,6 +2927,7 @@ mod tests { pending: false, gpu_written: true, gpu_writers: Vec::new(), + cpu_backed: true, placed: false, unmapped: false, generation: 0, From b271eba5a05580d10a5b92791b496f52ffc28c90 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:02:11 +0300 Subject: [PATCH 088/265] DXC: keep LINK_GATE open on OOM and forward opt/extra args to IDxcLinker::Link Fix two linked-compilation bugs in dxc.rs introduced alongside accessor-library linking (#174):\n\n1. Keep LINK_GATE open and propagate transient E_OUTOFMEMORY errors directly from compile_linked_or_fallback instead of permanently disabling linked compilation and falling back to the heavier compile_whole path under memory pressure. Deterministic non-OOM failures still close LINK_GATE once and fall back to compile_whole.\n2. Forward the shader optimization tier and caller extra arguments to IDxcLinker::Link, and reject library blobs whose length cannot be represented by the API.\n\nAdd unit tests for OOM gate retention, link argument boundaries, and live DXC argument forwarding.\n\nPart of #174\nPart of #1566\nPart of #1269\nPart of #1833\n\nAssisted-by: Google Antigravity (Gemini 4 Neon)\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/dxc.rs | 118 ++++++++++++++++++++++++++++--- 1 file changed, 107 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index dbf8fb24d7..68f0ee0f58 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -645,15 +645,11 @@ fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result // linear this way (`emit::linked_form`). Anything wrong with it: as one program, as before. if profile.starts_with("cs_") && linking() { if let Some((program, library)) = super::emit::linked_form(src, LINK_MIN_ACCESSES) { - match compile_linked(&program, &library, entry, profile, extra) { - Ok(dxil) => return Ok(dxil), - Err(e) => { - // the same DXC fails the same way for the next program: stop trying - if LINK_GATE.close() { - crate::xlog_warn!("DXC: a program could not be linked with its memory accessors, compiled whole, and no more programs are linked: {e}"); - } - } - } + return compile_linked_or_fallback( + &LINK_GATE, + || compile_linked(&program, &library, entry, profile, extra), + || compile_whole(src, entry, profile, extra), + ); } } compile_whole(src, entry, profile, extra) @@ -684,6 +680,47 @@ impl LinkGate { static LINK_GATE: LinkGate = LinkGate::new(); +fn is_oom_error(err: &str) -> bool { + let lower = err.to_ascii_lowercase(); + lower.contains("0x8007000e") || lower.contains("e_outofmemory") +} + +/// Try `linked()` while `gate` is open; transient OOM propagates without closing `gate` or +/// falling back to the heavier `whole()`, while deterministic failures close `gate` and retry whole. +fn compile_linked_or_fallback( + gate: &LinkGate, + linked: impl FnOnce() -> Result, String>, + whole: impl FnOnce() -> Result, String>, +) -> Result, String> { + if !gate.open() { + return whole(); + } + match linked() { + Ok(dxil) => Ok(dxil), + Err(e) if is_oom_error(&e) => Err(e), + Err(e) => { + // the same DXC fails the same way for the next program: stop trying + if gate.close() { + crate::xlog_warn!("DXC: a program could not be linked with its memory accessors, compiled whole, and no more programs are linked: {e}"); + } + whole() + } + } +} + +fn link_opt_args<'a>(src_len: usize, extra: &'a [&'a str]) -> Vec<&'a str> { + let mut args = Vec::with_capacity(extra.len() + 3); + if !extra.iter().any(|a| a.starts_with("-O") || *a == "-Od") { + if src_len > UNOPTIMISED_ABOVE { + args.extend(["-O0", "-opt-disable", "debug-nops"]); + } else if src_len > 1024 * 1024 { + args.push("-O1"); + } + } + args.extend(extra.iter().copied()); + args +} + /// `XCL_LINK_MEM=0`: every program is compiled whole (into the same cache: compare with /// another `XCL_DXIL_CACHE`). fn linking() -> bool { @@ -708,6 +745,7 @@ fn kept_once(map: &Mutex>>> /// Compile `program` and `library` (its memory accessors, kept once compiled) as libraries and /// link them to `profile`. fn compile_linked(program: &str, library: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { + let program_src_len = program.len(); let model = profile.split_once('_').map_or("6_6", |(_, m)| m); let lib = format!("lib_{model}"); let accessors = { @@ -724,17 +762,20 @@ fn compile_linked(program: &str, library: &str, entry: &str, profile: &str, extr } Ok(p) }; + let link_args_w: Vec> = link_opt_args(program_src_len, extra).into_iter().map(crate::util::wide).collect(); + let link_ptrs: Vec = link_args_w.iter().map(|a| PCWSTR(a.as_ptr())).collect(); unsafe { let linker = IDxcLinker::from_raw(instance(&CLSID_DxcLinker, &IDxcLinker::IID)?); let utils = IDxcUtils::from_raw(instance(&CLSID_DxcUtils, &IDxcUtils::IID)?); let names = [crate::util::wide("program"), crate::util::wide("accessors")]; for (name, dxil) in names.iter().zip([&program, &*accessors]) { - let blob = utils.CreateBlob(dxil.as_ptr() as *const c_void, dxil.len() as u32, DXC_CP(0)).map_err(|e| format!("CreateBlob: {e}"))?; + let len = u32::try_from(dxil.len()).map_err(|_| "DXIL library larger than 4 GiB".to_string())?; + let blob = utils.CreateBlob(dxil.as_ptr() as *const c_void, len, DXC_CP(0)).map_err(|e| format!("CreateBlob: {e}"))?; linker.RegisterLibrary(PCWSTR(name.as_ptr()), &blob).map_err(|e| format!("RegisterLibrary: {e}"))?; } let (entry, profile) = (crate::util::wide(entry), crate::util::wide(profile)); let r = linker - .Link(PCWSTR(entry.as_ptr()), PCWSTR(profile.as_ptr()), &names.each_ref().map(|n| PCWSTR(n.as_ptr())), None) + .Link(PCWSTR(entry.as_ptr()), PCWSTR(profile.as_ptr()), &names.each_ref().map(|n| PCWSTR(n.as_ptr())), (!link_ptrs.is_empty()).then_some(link_ptrs.as_slice())) .map_err(|e| format!("Link: {e}"))?; output(r.GetStatus(), r.GetErrorBuffer(), r.GetResult()) } @@ -1788,6 +1829,61 @@ mod accessor_library_tests { assert!(!gate.open()); assert!(!gate.close()); } + + #[test] + fn compile_linked_or_fallback_keeps_gate_open_on_oom() { + let gate = LinkGate::new(); + for oom in ["dxc (0x8007000E): out of memory", "Link: HRESULT(0x8007000e)", "CreateBlob: E_OUTOFMEMORY"] { + let mut whole_ran = false; + let err = compile_linked_or_fallback(&gate, || Err(oom.into()), || { whole_ran = true; Ok(vec![1]) }).unwrap_err(); + assert_eq!(err, oom); + assert!(gate.open() && !whole_ran, "OOM must keep LinkGate open and skip whole fallback: {oom}"); + } + // Deterministic non-OOM failure closes the gate and falls back to whole; subsequent calls skip linked. + let mut whole_runs = 0usize; + let ok = compile_linked_or_fallback(&gate, || Err("dxc: unsupported WaveSize on library".into()), || { whole_runs += 1; Ok(vec![42]) }).unwrap(); + assert_eq!((ok, gate.open(), whole_runs), (vec![42], false, 1)); + let ok = compile_linked_or_fallback(&gate, || panic!("linked must not run once gate is closed"), || { whole_runs += 1; Ok(vec![99]) }).unwrap(); + assert_eq!((ok, whole_runs), (vec![99], 2)); + } + + #[test] + fn link_opt_args_selects_tier_and_preserves_extra() { + assert_eq!(link_opt_args(1024 * 1024, &[]), Vec::<&str>::new()); + assert_eq!(link_opt_args(1024 * 1024 + 1, &[]), vec!["-O1"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE, &[]), vec!["-O1"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &[]), vec!["-O0", "-opt-disable", "debug-nops"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &["-O2"]), vec!["-O2"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &["-Od"]), vec!["-Od"]); + assert_eq!(link_opt_args(512, &["-Gis"]), vec!["-Gis"]); + assert_eq!(link_opt_args(1024 * 1024 + 1, &["-Gis"]), vec!["-O1", "-Gis"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &["-Gis"]), vec!["-O0", "-opt-disable", "debug-nops", "-Gis"]); + } + + #[test] + fn compile_linked_forwards_opt_and_extra_args_to_dxc_linker() { + if location().is_err() { + return super::super::runner::skip_test("no DXC"); + } + let library = "RWByteAddressBuffer res : register(u0);\nexport uint helper_add(uint a, uint b) { return a + b; }\n"; + let program = "RWByteAddressBuffer res : register(u0);\nuint helper_add(uint a, uint b);\n[shader(\"compute\")]\n[numthreads(64, 1, 1)]\nvoid main(uint gi : SV_GroupIndex) {\n float x = asfloat(res.Load(gi * 4u));\n float y = (x + 1.0) - 1.0;\n res.Store(gi * 4u, helper_add(asuint(y), gi));\n}\n"; + let run = |args: &[&str]| -> String { + let dxil = compile_linked(program, library, "main", "cs_6_6", args).unwrap_or_else(|e| panic!("args={args:?}: {e}")); + super::super::super::dxil::validate::validate(&dxil).unwrap_or_else(|e| panic!("validate args={args:?}: {e}")); + disassemble(&dxil).unwrap_or_else(|e| panic!("disasm args={args:?}: {e}")) + }; + let d_def = run(&[]); + assert!(!d_def.contains("fadd "), "default link should optimize (x + 1) - 1 away:\n{d_def}"); + let _ = run(&["-O1"]); + let d_o0 = run(&["-O0", "-opt-disable", "debug-nops"]); + assert!(d_o0.contains("fadd fast float") && d_o0.contains("mul i32 ") && !d_o0.contains("dx.op.nop"), "-O0 link must skip -O3 folding and debug-nops:\n{d_o0}"); + let d_gis = run(&["-Gis"]); + assert!(d_gis.contains("fadd float ") && !d_gis.contains("fadd fast "), "-Gis must keep strict IEEE fadd:\n{d_gis}"); + // Also check auto -O1 / -O0 when program.len() > 1 MiB (while library is small). + let big_prog = format!("{program}// {}\n", "a".repeat(1024 * 1024 + 16)); + let dxil_big = compile_linked(&big_prog, library, "main", "cs_6_6", &[]).unwrap(); + super::super::super::dxil::validate::validate(&dxil_big).unwrap(); + } } #[cfg(test)] From 2d8b8295a72f8e4f29ff09298d4ad7d734b0d769 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:02:47 +0100 Subject: [PATCH 089/265] D3D12.X: forget a command list before the runtime frees it cl_release dropped XCL state keyed by a PC command list address only after the runtime's final Release had freed the list. A list created on another thread could immediately reuse that address and lose its bind state, allocator, last submit, and DRED marks. Probe the final reference and forget keyed state before the freeing Release, matching the established resource-release pattern.\n\nA fake list whose Release reuses its address immediately verifies the new list keeps its state.\n\nAssisted-by: Claude Code (Claude Opus 5.5)\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 75 ++++++++++++++++++++++++++++--- 1 file changed, 70 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e6b9e0ec30..dd82d2f47f 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7439,17 +7439,30 @@ unsafe extern "system" fn cl_execute_indirect( f(this, sig, max_count, arg_buf, arg_off, cnt_buf, cnt_off); } +/// The last reference: what XCL keeps by the list's address goes before the runtime frees it, +/// as a list created on another thread can get the address at once. (Two last-but-one releases +/// at once miss each other here; the list's state then goes after it, as before.) unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let add: RefFn = std::mem::transmute(orig_fn(this, 1)); + let f: RefFn = std::mem::transmute(orig_fn(this, 2)); + let last = add(this) == 2; + f(this); + if last { + forget_command_list(this); + } let n = f(this); - if n == 0 { - super::list_x::on_release(this as usize); - super::bind::forget(this); - super::dred::forget_list(this); + if n == 0 && !last { + forget_command_list(this); } n } +fn forget_command_list(list: *mut c_void) { + super::list_x::on_release(list as usize); + super::bind::forget(list); + super::dred::forget_list(list); +} + unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); @@ -9451,3 +9464,55 @@ void main() { } } +#[cfg(test)] +mod list_release_tests { + use super::*; + + #[repr(C)] + struct FakeList { + vtable: usize, + refs: u32, + } + + const ALLOC: usize = 0x7E57_A130; + const PSO: usize = 0x7E57_D002; + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let l = &mut *(this as *mut FakeList); + l.refs += 1; + l.refs + } + + // the runtime frees the list, and a list created on another thread gets its address at once + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let l = &mut *(this as *mut FakeList); + l.refs -= 1; + if l.refs == 0 { + super::super::bind::reset(this, ALLOC, PSO); + super::super::alloc_pool::created_on(this as usize, ALLOC, 0); + } + l.refs + } + + #[test] + fn a_new_list_at_a_released_lists_address_keeps_its_state() { + let pc = [0, add_ref as usize, release as usize]; + let ext = [pc.as_ptr() as usize, 0]; + let mut list = FakeList { vtable: ext.as_ptr() as usize + 8, refs: 2 }; + let this = &mut list as *mut FakeList as *mut c_void; + super::super::bind::reset(this, ALLOC + 0x10, PSO + 0x10); + let (kept, n) = unsafe { + assert_eq!(cl_release(this), 1); + (super::super::bind::tracked_pso(this), cl_release(this)) + }; + let pso = super::super::bind::tracked_pso(this); + let backing = super::super::alloc_pool::recording_backing_for_test(this as usize); + super::super::bind::forget(this); + super::super::alloc_pool::forget_list(this as usize); + assert_eq!(kept, PSO + 0x10, "another reference is left"); + assert_eq!(n, 0); + assert_eq!(pso, PSO, "the new list's bind state"); + assert_eq!(backing, Some(ALLOC), "the new list's allocator"); + } +} + From 12b1b7864048dbbde15e99f12fd846152774cf3b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:33:43 -0800 Subject: [PATCH 090/265] D3D12.X: retire sparse queue fences without owning queues Replace sparse tile quarantine's process-lifetime command-queue references with temporary active-queue snapshots and independently owned completion fences. Include installed central retirement markers, wait through the short Preparing state, and fail closed when retirement cannot provide a trustworthy completion source.\n\nPrune raw queue keys only through the exact Stage C retirement callback before address reuse; in-flight batches retain their own fence clones.\n\nAdapted from #2638 after central queue retirement was active.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/present.rs | 34 +++++- crates/xcl/src/hle/d3d12x/sparse.rs | 162 ++++++++++++++++++--------- 2 files changed, 141 insertions(+), 55 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 5c70cbc3a7..6904a67267 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -19,7 +19,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU64, Ordering}; -use std::sync::{mpsc, Mutex, Once, OnceLock}; +use std::sync::{mpsc, Condvar, Mutex, Once, OnceLock}; use std::time::{Duration, Instant}; use windows::core::{Interface, HSTRING, PCSTR, PCWSTR}; @@ -430,6 +430,7 @@ impl OwnedQueues { /// Queues the title submitted work to. One process-lifetime owner per raw queue, as before. static QUEUES: Mutex> = Mutex::new(OwnedQueues::new()); +static QUEUE_STATE_CHANGED: Condvar = Condvar::new(); /// Keep the registry owner from queue creation onward, so non-owning users such as `KickoffX` /// can pin it safely even before the title's first ordinary submission. @@ -449,6 +450,32 @@ pub(super) fn active_queues_held() -> Vec { QUEUES.lock().unwrap().active_snapshot() } +pub(super) struct QueueCompletionSnapshot { + pub(super) active: Vec, + pub(super) retiring: Vec<(ID3D12Fence, u64)>, + pub(super) blocked: bool, +} + +/// Completion sources for work submitted before this instant. Active queue owners prevent their +/// retirement transition until callers signal them; installed retirement marks cover queues which +/// already transitioned. Preparing is allowed to install its mark; failed retirement has no +/// trustworthy completion source and makes the snapshot fail-closed. +pub(super) fn queue_completion_snapshot() -> QueueCompletionSnapshot { + let mut queues = QUEUES.lock().unwrap(); + while queues.entries.iter().any(|entry| matches!(&entry.state, QueueState::Retiring(Retiring::Preparing))) { + queues = QUEUE_STATE_CHANGED.wait(queues).unwrap(); + } + let mut out = QueueCompletionSnapshot { active: Vec::new(), retiring: Vec::new(), blocked: false }; + for entry in &queues.entries { + match &entry.state { + QueueState::Active => out.active.push(entry.owner.clone()), + QueueState::Retiring(Retiring::Mark(mark)) => out.retiring.push((mark.fence.clone(), mark.value)), + QueueState::Retiring(Retiring::Preparing | Retiring::Failed) => out.blocked = true, + } + } + out +} + pub(super) fn queue_accepts_internal_work(raw: usize) -> bool { QUEUES .lock() @@ -495,12 +522,15 @@ pub(super) fn mark_queue_retirement(id: QueueId, mark: QueueRetirementMark) -> R let mut queues = QUEUES.lock().unwrap(); queues.mark_retiring(id, mark) }; + QUEUE_STATE_CHANGED.notify_all(); result } #[allow(dead_code)] // Stage B API: wired to queue Release in a later unit. pub(super) fn fail_queue_retirement(id: QueueId) -> bool { - QUEUES.lock().unwrap().fail_retiring(id) + let failed = QUEUES.lock().unwrap().fail_retiring(id); + QUEUE_STATE_CHANGED.notify_all(); + failed } #[allow(dead_code)] // Stage B API: completion is checked and owners are released in a later unit. diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index cbbd82b11f..bec8a1bcf3 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -237,8 +237,9 @@ struct State { parked: FxHashMap, /// unmapped parked pool tiles awaiting `self.queue` and in-flight title queues before entering `free` quarantined: VecDeque, - /// per-title-queue fences used to mark in-flight GPU work (`note_queue`) - queue_fences: FxHashMap, + /// per-title-queue fences used to mark in-flight GPU work; raw keys are removed only by + /// exact-generation queue retirement before that queue's address can be reused + queue_fences: FxHashMap, /// placed buffers → the pool tiles they use buffers: FxHashMap>, /// reused tiles / decommitted partial pages to clear: (address, bytes) @@ -418,14 +419,22 @@ static STATE: Mutex> = Mutex::new(None); /// (a list's `Reset`, with `XCL_DRED=1` on every start): the two then waited for each other. static QUEUE: Mutex> = Mutex::new(None); +fn remove_queue_fence(fences: &mut FxHashMap, raw: usize) -> Option<(F, u64)> { + fences.remove(&raw) +} + +fn initial_quarantine_marks(own: (F, u64), retiring: &[(F, u64)], blocked: bool) -> Option> { + (!blocked).then(|| std::iter::once(own).chain(retiring.iter().cloned()).collect()) +} + /// Remove raw queue-address state before a retired queue's final owner is released. Retired tile -/// batches own fence clones independently; the cached queue and fence drop after unlocking. +/// batches own fence clones independently; the cached fence drops after unlocking. pub(super) fn forget_queue(id: super::present::QueueId) { let gone = { let mut state = STATE.lock().unwrap(); state.as_mut().and_then(|state| { state.waited.remove(&id.raw()); - state.queue_fences.remove(&id.raw()) + remove_queue_fence(&mut state.queue_fences, id.raw()) }) }; drop(gone); @@ -1269,7 +1278,6 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz } let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; - s.note_queue(queue); let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); if filtered.is_empty() { return; @@ -1437,52 +1445,47 @@ impl State { } } - unsafe fn note_queue(&mut self, q: &ID3D12CommandQueue) -> bool { - let key = q.as_raw() as usize; - if self.queue_fences.contains_key(&key) { - return true; - } - // Ignore queues belonging to a different device (e.g. isolated unit tests). - let mut qdev: Option = None; - if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self.dev.as_raw()) { - return true; - } - match self.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { - Ok(fence) => { - self.queue_fences.insert(key, (q.clone(), fence, 0)); - true - } - Err(_) => false, - } - } - - unsafe fn sync_known_queues(&mut self) -> bool { - let mut ok = true; - for q in super::present::active_queues_held() { - if !self.queue_fences.contains_key(&(q.as_raw() as usize)) { - ok &= self.note_queue(&q); - } - } - ok - } - - unsafe fn quarantine_tiles(&mut self, tiles: Vec<(u32, u32)>) { + unsafe fn quarantine_tiles_for( + &mut self, + tiles: Vec<(u32, u32)>, + queues: &[ID3D12CommandQueue], + retiring: &[(ID3D12Fence, u64)], + blocked: bool, + ) { if tiles.is_empty() { return; } - let mut ok = self.sync_known_queues(); - let mut marks = Vec::with_capacity(1 + self.queue_fences.len()); - marks.push((self.fence.clone(), self.value)); - if ok { - for (q, fence, val) in self.queue_fences.values_mut() { - let next = *val + 1; - if q.Signal(&*fence, next).is_ok() { - *val = next; - marks.push((fence.clone(), next)); - } else { - ok = false; - break; - } + let mut marks = initial_quarantine_marks((self.fence.clone(), self.value), retiring, blocked).unwrap_or_default(); + let mut ok = !blocked; + let mut seen = Vec::with_capacity(queues.len()); + marks.reserve(queues.len()); + for q in queues.iter().filter(|_| ok) { + let key = q.as_raw() as usize; + if key == self.queue.as_raw() as usize || seen.contains(&key) { + continue; + } + let mut qdev: Option = None; + if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self.dev.as_raw()) { + continue; + } + seen.push(key); + let entry = match self.queue_fences.entry(key) { + std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::hash_map::Entry::Vacant(entry) => match self.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { + Ok(fence) => entry.insert((fence, 0)), + Err(_) => { + ok = false; + break; + } + }, + }; + let next = entry.1 + 1; + if q.Signal(&entry.0, next).is_ok() { + entry.1 = next; + marks.push((entry.0.clone(), next)); + } else { + ok = false; + break; } } self.quarantined.push_back(RetiredTiles { tiles, marks: ok.then_some(marks) }); @@ -1511,6 +1514,29 @@ impl State { /// Pools left all free are not retired here: callers do that (`retire_free_pools`) unless /// they take a tile right away. unsafe fn flush_parked(&mut self) -> bool { + self.flush_parked_with(None) + } + + unsafe fn flush_parked_with(&mut self, extra: Option<&ID3D12CommandQueue>) -> bool { + if self.parked.is_empty() { + return false; + } + let mut completion = super::present::queue_completion_snapshot(); + if let Some(queue) = extra.filter(|queue| { + super::present::queue_accepts_internal_work(queue.as_raw() as usize) + && !completion.active.iter().any(|active| active.as_raw() == queue.as_raw()) + }) { + completion.active.push(queue.clone()); + } + self.flush_parked_for(&completion.active, &completion.retiring, completion.blocked) + } + + unsafe fn flush_parked_for( + &mut self, + queues: &[ID3D12CommandQueue], + retiring: &[(ID3D12Fence, u64)], + blocked: bool, + ) -> bool { if self.parked.is_empty() { return false; } @@ -1529,7 +1555,7 @@ impl State { self.unmap_tiles(&r, b, &ts); } self.signal(); - self.quarantine_tiles(tiles); + self.quarantine_tiles_for(tiles, queues, retiring, blocked); true } } @@ -1571,9 +1597,8 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: let t0 = std::time::Instant::now(); let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; - s.note_queue(queue); // the title's work sees what was decommitted unmapped, as it was - let flushed = s.flush_parked(); + let flushed = s.flush_parked_with(Some(queue)); let drained = s.drain_quarantined(); if flushed || drained { s.retire_free_pools(); @@ -1766,6 +1791,38 @@ mod tests { assert!(answered, "queue() waited for the sparse state's lock"); } + #[test] + fn exact_retirement_forgets_cache_but_inflight_batch_keeps_its_fence() { + use std::sync::Arc; + let old = Arc::new(7u32); + let mut fences = FxHashMap::default(); + fences.insert(0xA, (old.clone(), 3)); + let batch_mark = fences[&0xA].0.clone(); + + assert!(fences.contains_key(&0xA), "marker failure must leave the cache pinned"); + let gone = remove_queue_fence(&mut fences, 0xA).expect("exact retirement callback"); + assert!(fences.is_empty() && Arc::ptr_eq(&gone.0, &batch_mark)); + drop(gone); + drop(old); + assert_eq!(Arc::strong_count(&batch_mark), 1, "cache removal invalidated an in-flight batch mark"); + + let replacement = Arc::new(9u32); + fences.insert(0xA, (replacement.clone(), 1)); + assert!(!Arc::ptr_eq(&batch_mark, &fences[&0xA].0), "reused raw address kept the retired generation's fence"); + } + + #[test] + fn quarantine_uses_installed_retirement_marks_and_fails_closed_without_one() { + use std::sync::Arc; + let own = Arc::new(1u32); + let retired = Arc::new(2u32); + let marks = initial_quarantine_marks((own.clone(), 3), &[(retired.clone(), 4)], false).unwrap(); + assert_eq!(marks.iter().map(|(_, value)| *value).collect::>(), [3, 4]); + drop(retired); + assert_eq!(Arc::strong_count(&marks[1].0), 1, "batch did not own the retirement marker"); + assert!(initial_quarantine_marks((own, 3), &[(marks[1].0.clone(), 4)], true).is_none(), "Preparing/Failed reused tiles without a completion source"); + } + /// A block freed on one thread while another allocates: its address goes back to the /// windows only once it is decommitted (released first, the decommit came after another /// thread had the same address again: that thread's writes faulted). @@ -2393,7 +2450,6 @@ mod tests { unsafe { let (base, mut s) = test_state_with_reserved(2); let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); - assert!(s.note_queue(&title_q)); s.commit_range(base, TILE); let tile = s.mapped[&base].pool; @@ -2405,7 +2461,7 @@ mod tests { s.decommit_range(base, TILE); s.free.clear(); - assert!(s.flush_parked()); + assert!(s.flush_parked_for(std::slice::from_ref(&title_q), &[], false)); // Even after `s.queue` finishes `unmap_tiles`, `title_q` is still gated behind `title_gate`. s.wait_for(s.value); From b7af00962f7be33c5bf86fd341ddced0bc345c56 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:34:37 -0800 Subject: [PATCH 091/265] D3D12.X: add bounded reverse texture layout conversion Add a pure CPU helper that validates one exact D3D12 readback footprint and tiles its logical rows back into the matching XG subresource. It handles arrays, volumes, mip edges, and block formats while rejecting metadata planes, format conversions, malformed footprints, arithmetic overflow, allocation failure, and short buffers.\n\nThis is the conversion-only stage for ordered GPU-owned texture copyback; it performs no queue, COM, synchronization, or title-memory work.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 205 ++++++++++++++++++++ 1 file changed, 205 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index e6bce7b469..8479e120c5 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1751,6 +1751,127 @@ unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { out } +/// The bounded part of a mapped D3D12 readback buffer which holds one subresource. +/// `width`, `height`, and `depth` are texels (not format blocks); `size` bounds all reads. +#[derive(Clone, Copy, Debug)] +#[allow(dead_code)] // Stage 3 seam; queue/readback activation is a later change. +pub(super) struct ReadbackFootprint { + pub offset: usize, + pub size: usize, + pub row_pitch: usize, + pub width: u32, + pub height: u32, + pub depth: u32, + pub format: u32, +} + +#[derive(Debug, PartialEq, Eq)] +#[allow(dead_code)] // Stage 3 seam; queue/readback activation is a later change. +pub(super) enum ReverseLayoutError { + UnsupportedLayout, + Format, + Subresource, + Dimensions, + RowPitch, + Footprint, + Destination, +} + +/// Put one exact PC readback footprint back into its XG-tiled subresource. This is deliberately +/// pure: callers own both byte slices, and no resource, queue, title address, or COM object is +/// touched. Metadata planes and format conversions are not reconstructible and fail closed. +#[allow(dead_code)] // Stage 3 seam; queue/readback activation is a later change. +pub(super) fn reverse_layout_subresource( + tex: &xg::Texture, + format: u32, + subresource: u32, + footprint: ReadbackFootprint, + readback: &[u8], + console: &mut [u8], +) -> Result<(), ReverseLayoutError> { + if tex.main != 0 || tex.planes.len() != 1 { + return Err(ReverseLayoutError::UnsupportedLayout); + } + let (surface, plane_offset) = tex.plane_surface(0).ok_or(ReverseLayoutError::UnsupportedLayout)?; + let (elem_log2, side) = xg::element(format).ok_or(ReverseLayoutError::Format)?; + if footprint.format != format || surface.bpe != 1u32 << elem_log2 || surface.side != side { + return Err(ReverseLayoutError::Format); + } + let mips = surface.chain.levels.len(); + let (mip, slice) = if surface.depth > 0 { + let mip = usize::try_from(subresource).map_err(|_| ReverseLayoutError::Subresource)?; + if mip >= mips { + return Err(ReverseLayoutError::Subresource); + } + (mip, None) + } else { + let total = mips.checked_mul(surface.array as usize).ok_or(ReverseLayoutError::Subresource)?; + let sub = usize::try_from(subresource).map_err(|_| ReverseLayoutError::Subresource)?; + if sub >= total { + return Err(ReverseLayoutError::Subresource); + } + (sub % mips, Some(sub / mips)) + }; + let level = &surface.chain.levels[mip]; + let width = (surface.width >> mip).max(1); + let height = (surface.height >> mip).max(1); + let depth = if surface.depth > 0 { (surface.depth >> mip).max(1) } else { 1 }; + if footprint.width != width || footprint.height != height || footprint.depth != depth { + return Err(ReverseLayoutError::Dimensions); + } + let row_bytes = level.width.checked_mul(surface.bpe as usize).ok_or(ReverseLayoutError::Footprint)?; + if level.width != (width as usize).div_ceil(side as usize) + || level.height != (height as usize).div_ceil(side as usize) + || level.depth != depth as usize + { + return Err(ReverseLayoutError::UnsupportedLayout); + } + if footprint.row_pitch < row_bytes || footprint.row_pitch % 256 != 0 || footprint.offset % 512 != 0 { + return Err(ReverseLayoutError::RowPitch); + } + let slice_pitch = footprint.row_pitch.checked_mul(level.height).ok_or(ReverseLayoutError::Footprint)?; + let last_slice = slice_pitch.checked_mul(level.depth.saturating_sub(1)).ok_or(ReverseLayoutError::Footprint)?; + let last_row = footprint.row_pitch.checked_mul(level.height.saturating_sub(1)).ok_or(ReverseLayoutError::Footprint)?; + let used = last_slice.checked_add(last_row).and_then(|n| n.checked_add(row_bytes)).ok_or(ReverseLayoutError::Footprint)?; + let footprint_end = footprint.offset.checked_add(footprint.size).ok_or(ReverseLayoutError::Footprint)?; + if used > footprint.size || footprint_end > readback.len() { + return Err(ReverseLayoutError::Footprint); + } + let console_size = usize::try_from(tex.size()).map_err(|_| ReverseLayoutError::Destination)?; + if console.len() < console_size { + return Err(ReverseLayoutError::Destination); + } + let linear_size = row_bytes + .checked_mul(level.height) + .and_then(|n| n.checked_mul(level.depth)) + .ok_or(ReverseLayoutError::Footprint)?; + let mut linear = Vec::new(); + linear.try_reserve_exact(linear_size).map_err(|_| ReverseLayoutError::Footprint)?; + linear.resize(linear_size, 0); + for z in 0..level.depth { + for y in 0..level.height { + let from = footprint.offset + z * slice_pitch + y * footprint.row_pitch; + let to = (z * level.height + y) * row_bytes; + linear[to..to + row_bytes].copy_from_slice(&readback[from..from + row_bytes]); + } + } + let plane_at = usize::try_from(plane_offset).map_err(|_| ReverseLayoutError::Destination)?; + if let Some(slice) = slice { + let at = plane_at + .checked_add(slice.checked_mul(surface.chain.slice_bytes).ok_or(ReverseLayoutError::Destination)?) + .ok_or(ReverseLayoutError::Destination)?; + let end = at.checked_add(surface.chain.slice_bytes).ok_or(ReverseLayoutError::Destination)?; + let dst = console.get_mut(at..end).ok_or(ReverseLayoutError::Destination)?; + surface.chain.tile_level(dst, mip, slice, &linear); + } else { + let bytes = usize::try_from(surface.size()).map_err(|_| ReverseLayoutError::Destination)?; + let end = plane_at.checked_add(bytes).ok_or(ReverseLayoutError::Destination)?; + let dst = console.get_mut(plane_at..end).ok_or(ReverseLayoutError::Destination)?; + surface.chain.tile_volume(dst, mip, &linear); + } + Ok(()) +} + #[cfg(test)] mod tests { @@ -2451,6 +2572,90 @@ mod tests { d } + fn readback_for(tex: &xg::Texture, format: u32, subresource: u32) -> (ReadbackFootprint, Vec, Vec) { + let s = tex.texels().unwrap(); + let mips = s.chain.levels.len(); + let mip = subresource as usize % mips; + let l = &s.chain.levels[mip]; + let (w, h) = ((s.width >> mip).max(1), (s.height >> mip).max(1)); + let depth = if s.depth > 0 { (s.depth >> mip).max(1) } else { 1 }; + let row_bytes = l.width * s.bpe as usize; + let row_pitch = row_bytes.next_multiple_of(256); + let slice_pitch = row_pitch * l.height; + let size = slice_pitch * (l.depth - 1) + row_pitch * (l.height - 1) + row_bytes; + let mut readback = vec![0xE7; 512 + size + 31]; + let mut linear = vec![0; row_bytes * l.height * l.depth]; + for z in 0..l.depth { + for y in 0..l.height { + for x in 0..row_bytes { + let v = (z * 71 + y * 17 + x * 3 + 5) as u8; + readback[512 + z * slice_pitch + y * row_pitch + x] = v; + linear[(z * l.height + y) * row_bytes + x] = v; + } + } + } + (ReadbackFootprint { offset: 512, size, row_pitch, width: w, height: h, depth, format }, readback, linear) + } + + #[test] + fn reverse_layout_tiles_an_edge_array_mip_without_touching_guards() { + let tex = xg::Texture::new(&console_desc(3, 17, 9, 2, 3, 28, 0x105)).unwrap(); + let sub = 5; // array slice 1, mip 2 + let (fp, readback, linear) = readback_for(&tex, 28, sub); + let size = tex.size() as usize; + let mut console = vec![0xCD; size + 37]; + reverse_layout_subresource(&tex, 28, sub, fp, &readback, &mut console).unwrap(); + + let s = tex.texels().unwrap(); + let slice = &console[s.chain.slice_bytes..2 * s.chain.slice_bytes]; + assert_eq!(s.chain.detile_level(slice, 2, 1), linear); + assert!(console[size..].iter().all(|&b| b == 0xCD), "destination guard changed"); + assert!(readback[..512].iter().all(|&b| b == 0xE7)); + assert!(readback[512 + fp.size..].iter().all(|&b| b == 0xE7)); + } + + #[test] + fn reverse_layout_handles_volume_depth_and_block_geometry() { + let volume = xg::Texture::new(&console_desc(4, 32, 16, 8, 4, 28, 0x105)).unwrap(); + let (fp, readback, linear) = readback_for(&volume, 28, 2); + assert_eq!((fp.width, fp.height, fp.depth), (8, 4, 2)); + let mut console = vec![0u8; volume.size() as usize]; + reverse_layout_subresource(&volume, 28, 2, fp, &readback, &mut console).unwrap(); + assert_eq!(volume.texels().unwrap().chain.detile_volume(&console, 2), linear); + + let blocks = xg::Texture::new(&console_desc(3, 10, 9, 1, 1, 71, 0x105)).unwrap(); + let (fp, readback, linear) = readback_for(&blocks, 71, 0); + assert_eq!((fp.width, fp.height, fp.depth), (10, 9, 1)); + assert_eq!(blocks.texels().unwrap().chain.levels[0].width, 3); + let mut console = vec![0u8; blocks.size() as usize]; + reverse_layout_subresource(&blocks, 71, 0, fp, &readback, &mut console).unwrap(); + assert_eq!(blocks.texels().unwrap().chain.detile_level(&console, 0, 0), linear); + } + + #[test] + fn reverse_layout_rejects_metadata_malformed_footprints_and_truncation() { + let tex = xg::Texture::new(&console_desc(3, 16, 8, 1, 1, 28, 0x105)).unwrap(); + let (fp, readback, _) = readback_for(&tex, 28, 0); + let mut console = vec![0u8; tex.size() as usize]; + let call = |f: ReadbackFootprint, src: &[u8], dst: &mut [u8]| reverse_layout_subresource(&tex, 28, 0, f, src, dst); + assert_eq!(call(ReadbackFootprint { format: 87, ..fp }, &readback, &mut console), Err(ReverseLayoutError::Format)); + assert_eq!(reverse_layout_subresource(&tex, 28, 1, fp, &readback, &mut console), Err(ReverseLayoutError::Subresource)); + assert_eq!(call(ReadbackFootprint { width: 15, ..fp }, &readback, &mut console), Err(ReverseLayoutError::Dimensions)); + assert_eq!(call(ReadbackFootprint { row_pitch: 255, ..fp }, &readback, &mut console), Err(ReverseLayoutError::RowPitch)); + assert_eq!(call(ReadbackFootprint { offset: 1, ..fp }, &readback, &mut console), Err(ReverseLayoutError::RowPitch)); + assert_eq!(call(ReadbackFootprint { size: fp.size - 1, ..fp }, &readback, &mut console), Err(ReverseLayoutError::Footprint)); + assert_eq!(call(fp, &readback[..512 + fp.size - 1], &mut console), Err(ReverseLayoutError::Footprint)); + assert_eq!(call(fp, &readback, &mut console[..tex.size() as usize - 1]), Err(ReverseLayoutError::Destination)); + let overflow = ReadbackFootprint { offset: usize::MAX & !511, ..fp }; + assert_eq!(call(overflow, &readback, &mut console), Err(ReverseLayoutError::Footprint)); + + let mut rt = console_desc(3, 16, 8, 1, 1, 28, 0x105); + rt[0x30..0x34].copy_from_slice(&1u32.to_le_bytes()); + let rt = xg::Texture::new(&rt).unwrap(); + let mut rt_console = vec![0u8; rt.size() as usize]; + assert_eq!(reverse_layout_subresource(&rt, 28, 0, fp, &readback, &mut rt_console), Err(ReverseLayoutError::UnsupportedLayout)); + } + /// Overlapping textures shadow earlier ones so dead placements never re-upload over shared /// `vram::Pages` tiles; different-range overlaps request unmapping while exact same-range /// overlaps stay mapped; releasing a newer placement reactivates uncovered older ones. From 2bfc36eb93fd03fa5d1f1bb64e41bad3deca789a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 10:24:29 +0500 Subject: [PATCH 092/265] D3D12.X: preserve compute stream pipeline flags The console compute-stream projection dropped its FLAGS subobject, so stream-created pipelines always reached creation and the driver-blob cache key with zero flags. Forward type 20 exactly as the graphics-stream and legacy compute paths already do.\n\nAdd a synthetic stream test covering absent and nonzero flags.\n\nPart of #2607.\n\nAssisted-by: Devin (SWE-2 High)\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 44 +++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index dd82d2f47f..e5c19cc70a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7092,6 +7092,7 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { 0 => put(&mut c.pRootSignature, p), 6 => put(&mut c.CS, p), 18 => put(&mut c.NodeMask, p), + 20 => put(&mut c.Flags, p), _ => {} } } @@ -8782,6 +8783,49 @@ mod map_tests { assert!(parse(None, Some(true)).DepthStencilState.DepthEnable.as_bool()); assert!(!parse(Some(40), Some(false)).DepthStencilState.DepthEnable.as_bool()); } + + /// A console compute stream's FLAGS subobject reaches the projected descriptor: + /// `dev_create_compute_pso` uses it for the driver's own cache key the same way a + /// legacy desc's flags are used (#2607). + #[test] + fn a_compute_stream_keeps_its_flags_subobject() { + let console_cs = crate::gpu::xbox::tests::sample( + 1, + &[crate::gpu::xbox::tests::fssm(&crate::gpu::xbox::tests::CODE, &[])], + ); + let parse = |flags: Option| -> D3D12_COMPUTE_PIPELINE_STATE_DESC { + let mut stream = Vec::new(); + let mut cs_bc = [0u8; 16]; + cs_bc[0..8].copy_from_slice(&(console_cs.as_ptr() as usize).to_le_bytes()); + cs_bc[8..16].copy_from_slice(&console_cs.len().to_le_bytes()); + stream.extend_from_slice(&6u32.to_le_bytes()); + stream.extend_from_slice(&0u32.to_le_bytes()); + stream.extend_from_slice(&cs_bc); + while stream.len() % 8 != 0 { + stream.push(0); + } + if let Some(f) = flags { + stream.extend_from_slice(&20u32.to_le_bytes()); + stream.extend_from_slice(&f.to_le_bytes()); + while stream.len() % 8 != 0 { + stream.push(0); + } + } + #[repr(C)] + struct StreamDesc { + size: usize, + ptr: usize, + } + let desc = StreamDesc { size: stream.len(), ptr: stream.as_ptr() as usize }; + match unsafe { stream_pipeline(&desc as *const _ as *const c_void) } { + StreamPipeline::Compute(c) => *c, + _ => panic!("expected compute stream pipeline"), + } + }; + assert_eq!(parse(None).Flags.0, 0); + assert_eq!(parse(Some(1)).Flags.0, 1, "the FLAGS subobject must reach the projected compute desc"); + assert_eq!(parse(Some(3)).Flags.0, 3); + } } #[cfg(test)] From 911ad65d235d09e731c75863e9be110597a5526a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:37:26 -0800 Subject: [PATCH 093/265] Recompiler: bound far-jump analysis initial allocation The streaming effects fast path capped its initial instruction storage when it only needed to reject memory-writing shaders, but an early S_SETPC_B64 fallback still reserved for the entire shader before seeing a nearby store. Apply the same small initial capacity to the far-jump path and let it grow only when full analysis is required.\n\nFollow-up to #2656.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/effects.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/effects.rs b/crates/xcl/src/gpu/effects.rs index 8703febfb8..b76be2aaa9 100644 --- a/crates/xcl/src/gpu/effects.rs +++ b/crates/xcl/src/gpu/effects.rs @@ -81,7 +81,10 @@ fn analyze(code: &[u8], stop_on_memory: bool) -> Option { } fn analyze_with_far_jumps(code: &[u8], stop_on_memory: bool) -> Option { - let mut insts = Vec::with_capacity(code.len() / 6); + // Keep early memory-writer rejection cheap even when an initial SETPC selects this slower + // path; grow only if analysis actually has to retain the rest of a large shader. + let cap = if stop_on_memory { (code.len() / 6).min(256) } else { code.len() / 6 }; + let mut insts = Vec::with_capacity(cap); let mut off = 0; let mut ended = false; let mut e = Effects::default(); From 75c4a2451dedc4e98a553aea63bb7df56c19f430 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:39:40 -0800 Subject: [PATCH 094/265] Frame clock: remove paced wait allocations and validate writes Validate WaitFrameEventX's signaled-index target as committed, unguarded, and writable without touching its pages. Replace ancillary and paced wait handle vectors with fixed stack storage, avoid the scheduled-handle Arc clone on the paced path, and use deques for bounded frame history eviction.\n\nAdapted from #2692.\nPart of #103.\n\nAssisted-by: Google Antigravity (Gemini 4 Neon)\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/frame.rs | 202 ++++++++++++++++++++++++++--- 1 file changed, 182 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/frame.rs b/crates/xcl/src/hle/d3d12x/frame.rs index 38c073c0ec..c98fd55c2d 100644 --- a/crates/xcl/src/hle/d3d12x/frame.rs +++ b/crates/xcl/src/hle/d3d12x/frame.rs @@ -138,9 +138,9 @@ unsafe impl Send for Clock {} static CLOCK: Mutex> = Mutex::new(None); static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1); /// (token, qpc of the origin it was issued at) -static ISSUED: Mutex> = Mutex::new(Vec::new()); +static ISSUED: Mutex> = Mutex::new(VecDeque::new()); /// (token, origin qpc, flip qpc) -static FLIPPED: Mutex> = Mutex::new(Vec::new()); +static FLIPPED: Mutex> = Mutex::new(VecDeque::new()); static LAST_ORIGIN: AtomicI64 = AtomicI64::new(0); /// qpc of the origins the clock released and no WaitFrameEventX has consumed yet (the origin /// semaphore counts up to ORIGIN_SEMAPHORE_MAX): each token gets its own frame's origin, not @@ -260,23 +260,115 @@ pub unsafe extern "system" fn set_frame_interval_x(_this: *mut std::ffi::c_void, S_FALSE } +// Writability and stack-handle fast paths adapted from PR #2692 by Decodere. +fn is_writable_protect(protect: u32) -> bool { + use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_READWRITE, PAGE_WRITECOPY}; + matches!(protect & 0xFF, PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY) +} + +/// Fast-path working-set check for `[p, end)`: a definite answer for resident pages, otherwise +/// `None` so `writable` can inspect the virtual-memory regions without touching the pages. +fn resident_and_writable(p: usize, end: usize) -> Option { + use windows_sys::Win32::System::Memory::PAGE_GUARD; + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + const MAX_PAGES: usize = 16; + let first = p >> 12; + let pages = ((end - 1) >> 12) - first + 1; + if pages > MAX_PAGES { + return None; + } + let mut ws: [PSAPI_WORKING_SET_EX_INFORMATION; MAX_PAGES] = unsafe { std::mem::zeroed() }; + for (k, e) in ws[..pages].iter_mut().enumerate() { + e.VirtualAddress = ((first + k) << 12) as *mut std::ffi::c_void; + } + let size = (pages * std::mem::size_of::()) as u32; + if unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), ws.as_mut_ptr() as *mut std::ffi::c_void, size) } == 0 { + return None; + } + let mut all_resident = true; + for e in &ws[..pages] { + let flags = unsafe { e.VirtualAttributes.Flags }; + let protect = ((flags >> 4) & 0x7FF) as u32; + if flags & 1 != 0 && protect != 0 { + if protect & PAGE_GUARD != 0 || !is_writable_protect(protect) { + return Some(false); + } + } else { + all_resident = false; + } + } + all_resident.then_some(true) +} + +/// Whether `[p, p + len)` is committed, unguarded and writable without touching any page. +fn writable(p: usize, len: usize) -> bool { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_GUARD}; + if p == 0 || len == 0 || len > 256 << 20 { + return false; + } + let Some(end) = p.checked_add(len) else { return false }; + if let Some(ok) = resident_and_writable(p, end) { + return ok; + } + let mut cur = p; + while cur < end { + let mut mbi: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let n = unsafe { VirtualQuery(cur as *const _, &mut mbi, std::mem::size_of::()) }; + if n == 0 || mbi.State != MEM_COMMIT || mbi.Protect & PAGE_GUARD != 0 || !is_writable_protect(mbi.Protect) { + return false; + } + let Some(next) = (mbi.BaseAddress as usize).checked_add(mbi.RegionSize) else { return false }; + if next <= cur { + return false; + } + cur = next; + } + true +} + +/// Stack-allocated ancillary handles (at most `MAXIMUM_WAIT_OBJECTS - 1`). +struct AncillaryHandles { + handles: [HANDLE; 63], + len: usize, +} + +impl std::ops::Deref for AncillaryHandles { + type Target = [HANDLE]; + fn deref(&self) -> &[HANDLE] { + &self.handles[..self.len] + } +} + +impl IntoIterator for AncillaryHandles { + type Item = HANDLE; + type IntoIter = std::iter::Take>; + fn into_iter(self) -> Self::IntoIter { + self.handles.into_iter().take(self.len) + } +} + /// the handles of an ancillary block `{ u32 count; HANDLE* list @8; i32* signaled @0x10 }` -unsafe fn ancillary(block: *const u8) -> Result, HRESULT> { +unsafe fn ancillary(block: *const u8) -> Result { + let mut out = AncillaryHandles { handles: [std::ptr::null_mut(); 63], len: 0 }; if block.is_null() { - return Ok(Vec::new()); + return Ok(out); } if !crate::gpu::shader::readable(block as usize, 16) { return Err(E_INVALIDARG); } let count = (block as *const u32).read_unaligned() as usize; if count == 0 { - return Ok(Vec::new()); + return Ok(out); } let list = (block.add(8) as *const usize).read_unaligned(); if count > 63 || !crate::gpu::shader::readable(list, count * 8) { return Err(E_INVALIDARG); } - Ok((0..count).map(|i| (list as *const HANDLE).add(i).read_unaligned()).collect()) + for (i, slot) in out.handles[..count].iter_mut().enumerate() { + *slot = (list as *const HANDLE).add(i).read_unaligned(); + } + out.len = count; + Ok(out) } unsafe fn note_signaled(block: *const u8, index: i32) { @@ -284,7 +376,7 @@ unsafe fn note_signaled(block: *const u8, index: i32) { return; } let out = (block.add(0x10) as *const usize).read_unaligned(); - if crate::gpu::shader::readable(out, 4) { + if writable(out, 4) { (out as *mut i32).write_unaligned(index); } } @@ -363,7 +455,7 @@ pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, t trace_calls(format_args!("WaitFrameEventX(type {ty}, timeout {timeout_ms} ms, block {block:p}, flags {flags:#x}, token in {:#x})", if token.is_null() { 0 } else { *token })); let scheduled = with(|c| { ((ty as usize) < TYPES && c.kinds[ty as usize].scheduled) - .then(|| (c.kinds[ty as usize].internal as usize, Arc::clone(&c.kinds[ty as usize].extra))) + .then(|| (c.kinds[ty as usize].internal as usize, (interval_override() == Some(0)).then(|| Arc::clone(&c.kinds[ty as usize].extra)))) }); let Some((internal, scheduled_extra)) = scheduled else { return E_INVALIDARG }; let token_in = if token.is_null() { 0 } else { *token }; @@ -374,8 +466,7 @@ pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, t Ok(h) => h, Err(e) => return e, }; - let uncapped = interval_override() == Some(0); - let (hr, index, origin_now) = if uncapped { + let (hr, index, origin_now) = if let Some(scheduled_extra) = scheduled_extra { for &h in &scheduled_extra.0 { if SetEvent(h) == 0 { ReleaseSemaphore(h, 1, std::ptr::null_mut()); @@ -402,16 +493,18 @@ pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, t } (hr, index, Some(now)) } else { - let mut hs = vec![internal as HANDLE]; - hs.extend(extra); - let r = WaitForMultipleObjects(hs.len() as u32, hs.as_ptr(), (flags & WAIT_ALL != 0) as i32, timeout_ms); + let mut hs = [std::ptr::null_mut(); 64]; + hs[0] = internal as HANDLE; + hs[1..1 + extra.len()].copy_from_slice(&extra); + let count = 1 + extra.len(); + let r = WaitForMultipleObjects(count as u32, hs.as_ptr(), (flags & WAIT_ALL != 0) as i32, timeout_ms); ACTIVITY[0].fetch_add(1, Ordering::Relaxed); if r == WAIT_TIMEOUT { ACTIVITY[1].fetch_add(1, Ordering::Relaxed); } let (hr, index) = if r == WAIT_TIMEOUT { (S_FALSE, -1) - } else if ((r - WAIT_OBJECT_0) as usize) < hs.len() { + } else if ((r - WAIT_OBJECT_0) as usize) < count { // -2: the frame event itself, else the index of the ancillary handle (S_OK, if r == WAIT_OBJECT_0 { -2 } else { (r - WAIT_OBJECT_0) as i32 - 1 }) } else { @@ -440,9 +533,9 @@ pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, t t = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed) & TOKEN_MASK; } if issued.len() >= KNOWN_TOKENS { - issued.remove(0); + issued.pop_front(); } - issued.push((t, origin)); + issued.push_back((t, origin)); if !token.is_null() { *token = t; } @@ -459,10 +552,9 @@ pub fn mark_flipped(token: u64) { // the frame's own origin (a token XCL did not issue: the latest origin) let origin = ISSUED.lock().unwrap().iter().rev().find(|e| e.0 == token).map(|e| e.1).unwrap_or_else(|| LAST_ORIGIN.load(Ordering::Relaxed)); let mut f = FLIPPED.lock().unwrap(); - f.push((token, origin, qpc())); - if f.len() > FLIPPED_KEEP { - let n = f.len() - FLIPPED_KEEP; - f.drain(..n); + f.push_back((token, origin, qpc())); + while f.len() > FLIPPED_KEEP { + f.pop_front(); } } @@ -623,6 +715,76 @@ mod tests { assert_eq!(effective_clock_interval_us(33333, Some(200)), Some(1000)); } + #[test] + fn note_signaled_requires_every_target_page_to_be_writable() { + use windows_sys::Win32::System::Memory::{ + VirtualAlloc, VirtualFree, VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_GUARD, + PAGE_READONLY, PAGE_READWRITE, + }; + let block = |out: usize| { + let mut b = [0u8; 0x18]; + b[0x10..].copy_from_slice(&out.to_le_bytes()); + b + }; + unsafe { + assert!(!writable(0, 4) && !writable(usize::MAX - 1, 4)); + let base = VirtualAlloc(std::ptr::null(), 0x3000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + assert!(!base.is_null()); + let (ro, guard) = (base.add(0x1000), base.add(0x2000)); + (ro as *mut i32).write_unaligned(0x1234_5678); + let mut old = 0; + assert_ne!(VirtualProtect(ro as *const _, 0x1000, PAGE_READONLY, &mut old), 0); + assert_ne!(VirtualProtect(guard as *const _, 0x1000, PAGE_READWRITE | PAGE_GUARD, &mut old), 0); + assert!(writable(base as usize, 4)); + assert!(!writable(base as usize + 0xFFE, 4) && !writable(guard as usize, 4)); + note_signaled(block(ro as usize).as_ptr(), 9); + assert_eq!((ro as *const i32).read_unaligned(), 0x1234_5678); + note_signaled(block(base as usize).as_ptr(), 7); + assert_eq!((base as *const i32).read_unaligned(), 7); + let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(VirtualQuery(guard as *const _, &mut mbi, std::mem::size_of_val(&mbi)), 0); + assert_ne!(mbi.Protect & PAGE_GUARD, 0, "validation consumed the guard page"); + assert_ne!(VirtualFree(base as *mut _, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn ancillary_stack_handles_preserve_boundaries_and_order() { + unsafe { + assert!(ancillary(std::ptr::null()).unwrap().is_empty()); + let mut block = [0u8; 0x18]; + let list: [HANDLE; 63] = std::array::from_fn(|i| ((i + 1) * 4) as HANDLE); + block[..4].copy_from_slice(&63u32.to_le_bytes()); + block[8..16].copy_from_slice(&(list.as_ptr() as usize).to_le_bytes()); + let got = ancillary(block.as_ptr()).unwrap(); + assert_eq!(&*got, &list); + assert_eq!(got.into_iter().collect::>(), list); + block[..4].copy_from_slice(&64u32.to_le_bytes()); + assert_eq!(ancillary(block.as_ptr()).err(), Some(E_INVALIDARG)); + } + } + + #[test] + fn frame_history_deques_evict_oldest_in_order() { + let mut issued = VecDeque::new(); + for i in 0..KNOWN_TOKENS + 10 { + if issued.len() >= KNOWN_TOKENS { + issued.pop_front(); + } + issued.push_back(i); + } + assert_eq!((issued.len(), issued.front(), issued.back()), (KNOWN_TOKENS, Some(&10), Some(&(KNOWN_TOKENS + 9)))); + + let mut flipped = VecDeque::new(); + for i in 0..FLIPPED_KEEP + 10 { + flipped.push_back(i); + while flipped.len() > FLIPPED_KEEP { + flipped.pop_front(); + } + } + assert_eq!((flipped.len(), flipped.front(), flipped.back()), (FLIPPED_KEEP, Some(&10), Some(&(FLIPPED_KEEP + 9)))); + } + #[test] fn console_intervals_and_deadlines() { assert!(interval_valid(16667, false) && interval_valid(16666 + 16, false) && interval_valid(33333, false)); From 3364f184d44baa0f6d1ec0f209b7d04e41aa7b5f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 19:24:20 -0700 Subject: [PATCH 095/265] D3D12.X: reject put-off segments that fail Close The deferred-call path ignored native Close failures both while reserving an empty segment and after replaying the call. Such a segment could reach ExecuteCommandLists and remove the device.\n\nReject a reservation whose initial Close fails. If replay Close fails, drop the call, restore arena ownership to the previous valid segment, and quarantine the still-open list until wrapper destruction so it can never be reused as a closed spare.\n\nCo-Authored-By: Claude Opus 5.5 \nAssisted-by: Claude Code (Claude Opus 5.5)\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 174 +++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/title_list.rs | 10 ++ 2 files changed, 182 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index d850a319a1..eaabfbc28e 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3244,12 +3244,48 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { Deferred::Indirect(sig, max, args, args_off, count_buf, count_off) => super::bind::execute_indirect(seg, sig, max, args, args_off, count_buf, count_off), } let ext = *(seg as *const usize); - pc:: i32>(seg, PC_CLOSE)(seg); + let hr = segment_close(wrapper, seg); real::preserve_vtable(seg, ext); + if hr < 0 { + // a recording the runtime refused is not submitted: the segment leaves the recording + // (a list whose Close failed is still open and cannot be reset), its call is dropped, + // and the next one does not follow it + static CLOSE_ERR: AtomicU64 = AtomicU64::new(0); + warn(&CLOSE_ERR, "deferred call", format_args!("Close failed ({hr:#x}), the call is dropped")); + super::bind::dispatch_dropped(); + if let Some(last) = last { + super::bind::pass_arena(seg, last); + } + super::title_list::drop_segment(wrapper, seg); + continue; + } last = Some(seg); } } +/// (tests) What the next native Close of a put-off segment of this wrapper does instead +/// (`segment_close`; tests run in parallel, so it is the given wrapper's only). +#[cfg(test)] +type CloseHook = Box i32 + Send>; +#[cfg(test)] +static CLOSE_HOOK: Mutex> = Mutex::new(Vec::new()); + +/// The native Close of `wrapper`'s put-off segment `p`: its HRESULT. +unsafe fn segment_close(wrapper: *mut c_void, p: *mut c_void) -> i32 { + #[cfg(test)] + { + let hook = { + let mut g = CLOSE_HOOK.lock().unwrap(); + g.iter().position(|h| h.0 == wrapper as usize).map(|i| g.remove(i).1) + }; + if let Some(hook) = hook { + return hook(p); + } + } + let _ = wrapper; + pc:: i32>(p, PC_CLOSE)(p) +} + /// The allocator `list`'s put-off calls recorded on is reset once the GPU is done with them, so /// their split dispatches' scratch does not outlive them. unsafe fn reset_own_alloc(list: *mut c_void) { @@ -3474,12 +3510,14 @@ unsafe fn reserve_closed_segment( } let made = real::create_raw_pc_command_list(dev.as_raw(), ty, temp.as_raw() as usize, 0)?; let ext = *(made as *const usize); - let hr = pc:: i32>(made, PC_CLOSE)(made); + let hr = segment_close(wrapper, made); real::preserve_vtable(made, ext); if hr >= 0 { note_reserved_closed(made as usize, ty); Some(made) } else { + static CLOSE_ERR: AtomicU64 = AtomicU64::new(0); + warn(&CLOSE_ERR, "put-off segment", format_args!("Close failed ({hr:#x})")); pc:: u32>(made, 2)(made); None } @@ -8306,6 +8344,138 @@ mod tests { } } + /// A direct queue, its allocator and a title list wrapped as XCL wraps one, bound to `standin` + /// (None: no adapter). + unsafe fn put_off_rig(standin: usize) -> Option<(ID3D12Device, ID3D12CommandQueue, ID3D12CommandAllocator, *mut c_void, *mut c_void)> { + use super::super::{bind, title_list}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()); + if warp.and_then(|w| D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev)).is_err() { + return None; + } + } + let dev = dev.unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let pc0 = raw.into_raw(); + real::adopt(pc0, real::Kind::CommandList); + on_create(pc0, alloc.as_raw() as usize, 0, ty); + bind::reset(pc0, alloc.as_raw() as usize, standin); + let wrap = title_list::wrap(pc0); + Some((dev, queue, alloc, pc0, wrap)) + } + + /// A put-off call whose recording the driver refuses at the submit (its segment's Close + /// fails) is not submitted as it is: the segment goes out empty, the call is dropped, and the + /// rest of the submission runs (its fence is signalled, the device stays). + #[test] + fn a_put_off_call_whose_close_fails_is_not_submitted() { + use super::super::{bind, pso_async, title_list}; + use std::time::{Duration, Instant}; + unsafe { + let standin = 0x7E57_C105usize; + static BUILD: AtomicBool = AtomicBool::new(false); + BUILD.store(false, Ordering::Release); + pso_async::submit(standin, true, Box::new(|| { + let t = Instant::now(); + while !BUILD.load(Ordering::Acquire) && t.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } + 0 + })); + let Some((dev, queue, _alloc, pc0, wrap)) = put_off_rig(standin) else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + bind::dispatch(pc0, 1, 1, 1); + let mut segs = Vec::new(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 3, "the dispatch was put off"); + + // the replay's recording fails in the runtime: a query begun and never ended + let mut heap: Option = None; + dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_OCCLUSION, Count: 1, NodeMask: 0 }, &mut heap).unwrap(); + let heap = heap.unwrap(); + let h = heap.as_raw() as usize; + static REFUSED: AtomicU32 = AtomicU32::new(0); + CLOSE_HOOK.lock().unwrap().push((wrap as usize, Box::new(move |p| { + pc::(p, PC_BEGIN_QUERY)(p, h, D3D12_QUERY_TYPE_OCCLUSION, 0); + let hr = pc:: i32>(p, PC_CLOSE)(p); + REFUSED.store(hr as u32, Ordering::Release); + hr + }))); + let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(9)); + assert_eq!(close_fn(wrap), 0); + BUILD.store(true, Ordering::Release); + record_deferred(wrap); + assert!(!CLOSE_HOOK.lock().unwrap().iter().any(|h| h.0 == wrap as usize), "the replay closed its segment"); + assert!((REFUSED.load(Ordering::Acquire) as i32) < 0, "the runtime refused the recording ({:#x})", REFUSED.load(Ordering::Acquire)); + // what the submit collects after the replay (`q_execute_command_lists`) + segs.clear(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 2, "the refused segment is not submitted"); + + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let exec: ExecFn = std::mem::transmute(*(*(queue.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); + exec(queue.as_raw(), segs.len() as u32, segs.as_ptr()); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 2000).expect("the submission runs"); + assert!(dev.GetDeviceRemovedReason().is_ok(), "the device stays"); + + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2)); + rel_fn(wrap); + let _ = pso_async::released(standin); + } + } + + /// A put-off segment that does not close when it is made is not used: the call waits in its + /// list instead of being put off. + #[test] + fn a_put_off_segment_that_does_not_close_is_not_used() { + use super::super::{bind, pso_async, title_list}; + unsafe { + let standin = 0x7E57_C106usize; + static BUILD: AtomicBool = AtomicBool::new(false); + BUILD.store(false, Ordering::Release); + pso_async::submit(standin, true, Box::new(|| { + let t = std::time::Instant::now(); + while !BUILD.load(Ordering::Acquire) && t.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + 0 + })); + let Some((_dev, _queue, _alloc, pc0, wrap)) = put_off_rig(standin) else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + CLOSE_HOOK.lock().unwrap().push((wrap as usize, Box::new(|p| { + pc:: i32>(p, PC_CLOSE)(p); + windows::Win32::Foundation::E_FAIL.0 + }))); + // (the call that is not put off waits for the build in the call; started here, after + // the device is made, so the build is still going when the call comes) + let ends = std::thread::spawn(|| { + std::thread::sleep(std::time::Duration::from_millis(300)); + BUILD.store(true, Ordering::Release); + }); + bind::dispatch(pc0, 1, 1, 1); + ends.join().unwrap(); + assert!(!CLOSE_HOOK.lock().unwrap().iter().any(|h| h.0 == wrap as usize), "the put-off segment was closed"); + let mut segs = Vec::new(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 1, "nothing was put off"); + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2)); + rel_fn(wrap); + let _ = pso_async::released(standin); + } + } + /// Reproduces the exact intra-list fork-join pattern seen on retail compute queues: /// q_compute list O_c: Write64(cell_A, frame) -> Wait64(cell_B >= frame) -> Write64(cell_C, frame) /// q_direct list O_d: Wait64(cell_A >= frame) -> Write64(cell_B, frame) diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index fa57110563..90aca4aa20 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -363,6 +363,16 @@ 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); } +/// Take segment `pc` out of `wrapper`'s recording, so it is not submitted. Its failed Close left +/// it open, so quarantine it until wrapper destruction rather than treating it as a closed spare. +pub(super) fn drop_segment(wrapper: *mut c_void, pc: *mut c_void) { + let mut sg = SEGMENTS.lock().unwrap(); + if let Some(b) = sg.as_mut().and_then(|m| m.get_mut(&(wrapper as usize))) { + b.extra_active.retain(|&p| p != pc as usize); + b.unresettable.push(pc as usize); + } +} + /// 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); From 32ecdb27146c34934f5b0281426c639e9fb53a47 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:49:21 -0800 Subject: [PATCH 096/265] D3D12.X: make projected stream caching conservative Checked parsing retains a known graphics-stream prefix while marking unknown or truncated suffixes uncacheable. Thread that decision through synchronous and worker builds so projected descriptors cannot populate memory or driver caches when omitted state may affect identity.\n\nAlso preserve the legacy-representable RASTERIZER1 and RASTERIZER2 fields. Fractional depth bias and RASTERIZER2 line mode remain for the later native-stream stage.\n\nAdapted from PR #2621 by Decodere.\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 176 +++++++++++++++++++++++++----- 1 file changed, 151 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e5c19cc70a..1f70d899b7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5598,11 +5598,11 @@ fn create_graphics_pso_cached( } } -unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { - with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) +unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, cacheable: bool) -> Option { + with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv, cacheable)) } -unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { +unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, cacheable: bool) -> Option { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; @@ -5677,8 +5677,8 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + rect_gs.as_ref().map_or(0, Vec::len); let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers); - let mut cached = graphics_blob(gkey); - let disk = driver_cache::graphics_path(gkey.0, gkey.1); + let mut cached = cacheable.then(|| graphics_blob(gkey)).flatten(); + let disk = cacheable.then(|| driver_cache::graphics_path(gkey.0, gkey.1)).flatten(); let from_disk = cached.is_none(); let mut loaded = None; if from_disk { @@ -5699,7 +5699,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), ); let hr = build.hr; - if build.cache_eligible { + if cacheable && build.cache_eligible { keep_driver_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, gkey, bytes, disk.as_deref(), build.built_in_driver, || read_pso_cached_blob(*ppv)); } else if build.reused && from_disk { @@ -6088,7 +6088,12 @@ unsafe fn go_background( unsafe fn build_graphics(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); - matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out), Some(hr) if hr >= 0) + matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out, true), Some(hr) if hr >= 0) +} + +unsafe fn build_graphics_uncacheable(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { + let iid = pc_iid(Kind::PipelineState); + matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out, false), Some(hr) if hr >= 0) } unsafe fn build_compute(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { @@ -6102,19 +6107,20 @@ unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { } pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - graphics_pso(this, desc, riid, ppv, false) + graphics_pso(this, desc, riid, ppv, false, true) } /// `dev_create_graphics_pso`; `stream`: the desc is a pipeline stream's (`stream_pipeline`). -unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, stream: bool) -> HRESULT { +unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, stream: bool, cacheable: bool) -> HRESULT { super::null::capture_graphics_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); - let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_pso(this, f, desc, riid, ppv)) } else { (translated_graphics_pso(this, f, desc, riid, ppv), false) }; + let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_pso(this, f, desc, riid, ppv, cacheable)) } else { (translated_graphics_pso(this, f, desc, riid, ppv, cacheable), false) }; if missed { - if let Some(hr) = own_graphics(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_graphics, graphics_key, build_graphics)) { + let build = if cacheable { build_graphics } else { build_graphics_uncacheable }; + if let Some(hr) = own_graphics(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_graphics, graphics_key, build)) { return hr; } - if let Some(hr) = translated_graphics_pso(this, f, desc, riid, ppv) { + if let Some(hr) = translated_graphics_pso(this, f, desc, riid, ppv, cacheable) { return hr; } } else if let Some(hr) = translated { @@ -6309,24 +6315,41 @@ fn stream_subobjects(buf: &[u8]) -> Option> { /// The stream's subobjects up to the first of a type XCL does not know (logged): a console /// shader in front of it must still be found. -fn known_subobjects(buf: &[u8]) -> Vec<(u32, &[u8])> { +// Checked parsing and extended rasterizer projection adapted from PR #2621 by Decodere. +fn known_subobjects_checked(buf: &[u8]) -> (Vec<(u32, &[u8])>, bool) { let mut out = Vec::new(); let mut off = 0usize; - while off + 8 <= buf.len() { + loop { + if off == buf.len() { + return (out, true); + } + let Some(header) = off.checked_add(8) else { return (out, false) }; + if header > buf.len() { + return (out, false); + } let ty = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap()); let Some((psize, palign)) = super::null::subobject_payload(ty) else { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: pipeline stream: unknown subobject type {ty} at {off:#x} of {:#x} - the rest is not read", buf.len()); } - break; + return (out, false); }; let poff = if palign == 8 { 8 } else { 4 }; - let Some(p) = buf.get(off + poff..off + poff + psize) else { break }; + let Some(start) = off.checked_add(poff) else { return (out, false) }; + let Some(end) = start.checked_add(psize) else { return (out, false) }; + let Some(p) = buf.get(start..end) else { return (out, false) }; out.push((ty, p)); - off += (poff + psize + 7) & !7; + let Some(next) = end.checked_add(7).map(|n| n & !7) else { return (out, false) }; + if next > buf.len() { + return (out, false); + } + off = next; } - out +} + +fn known_subobjects(buf: &[u8]) -> Vec<(u32, &[u8])> { + known_subobjects_checked(buf).0 } unsafe fn payload_shader<'a>(p: &[u8]) -> Option<&'a [u8]> { @@ -7063,7 +7086,7 @@ mod pso_blend_and_tsharp_tests { } enum StreamPipeline { - Graphics(Box), + Graphics(Box, bool), Compute(Box), /// neither with console shaders (or not readable) Unknown, @@ -7083,7 +7106,7 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { if !crate::gpu::shader::readable(base, size) { return StreamPipeline::Unknown; } - let subs = known_subobjects(std::slice::from_raw_parts(base as *const u8, size)); + let (subs, cacheable) = known_subobjects_checked(std::slice::from_raw_parts(base as *const u8, size)); let console = |ty: u32| subs.iter().find(|s| s.0 == ty).and_then(|s| payload_shader(s.1)).is_some_and(is_console); if console(6) { let mut c: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::mem::zeroed(); @@ -7176,8 +7199,7 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { BackFace: face(&d.BackFace), }; } - 27 | 28 => { - // RASTERIZER1 / 2: fill, cull, winding, depth bias (float), clamp, slope, depth clip + 27 => { let mut d: D3D12_RASTERIZER_DESC1 = std::mem::zeroed(); put(&mut d, p); g.RasterizerState = D3D12_RASTERIZER_DESC { @@ -7188,6 +7210,25 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { DepthBiasClamp: d.DepthBiasClamp, SlopeScaledDepthBias: d.SlopeScaledDepthBias, DepthClipEnable: d.DepthClipEnable, + MultisampleEnable: d.MultisampleEnable, + AntialiasedLineEnable: d.AntialiasedLineEnable, + ForcedSampleCount: d.ForcedSampleCount, + ConservativeRaster: d.ConservativeRaster, + }; + } + 28 => { + let mut d: D3D12_RASTERIZER_DESC2 = std::mem::zeroed(); + put(&mut d, p); + g.RasterizerState = D3D12_RASTERIZER_DESC { + FillMode: d.FillMode, + CullMode: d.CullMode, + FrontCounterClockwise: d.FrontCounterClockwise, + DepthBias: d.DepthBias as i32, + DepthBiasClamp: d.DepthBiasClamp, + SlopeScaledDepthBias: d.SlopeScaledDepthBias, + DepthClipEnable: d.DepthClipEnable, + ForcedSampleCount: d.ForcedSampleCount, + ConservativeRaster: d.ConservativeRaster, ..Default::default() }; } @@ -7204,7 +7245,7 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { if g.PrimitiveTopologyType.0 != RECT_LIST_TYPE { pc_topology_type(&mut g); } - StreamPipeline::Graphics(Box::new(g)) + StreamPipeline::Graphics(Box::new(g), cacheable) } /// The bytes of a stream payload as a desc field (no references counted: the desc only borrows). @@ -7248,7 +7289,7 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void return hr; } match stream_pipeline(desc) { - StreamPipeline::Graphics(d) => return graphics_pso(this, &*d as *const _ as *const c_void, riid, ppv, true), + StreamPipeline::Graphics(d, cacheable) => return graphics_pso(this, &*d as *const _ as *const c_void, riid, ppv, true, cacheable), StreamPipeline::Compute(d) => return dev_create_compute_pso(this, &*d as *const _ as *const c_void, riid, ppv), StreamPipeline::Unknown => {} } @@ -8727,6 +8768,91 @@ mod map_tests { } } + #[test] + fn known_stream_suffix_controls_cacheability() { + let console_vs = crate::gpu::xbox::tests::sample( + 1, + &[crate::gpu::xbox::tests::fssm(&crate::gpu::xbox::tests::CODE, &[])], + ); + let mut stream = StreamOut::default(); + stream.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &console_vs); + let (subs, cacheable) = known_subobjects_checked(&stream.0); + assert!(cacheable); + assert_eq!(subs.len(), 1); + + let mut unknown = stream.0.clone(); + unknown.extend_from_slice(&999u32.to_le_bytes()); + unknown.extend_from_slice(&0u32.to_le_bytes()); + let (subs, cacheable) = known_subobjects_checked(&unknown); + assert!(!cacheable, "an unknown suffix must not share a projected-desc cache entry"); + assert_eq!(subs.len(), 1, "the known prefix remains usable"); + let desc = [unknown.len(), unknown.as_ptr() as usize]; + assert!(matches!(unsafe { stream_pipeline(desc.as_ptr() as *const c_void) }, StreamPipeline::Graphics(_, false))); + + let mut truncated_header = stream.0.clone(); + truncated_header.extend_from_slice(&[1, 2, 3, 4]); + assert!(!known_subobjects_checked(&truncated_header).1); + let mut truncated_payload = stream.0.clone(); + truncated_payload.pop(); + assert!(!known_subobjects_checked(&truncated_payload).1); + } + + #[test] + fn stream_pipeline_projects_legacy_rasterizer_fields() { + let console_vs = crate::gpu::xbox::tests::sample( + 1, + &[crate::gpu::xbox::tests::fssm(&crate::gpu::xbox::tests::CODE, &[])], + ); + let parse = |ty: u32, raster: &[u8]| -> (D3D12_RASTERIZER_DESC, bool) { + let mut stream = StreamOut::default(); + stream.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &console_vs); + stream.raw(ty, raster, false); + let desc = [stream.0.len(), stream.0.as_ptr() as usize]; + match unsafe { stream_pipeline(desc.as_ptr() as *const c_void) } { + StreamPipeline::Graphics(g, cacheable) => (g.RasterizerState, cacheable), + _ => panic!("expected graphics stream pipeline"), + } + }; + let bytes = |p: *const u8, n| unsafe { std::slice::from_raw_parts(p, n) }; + + let r1 = D3D12_RASTERIZER_DESC1 { + FillMode: D3D12_FILL_MODE_WIREFRAME, + CullMode: D3D12_CULL_MODE_FRONT, + FrontCounterClockwise: true.into(), + DepthBias: 7.75, + DepthBiasClamp: 2.5, + SlopeScaledDepthBias: 1.5, + DepthClipEnable: false.into(), + MultisampleEnable: true.into(), + AntialiasedLineEnable: true.into(), + ForcedSampleCount: 4, + ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON, + }; + let (got, cacheable) = parse(27, bytes(&r1 as *const _ as *const u8, std::mem::size_of_val(&r1))); + assert!(cacheable); + assert_eq!((got.FillMode, got.CullMode, got.DepthBias), (r1.FillMode, r1.CullMode, 7)); + assert!(got.MultisampleEnable.as_bool() && got.AntialiasedLineEnable.as_bool()); + assert_eq!((got.ForcedSampleCount, got.ConservativeRaster), (4, r1.ConservativeRaster)); + + let r2 = D3D12_RASTERIZER_DESC2 { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + FrontCounterClockwise: false.into(), + DepthBias: -3.25, + DepthBiasClamp: 3.5, + SlopeScaledDepthBias: -0.5, + DepthClipEnable: true.into(), + LineRasterizationMode: D3D12_LINE_RASTERIZATION_MODE_QUADRILATERAL_WIDE, + ForcedSampleCount: 8, + ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON, + }; + let (got, cacheable) = parse(28, bytes(&r2 as *const _ as *const u8, std::mem::size_of_val(&r2))); + assert!(cacheable); + assert_eq!((got.FillMode, got.CullMode, got.DepthBias), (r2.FillMode, r2.CullMode, -3)); + assert!(!got.MultisampleEnable.as_bool() && !got.AntialiasedLineEnable.as_bool()); + assert_eq!((got.ForcedSampleCount, got.ConservativeRaster), (8, r2.ConservativeRaster)); + } + #[test] fn stream_pipeline_defaults_depth_enable_from_dsv_format() { let console_vs = crate::gpu::xbox::tests::sample( @@ -8769,7 +8895,7 @@ mod map_tests { } let desc = StreamDesc { size: stream.len(), ptr: stream.as_ptr() as usize }; match unsafe { stream_pipeline(&desc as *const _ as *const c_void) } { - StreamPipeline::Graphics(g) => *g, + StreamPipeline::Graphics(g, _) => *g, _ => panic!("expected graphics stream pipeline"), } }; From e04168436a9c311137fb08059e3bd8d5a0198dd8 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:50:08 -0800 Subject: [PATCH 097/265] Recompiler: remap wave-local split-wave64 groups Run eligible split-wave64 compute programs as independent 64-thread hardware groups and scale the dispatch dimension, avoiding cross-wave spin coordination. Preserve console group/thread IDs in generated HLSL and keep direct-DXIL pipelines unremapped.\n\nBuild an unremapped worker fallback for indirect dispatch or dimension overflow, with OOM cooldown, stand-in resolution, and fail-closed skip behavior. Retain fallback device/root-signature ownership and drop cache entries outside their mutex to avoid reentrant Release deadlocks.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/dxc.rs | 5 + crates/xcl/src/gpu/recomp/emit.rs | 53 ++++++++++- crates/xcl/src/gpu/recomp/mod.rs | 9 +- crates/xcl/src/gpu/recomp/pso.rs | 64 ++++++++----- crates/xcl/src/gpu/recomp/runner.rs | 8 ++ crates/xcl/src/gpu/recomp/tests.rs | 49 ++++++++-- crates/xcl/src/hle/d3d12x/bind.rs | 13 +++ crates/xcl/src/hle/d3d12x/pso_async.rs | 24 +++++ crates/xcl/src/hle/d3d12x/real.rs | 95 +++++++++++++++++++ .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 62 +++++++++++- crates/xcl/src/shaders.rs | 5 +- 11 files changed, 345 insertions(+), 42 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index dbf8fb24d7..8962fa6397 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -684,6 +684,11 @@ impl LinkGate { static LINK_GATE: LinkGate = LinkGate::new(); +pub(crate) fn is_oom_error(err: &str) -> bool { + let lower = err.to_ascii_lowercase(); + lower.contains("0x8007000e") || lower.contains("e_outofmemory") +} + /// `XCL_LINK_MEM=0`: every program is compiled whole (into the same cache: compare with /// another `XCL_DXIL_CACHE`). fn linking() -> bool { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index ee2acf3647..7d259d55ac 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -72,6 +72,8 @@ pub(super) struct Em { /// LDS arrival barrier (`xcl_s_barrier`) so RDNA2 early `s_endpgm`, `LOOP_GUARD` exits, /// or split-wave64 desyncs cannot permanently hang an NVIDIA SM at `bar.sync`. safe_barrier: bool, + /// any console group barrier; with LDS, this excludes cross-wave-local remapping + has_s_barrier: bool, /// the T# SGPRs of the program's image stores and atomics (`image_write_srsrcs`) img_writes: Vec, /// compute program needs `globallycoherent` on flat memory windows (`needs_coherent_mem`) @@ -624,6 +626,7 @@ impl Em { dynamic_f16_rm: false, track_frexp_denorm: false, safe_barrier: false, + has_s_barrier: false, img_writes: Vec::new(), coherent_mem: false, } @@ -689,6 +692,7 @@ impl Em { } } self.dynamic_f16_rm = writes_nonzero_dp && self.has_f16_round_op && !self.has_f64_round_op; + self.has_s_barrier = has_s_barrier; self.safe_barrier = has_s_barrier && self.compute_or_mesh_hw_waves().is_some_and(|w| w > 1) && std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0"); @@ -4758,11 +4762,42 @@ impl Em { } } + /// Split-wave64 compute whose console waves share neither LDS nor a group barrier: groups per + /// console group, scaled dispatch dimension, and the one-wave hardware group shape. + pub(crate) fn remap(&self) -> Option<(u32, usize, [u32; 3])> { + if self.opt.no_remap || !self.x64() || self.uses_lds || self.has_s_barrier { + return None; + } + let Mode::Compute(cs) = &self.opt.mode else { return None }; + let [x, y, z] = cs.threads; + let threads = x.checked_mul(y)?.checked_mul(z)?; + if x == 0 || threads <= 64 || threads % 64 != 0 { + return None; + } + if x >= 64 && x % 64 == 0 && y == 1 && z == 1 { + return Some((x / 64, 0, [64, 1, 1])); + } + if x <= 64 && 64 % x == 0 { + let rows = 64 / x; + if rows <= y && y % rows == 0 && z == 1 { + return Some((y / rows, 1, [x, rows, 1])); + } + } + None + } + + fn x64_hw_threads(&self) -> u32 { + self.remap().map_or(self.x64_threads(), |_| 64) + } + /// Split wave64: meet through bounded arrival counters (`XCL_X_SPIN 1`) by default so /// divergent wave32 halves can never permanently deadlock a GPU SM at an unbounded /// `GroupMemoryBarrierWithGroupSync()`. Set `XCL_WAVE64_SPIN=0` to force group barriers /// for 1-wave64 groups. fn x64_spin(&self) -> bool { + if self.remap().is_some() { + return false; + } self.x64_threads() > 64 || std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0") } @@ -4775,7 +4810,7 @@ impl Em { /// Storage and functions of the split wave64 form (`PRELUDE_X64`). fn x64_prelude(&self, h: &mut String) { - let threads = self.x64_threads(); + let threads = self.x64_hw_threads(); let waves = threads.div_ceil(64).max(1) as usize; let slot = self.x64_words; // slots (console wave, half, parity), the arrival counters (console wave, half), the @@ -4982,6 +5017,8 @@ impl Em { h.push_str("groupshared uint xcl_lds[8192]; // D3D12 limit: 32 KB (the console allows 64 KB)\n"); } let [x, y, z] = cs.threads; + let remap = self.remap(); + let [nx, ny, nz] = remap.map_or([x, y, z], |(_, _, hw)| hw); // split wave64: the same group in hardware wave32s (a console wave = two of them) let hw_lanes = if self.x64() { 32 } else { lanes }; // 2-D / 3-D groups: the PC driver need not form its waves from consecutive @@ -5002,12 +5039,16 @@ impl Em { self.safe_barrier_prelude(&mut h); let _ = writeln!( h, - "[WaveSize({hw_lanes})]\n[numthreads({x}, {y}, {z})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{" + "[WaveSize({hw_lanes})]\n[numthreads({nx}, {ny}, {nz})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{" ); if self.safe_barrier { h.push_str(" xcl_s_barrier_init(gi);\n"); } - if self.x64() { + if let Some((ratio, dim, _)) = remap { + let d = ["x", "y", "z"][dim]; + h.push_str(" uint xcl_local = xcl_x_thread(gi);\n lane_id = xcl_local & 63u;\n xcl_half = (xcl_local >> 5) & 1u;\n xcl_cw = 0u;\n xcl_xn = XCL_X_THREADS > ((xcl_local & ~31u) ^ 32u) ? min(32u, XCL_X_THREADS - ((xcl_local & ~31u) ^ 32u)) : 0u;\n"); + let _ = writeln!(h, " uint xcl_tid = (gid.{d} % {ratio}u) * 64u + xcl_local;\n gtid = uint3(xcl_tid % {x}u, (xcl_tid / {x}u) % {y}u, xcl_tid / {}u);\n gi = xcl_tid;", x * y); + } else if self.x64() { // the console thread's ids (`xcl_x_thread`), not this hardware thread's self.x64_entry(&mut h); let _ = writeln!(h, " gtid = uint3(xcl_tid % {x}u, (xcl_tid / {x}u) % {y}u, xcl_tid / {}u);\n gi = xcl_tid;", x * y); @@ -5028,7 +5069,11 @@ impl Em { for (k, c) in ["x", "y", "z"].iter().enumerate() { if cs.tgid[k] { if sg.contains(&next) { - let _ = writeln!(h, " {} = gid.{c};", sname(next).unwrap()); + let div = match remap { + Some((ratio, dim, _)) if ["x", "y", "z"][dim] == *c => format!(" / {ratio}u"), + _ => String::new(), + }; + let _ = writeln!(h, " {} = gid.{c}{div};", sname(next).unwrap()); } next += 1; } diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index b5c1a14237..3a7b0520fb 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -533,11 +533,13 @@ pub struct Options { /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, + /// force the console-sized form used when an indirect dispatch cannot scale GPU arguments + pub no_remap: bool, } impl Default for Options { fn default() -> Self { - Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true } + Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true, no_remap: false } } } @@ -557,6 +559,8 @@ pub struct Translation { /// console root signature's static samplers): (S#, comparison), register /// `static_sampler_base + i` in space 1 pub static_samplers: Vec<([u32; 4], bool)>, + /// `(hardware groups per console group, scaled dimension)` for wave-local split-wave64 compute + pub dispatch_remap: Option<(u32, u32)>, } impl Translation { @@ -1637,7 +1641,8 @@ fn translate_inner(code: &[u8], opt: &Options) -> Result { } let hlsl = em.finish(&body); let static_samplers = em.static_used.clone(); - Ok(Translation { hlsl, unsupported: em.unsupported, unsupported_why: em.unsupported_why, ignored: em.ignored, instructions: insts.len(), blocks, static_samplers }) + let dispatch_remap = em.remap().map(|(ratio, dim, _)| (ratio, dim as u32)); + Ok(Translation { hlsl, unsupported: em.unsupported, unsupported_why: em.unsupported_why, ignored: em.ignored, instructions: insts.len(), blocks, static_samplers, dispatch_remap }) } #[cfg(test)] diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index d448906732..ea5597d4d4 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -169,6 +169,7 @@ pub struct Compiled { pub dispatch_chain: Option>, pub dxil: Vec, pub samplers: Vec, + pub dispatch_remap: Option<(u32, u32)>, } /// Translate a console shader for `stage` to signed DXIL (DXC, disk-cached); its static @@ -225,7 +226,7 @@ mod translated { use std::path::{Path, PathBuf}; use std::sync::OnceLock; - const MAGIC: &[u8; 8] = b"XCLTRAN2"; + const MAGIC: &[u8; 8] = b"XCLTRAN3"; const ERR_MAGIC: &[u8; 8] = b"XCLTERR1"; const MAX_CACHED_ERR_BYTES: usize = 64 * 1024; @@ -357,6 +358,9 @@ mod translated { *r = rest; Some(u32::from_le_bytes(*v)) }; + let ratio = u32_(&mut r)?; + let dim = u32_(&mut r)?; + let dispatch_remap = (ratio > 1 && dim < 3).then_some((ratio, dim)); let n = u32_(&mut r)? as usize; if n > r.len() / 17 { return None; @@ -378,7 +382,7 @@ mod translated { let start = b.len() - len; b.copy_within(start.., 0); b.truncate(len); - return Some(Compiled { dxil: b, samplers, dispatch_chain: None }); + return Some(Compiled { dxil: b, samplers, dispatch_chain: None, dispatch_remap }); } else { let dwords_per_group = u32_(&mut rest)?; let count = u32_(&mut rest)?; @@ -395,7 +399,7 @@ mod translated { if !rest.is_empty() { return None; } Some(std::sync::Arc::new(crate::gpu::dxil::kernel::DispatchChain { dwords_per_group, pieces })) }; - Some(Compiled { dxil: whole.to_vec(), samplers, dispatch_chain }) + Some(Compiled { dxil: whole.to_vec(), samplers, dispatch_chain, dispatch_remap }) } pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) { @@ -403,6 +407,9 @@ mod translated { return; } let mut b = header(ident, blob); + let (ratio, dim) = c.dispatch_remap.unwrap_or((1, 0)); + b.extend_from_slice(&ratio.to_le_bytes()); + b.extend_from_slice(&dim.to_le_bytes()); b.extend_from_slice(&(c.samplers.len() as u32).to_le_bytes()); for (s, cmp) in &c.samplers { s.iter().for_each(|v| b.extend_from_slice(&v.to_le_bytes())); @@ -694,7 +701,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: Err(e) => direct_fallback(if stage == Stage::Vertex { "VS" } else { "PS" }, &e), } } - let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64)?; + let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64, false)?; if enormous(stage, t.hlsl.len()) && !crate::gpu::dxil::kernel::enabled() { if dxc::defer() { return Err("DXIL not compiled yet".into()); @@ -742,7 +749,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1); } let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0; - Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }, false)) + Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: t.dispatch_remap }, false)) } /// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`. @@ -800,7 +807,7 @@ fn debug_color(blob: &[u8]) -> Option<[f32; 3]> { /// The HLSL (and its DXC profile) `console_to_dxil` compiles. pub fn console_to_hlsl(blob: &[u8], stage: Stage) -> Result<(String, &'static str), String> { - console_translation(blob, stage, 0, mem_windows(), false).map(|(t, p)| (t.hlsl, p)) + console_translation(blob, stage, 0, mem_windows(), false, false).map(|(t, p)| (t.hlsl, p)) } /// Upper entry cap for `ShaderCache` (the 64 MiB byte limit is the primary bound; a retail game @@ -1019,7 +1026,12 @@ pub fn compute_user_sgprs(blob: &[u8]) -> Option { /// The HLSL and profile a console program compiles from at pipeline creation (for /// `xcl shaders --export-hlsl`: compile-time investigations outside a title). pub fn console_hlsl(blob: &[u8], stage: Stage, windows: u32, split_wave64: bool) -> Result<(String, &'static str), String> { - console_translation(blob, stage, 0, windows, split_wave64).map(|(t, p)| (t.hlsl, p)) + console_translation(blob, stage, 0, windows, split_wave64, false).map(|(t, p)| (t.hlsl, p)) +} + +pub fn console_dxil_noremap(blob: &[u8], split_wave64: bool, windows: u32) -> Result, String> { + let (t, profile) = console_translation(blob, Stage::Compute, 0, windows, split_wave64, true)?; + Ok(dxc::compile_cached(&t.hlsl, "main", profile)?.0) } /// A direct DXIL translation that fell back to the HLSL path: one structured log line @@ -1046,7 +1058,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo Ok(k) => { crate::gpu::dxil::coverage::record_translated("CS per-lane"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }); } Err(e) => { let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e); @@ -1056,7 +1068,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } let k = crate::gpu::dxil::kernel::translate_compute_on(code, o, &cs, split_wave64)?; dump_direct(blob, &k.dxil); - Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers }) + Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) } /// `XCL_DXIL_DUMP=[,…]` (`[SHADER]` hashes, or `all`): writes the direct path's @@ -1091,16 +1103,16 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) - _ => return Err("the shader stage does not match its slot in the PSO".into()), }; dump_direct(blob, &k.dxil); - Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) } -pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(super::Translation, &'static str), String> { +pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, no_remap: bool) -> Result<(super::Translation, &'static str), String> { if let Some(f) = fspx(blob) { if stage != Stage::Compute { return Err("an FSPX (driver) container in a graphics slot".into()); } let cs = super::CsInterface::from_rsrc2(f.threads, f.rsrc2); - let t = translate(f.code, &Options { mode: Mode::Compute(cs), wave64: super::detect_wave64(f.code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let t = translate(f.code, &Options { mode: Mode::Compute(cs), wave64: super::detect_wave64(f.code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, no_remap, ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -1129,7 +1141,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, no_remap, ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -1166,7 +1178,7 @@ fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option return Err(format!("incomplete translation, missing: {missing:?}")); } let cs = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs, samplers: t.static_samplers }, record, ps) + finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs, samplers: t.static_samplers, dispatch_remap: None }, record, ps) } fn compile_console_mesh( @@ -1192,7 +1204,7 @@ fn compile_console_mesh( Ok(k) => { crate::gpu::dxil::coverage::record_translated("MS"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }); } Err(e) => direct_fallback("MS", &e), } @@ -1203,7 +1215,7 @@ fn compile_console_mesh( return Err(format!("incomplete translation, missing: {missing:?}")); } let dxil = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: None }) } fn console_mesh_with( @@ -1533,10 +1545,10 @@ mod shader_cache_tests { fn translations_on_disk_need_the_same_bytes_and_identity() { let dir = std::env::temp_dir().join(format!("xcl-translated-{}", std::process::id())); let path = dir.join("t.bin"); - let c = Compiled { dispatch_chain: None, dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] }; + let c = Compiled { dispatch_chain: None, dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)], dispatch_remap: Some((2, 1)) }; translated::store_in(&path, 42, b"console", &c); let back = translated::load_in(&path, 42, b"console").expect("stored"); - assert_eq!((back.dxil, back.samplers), (c.dxil.clone(), c.samplers.clone())); + assert_eq!((back.dxil, back.samplers, back.dispatch_remap), (c.dxil.clone(), c.samplers.clone(), c.dispatch_remap)); assert!(translated::load_in(&path, 43, b"console").is_none(), "another identity"); assert!(translated::load_in(&path, 42, b"consolf").is_none(), "other bytes"); let full = std::fs::read(&path).unwrap(); @@ -1769,7 +1781,7 @@ mod shader_cache_tests { // Store a valid entry first, then corrupt only the DXIL payload while keeping the // XCLTRAN2 header and payload length intact (e.g. zeroed blocks after a hard reset). - let valid = Compiled { dispatch_chain: None, dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)] }; + let valid = Compiled { dispatch_chain: None, dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)], dispatch_remap: None }; translated::store_in(&path, ident, blob, &valid); let mut raw = std::fs::read(&path).unwrap(); let dxil_start = raw.len() - valid.dxil.len(); @@ -1788,7 +1800,7 @@ mod shader_cache_tests { let mut calls = 0usize; let rebuilt = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { calls += 1; - Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)] }) + Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)], dispatch_remap: None }) }) .unwrap(); assert_eq!(calls, 1); @@ -1812,20 +1824,20 @@ mod shader_cache_tests { let path = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false); let err = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new() }) + Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None }) }) .err() .expect("invalid fresh DXIL must be rejected"); assert!(err.contains("invalid DXIL container"), "{err}"); assert!(!path.exists(), "invalid fresh DXIL must not be written to disk"); - translated::store_in(&path, ident, blob, &Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new() }); + translated::store_in(&path, ident, blob, &Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None }); assert!(!path.exists(), "store_in must not write an invalid DXIL container"); // A real container emitted by the direct DXIL backend must be accepted and cached. let real_direct = crate::gpu::dxil::shader::Shader::new(crate::gpu::dxil::container::Stage::Compute, (6, 6)).finish([1, 1, 1], None); let stored = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new() }) + Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new(), dispatch_remap: None }) }) .unwrap(); assert_eq!(stored.dxil, real_direct); @@ -1842,6 +1854,7 @@ mod shader_cache_tests { dispatch_chain: None, dxil: synthetic_dxil(marker), samplers: vec![([marker as u32; 4], false)], + dispatch_remap: None, } } @@ -1983,6 +1996,7 @@ mod shader_cache_tests { dispatch_chain: None, dxil, samplers: Vec::new(), + dispatch_remap: None, }) }) }); @@ -2017,6 +2031,7 @@ mod shader_cache_tests { dispatch_chain: None, dxil: vec![0; limit + 1], samplers: Vec::new(), + dispatch_remap: None, }), ); assert!(cache.get(&key(4), b"d").is_none()); @@ -2192,6 +2207,7 @@ mod shader_cache_tests { dispatch_chain: None, dxil, samplers: Vec::new(), + dispatch_remap: None, }) }) }); @@ -2280,7 +2296,7 @@ mod shader_cache_tests { let (res, missed) = dxc::cached_only(|| { translated::cached_in(&dir, ident_v1, deferred_blob, Stage::Compute, 0, 1, false, || { let dxil = dxc::compile_cached_in(&dir, "deferred probe", "main", "cs_6_6")?.0; - Ok(Compiled { dxil, samplers: Vec::new(), dispatch_chain: None }) + Ok(Compiled { dxil, samplers: Vec::new(), dispatch_chain: None, dispatch_remap: None }) }) }); assert!(res.is_err() && missed); diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index f738b41485..e2f49929fd 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1612,6 +1612,14 @@ pub fn try_create_texture(desc: &D3D12_RESOURCE_DESC) -> Result<(), String> { /// A compute shader with the console dispatch ABI (`Mode::Compute`): `groups` thread groups, /// u0 = user SGPRs, u2 = flat memory. Returns the memory afterwards. pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Result, String> { + dispatch_remapped(dxil, groups, None, sgprs, mem) +} + +pub fn dispatch_remapped(dxil: &[u8], mut groups: [u32; 3], remap: Option<(u32, u32)>, sgprs: &[u32], mem: &[u32]) -> Result, String> { + if let Some((ratio, dim)) = remap { + let count = groups.get_mut(dim as usize).ok_or("invalid remap dimension")?; + *count = count.checked_mul(ratio).ok_or("remapped dispatch overflows")?; + } let mut g = GPU.lock().unwrap(); let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; let pso: ID3D12PipelineState = unsafe { diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0b018edc36..37fd347cd4 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -72,10 +72,13 @@ fn kernel_wave(code: &[u8], wave64: bool) -> (Vec, Vec) { /// `XCL_DIRECT_DXIL=1`: the direct DXIL translator's kernel for a kernel-mode program with /// one memory window (else `hlsl`, the HLSL path's container). +fn direct_enabled(opt: &Options) -> bool { + runner::direct_dxil() && opt.mem_windows <= 4 && (opt.hw_wave == 0 || (opt.hw_wave == 32 && !opt.wave64)) +} + fn direct_or(code: &[u8], opt: &Options, hlsl: Vec) -> Vec { use crate::gpu::dxil::kernel::{translate, translate_compute, KernelOptions}; - let windows = opt.mem_windows <= 4 && (opt.hw_wave == 0 || (opt.hw_wave == 32 && !opt.wave64)); - if !runner::direct_dxil() || !windows { + if !direct_enabled(opt) { return hlsl; } let split = opt.wave64 && (opt.split_wave64 || runner::split_wave64()); @@ -7305,6 +7308,7 @@ fn gpu_split_wave64_local_and_exchanged_masks_in_diverging_waves() { assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 1, "the v_cmp: read whole by the odd waves"); assert_eq!(t.hlsl.matches("= xcl_x_ballot_local(and(").count(), 2, "the carries"); } + let remap = if direct_enabled(&opt) { None } else { t.dispatch_remap }; let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); let base = 0x100usize; let mut io = vec![0u32; 128]; @@ -7312,7 +7316,7 @@ fn gpu_split_wave64_local_and_exchanged_masks_in_diverging_waves() { io[1] = dims[0]; io[2] = dims[0] * dims[1]; let groups = 3usize; - let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &io, &vec![0u32; (base + groups * 256 * 16) / 4]).unwrap(); + let out = runner::dispatch_remapped(&dxil, [groups as u32, 1, 1], remap, &io, &vec![0u32; (base + groups * 256 * 16) / 4]).unwrap(); for g in 0..groups { for tid in 0..threads as usize { let (w, l) = (tid / 64, (tid % 64) as u32); @@ -7380,9 +7384,10 @@ fn gpu_split_wave64_waves_diverge() { let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); - if runner::split_wave64() && std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0") { + if runner::split_wave64() && t.dispatch_remap.is_none() && std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0") { assert!(t.hlsl.contains("[WaveSize(32)]") && t.hlsl.contains("#define XCL_X_SPIN 1"), "{dims:?}"); } + let remap = if direct_enabled(&opt) { None } else { t.dispatch_remap }; let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); let base = 0x100usize; let mut io = vec![0u32; 128]; @@ -7390,7 +7395,7 @@ fn gpu_split_wave64_waves_diverge() { io[1] = dims[0]; io[2] = dims[0] * dims[1]; let groups = 3usize; - let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &io, &vec![0u32; (base + groups * 256 * 8) / 4]).unwrap(); + let out = runner::dispatch_remapped(&dxil, [groups as u32, 1, 1], remap, &io, &vec![0u32; (base + groups * 256 * 8) / 4]).unwrap(); for g in 0..groups { for tid in 0..threads as usize { let (w, l) = (tid / 64, tid % 64); @@ -7403,6 +7408,37 @@ fn gpu_split_wave64_waves_diverge() { } } +#[test] +fn wave_local_remap_decision_and_console_ids() { + use super::{CsInterface, Mode, Options}; + let store = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 0), ("SADDR", 0x7D)], None), + ]); + let translate_as = |code: &[u8], threads, tgid, no_remap| { + let cs = CsInterface { threads, user_sgprs: 2, tgid, tg_size: false, tid_components: 3 }; + translate(code, &Options { mode: Mode::Compute(cs), wave64: true, split_wave64: true, no_remap, ..Default::default() }).unwrap() + }; + for (threads, remap, shape, group_id) in [ + ([128, 1, 1], Some((2, 0)), "numthreads(64, 1, 1)", "gid.x / 2u"), + ([8, 16, 1], Some((2, 1)), "numthreads(8, 8, 1)", "gid.y / 2u"), + ([256, 1, 1], Some((4, 0)), "numthreads(64, 1, 1)", "gid.x / 4u"), + ] { + let t = translate_as(&store, threads, [true; 3], false); + assert_eq!(t.dispatch_remap, remap, "{threads:?}"); + assert!(t.hlsl.contains(shape) && t.hlsl.contains(group_id), "{threads:?}"); + assert!(t.hlsl.contains("#define XCL_X_SPIN 0"), "{threads:?}"); + } + let barrier = prog(&[("S_BARRIER", "ENC_SOPP", &[], None)]); + let lds = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 0)], None)]); + for (code, threads) in [(&store[..], [8, 8, 4]), (&store[..], [96, 1, 1]), (&barrier, [128, 1, 1]), (&lds, [128, 1, 1])] { + assert_eq!(translate_as(code, threads, [false; 3], false).dispatch_remap, None, "{threads:?}"); + } + let fallback = translate_as(&store, [128, 1, 1], [false; 3], true); + assert_eq!(fallback.dispatch_remap, None); + assert!(fallback.hlsl.contains("numthreads(128, 1, 1)") && fallback.hlsl.contains("#define XCL_X_SPIN 1")); +} + /// What the split wave64 form costs (`cargo test --release -- --ignored bench_split_wave64 /// --nocapture`): a loop of a few VALU instructions and one mask (`v_cmp`, an exchange in the /// split form), plus a readfirstlane (another exchange) in the second variant, as a wave32 @@ -7510,8 +7546,9 @@ fn gpu_compute_tg_size_counts_a_partial_last_wave() { let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); // `XCL_DIRECT_DXIL=1`: the direct translator's kernel, which sets up TG_SIZE on its own + let remap = if direct_enabled(&opt) { None } else { t.dispatch_remap }; let dxil = direct_or(&p, &opt, super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl))); - let mem = runner::dispatch(&dxil, [1, 1, 1], &[0u32; 128], &vec![0xFFFF_FFFFu32; threads as usize]).unwrap(); + let mem = runner::dispatch_remapped(&dxil, [1, 1, 1], remap, &[0u32; 128], &vec![0xFFFF_FFFFu32; threads as usize]).unwrap(); let waves = threads.div_ceil(lanes); for (k, &got) in mem.iter().take(threads as usize).enumerate() { assert_eq!(got, waves | (k as u32 / lanes) << 6, "{threads} threads, wave{lanes}: thread {k}"); diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index ea4a481462..cdd26ca9bf 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -358,6 +358,19 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us match bind_abi(this, list, pso, gfx) { Ok(()) => { if compute { + if super::real::pso_dispatch_remap(pso).is_some() { + match super::real::remap_fallback::whole(pso) { + Ok(fallback) => list.SetPipelineState(&fallback), + Err(e) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect remap fallback skipped: {e}"); + } + count(DISPATCHES_SKIPPED); + return; + } + } + } match super::real::dispatch_chain::whole(pso) { Ok(Some(whole)) => list.SetPipelineState(&whole), Ok(None) => {} diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index b7517dd645..d54bb6c580 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -653,6 +653,21 @@ pub(super) fn build_pieces(jobs: Vec) -> Vec { results } +/// Run one demanded auxiliary pipeline build on the foreground worker queue and wait for it. +/// Unlike `build_pieces`, the caller never drains or executes the job itself. +pub(super) fn build_foreground(job: Job) -> usize { + let build = Arc::new(Build::new(job, false)); + build.want(); + schedule(&build, Priority::Foreground, false, None); + let _held = Held::new(); + let _stall = crate::stall::span(crate::stall::StallKind::PipelineWait); + let mut done = build.done.lock().unwrap(); + while !*done { + done = build.cv.wait(done).unwrap(); + } + build.real.load(Ordering::Acquire) +} + /// Release a pipeline state XCL owns (raw pointer, 0 = none). pub fn release(p: usize) { if p != 0 { @@ -870,6 +885,15 @@ fn preload_enabled() -> bool { mod used_tests { use super::*; + #[test] + fn demanded_auxiliary_build_runs_on_a_worker() { + let caller = std::thread::current().id(); + assert_eq!(build_foreground(Box::new(move || { + assert_ne!(std::thread::current().id(), caller); + 0x7E57_C0DE + })), 0x7E57_C0DE); + } + #[test] fn coalescing_counter_math_tracks_lifetime_current_and_peak() { let counters = CoalescingCounters::new(); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e6b9e0ec30..442da8fbcd 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1847,6 +1847,10 @@ fn forget_pso(pso: usize) { if let Some(m) = PSO_USER_SGPRS.lock().unwrap().as_mut() { m.remove(&pso); } + if let Some(m) = PSO_DISPATCH_REMAP.lock().unwrap().as_mut() { + m.remove(&pso); + } + remap_fallback::forget(pso); super::device_x::forget_base(pso); // the compute pass goes with the last user of its entry (`Drop for TwoPassPso`) let gone = TWO_PASS.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)); @@ -3931,6 +3935,7 @@ fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) { /// user SGPRs of the console CS of a translated compute pipeline static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); +static PSO_DISPATCH_REMAP: Mutex>> = Mutex::new(None); /// How many user SGPRs the console compute shader of a translated pipeline has (None: not /// known). What is above the driver's four holds root arguments (`console_list::inline_for`). @@ -3939,6 +3944,24 @@ pub fn pso_user_sgprs(pso: usize) -> Option { PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).copied() } +pub fn pso_dispatch_remap(pso: usize) -> Option<(u32, u32)> { + let pso = super::pso_async::resolve(pso); + PSO_DISPATCH_REMAP.lock().unwrap().as_ref()?.get(&pso).copied() +} + +fn note_pso_dispatch_remap(pso: *mut c_void, remap: Option<(u32, u32)>) { + if pso.is_null() { + return; + } + let mut guard = PSO_DISPATCH_REMAP.lock().unwrap(); + let map = guard.get_or_insert_with(HashMap::new); + if let Some(remap) = remap { + map.insert(pso as usize, remap); + } else { + map.remove(&(pso as usize)); + } +} + /// The root signature a translated pipeline state was created with. pub fn pso_root_signature(pso: usize) -> Option { let pso = super::pso_async::resolve(pso); @@ -4445,6 +4468,9 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } + note_pso_dispatch_remap(*ppv, compiled.dispatch_remap); + remap_fallback::note(*ppv as usize, this, f, rs as usize, d.Flags, d.NodeMask, record, cs, + wave32_only(this), crate::gpu::recomp::pso::mem_windows(), compiled.dispatch_remap.is_some()); note_translated_compute(hr, ppv); crate::xlog_info!( "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", @@ -4458,6 +4484,75 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const pub(super) mod dispatch_chain; pub(crate) use dispatch_chain::log_counts as log_dispatch_chain_counts; +pub(super) mod remap_fallback { + use super::*; + use std::sync::{Arc, LazyLock}; + + struct Fallback { + device: ID3D12Device, + create: PsoFn, + signature: ID3D12RootSignature, + flags: D3D12_PIPELINE_STATE_FLAGS, + node: u32, + record: u64, + cs: Vec, + split_wave64: bool, + windows: u32, + whole: dispatch_chain::WholeBuild, + } + + static FALLBACKS: LazyLock>>> = LazyLock::new(Default::default); + + pub(super) fn compile_error_hr(err: &str) -> HRESULT { + if crate::gpu::recomp::dxc::is_oom_error(err) { E_OUTOFMEMORY } else { E_INVALIDARG } + } + + pub(super) unsafe fn note(pso: usize, this: *mut c_void, create: PsoFn, rs: usize, + flags: D3D12_PIPELINE_STATE_FLAGS, node: u32, record: u64, cs: &[u8], split_wave64: bool, windows: u32, remapped: bool) { + if remapped && pso != 0 { + let Some(device) = ID3D12Device::from_raw_borrowed(&this) else { return }; + let raw_rs = rs as *mut c_void; + let Some(signature) = ID3D12RootSignature::from_raw_borrowed(&raw_rs) else { return }; + let old = FALLBACKS.lock().unwrap().insert(pso, Arc::new(Fallback { + device: device.clone(), create, signature: signature.clone(), flags, node, record, cs: cs.to_vec(), split_wave64, windows, + whole: dispatch_chain::WholeBuild::new(), + })); + drop(old); + } + } + + pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result { + let pso = super::super::pso_async::resolve(pso); + let fb = FALLBACKS.lock().unwrap().get(&pso).cloned().ok_or("no remap fallback")?; + fb.whole.get_or_build(std::time::Instant::now(), || { + let status = Arc::new(std::sync::atomic::AtomicI32::new(E_INVALIDARG)); + let (job_fb, job_status) = (fb.clone(), status.clone()); + let raw = super::super::pso_async::build_foreground(Box::new(move || unsafe { + let dxil = match crate::gpu::recomp::pso::console_dxil_noremap(&job_fb.cs, job_fb.split_wave64, job_fb.windows) { + Ok(dxil) => dxil, + Err(e) => { + job_status.store(compile_error_hr(&e), Ordering::Release); + return 0 + } + }; + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: job_fb.node, Flags: job_fb.flags, ..Default::default() }; + let mut raw = std::ptr::null_mut(); + let (hr, _, _) = compute_container(job_fb.device.as_raw(), job_fb.create, &desc, + job_fb.signature.as_raw(), &dxil, job_fb.record, &pc_iid(Kind::PipelineState), &mut raw, ComputeBuild::Whole); + job_status.store(hr, Ordering::Release); + if hr >= 0 { raw as usize } else { 0 } + })); + if raw != 0 { Ok(ID3D12PipelineState::from_raw(raw as *mut c_void)) } + else { Err(status.load(Ordering::Acquire)) } + }).map_err(|hr| format!("un-remapped compute pipeline ({hr:#x})")) + } + + pub(super) fn forget(pso: usize) { + let gone = FALLBACKS.lock().unwrap().remove(&pso); + drop(gone); + } +} + #[derive(Clone, Copy, PartialEq)] enum ComputeBuild { Whole, diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index d7c0b603a3..8b84548a04 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -50,17 +50,17 @@ impl PipelineBuilder { /// One exact chain's whole-form outcome. The owning `Chain` fixes device, DXIL, root signature, /// flags and node; releasing/recreating the pipeline gets a fresh outcome. -struct WholeBuild { +pub(super) struct WholeBuild { result: OnceLock>, retry_at: Mutex>, } impl WholeBuild { - fn new() -> Self { + pub(super) fn new() -> Self { Self { result: OnceLock::new(), retry_at: Mutex::new(None) } } - fn get_or_build(&self, now: std::time::Instant, build: impl FnOnce() -> Result) -> Result { + pub(super) fn get_or_build(&self, now: std::time::Instant, build: impl FnOnce() -> Result) -> Result { if let Some(result) = self.result.get() { return result.clone(); } @@ -234,13 +234,35 @@ unsafe fn scratch_buffer(dev: &ID3D12Device, bytes: u64) -> Option) -> Option<[u32; 3]> { + if let Some((ratio, dim)) = remap { + let count = grid.get_mut(dim as usize)?; + let scaled = count.checked_mul(ratio)?; + // D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION (an SDK macro, not in windows-rs). + if scaled > 65_535 { + return None; + } + *count = scaled; + } + Some(grid) +} + /// Called with the original six ABI views bound. The extended signature is /// common to every piece and the whole fallback. Choose before recording any /// part of the dispatch, including when scratch allocation fails. pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, grid: [u32; 3]) -> Result<(), String> { let [x, y, z] = grid; let chain = CHAINS.lock().unwrap().get(&pso).cloned(); - let Some(chain) = chain else { list.Dispatch(x, y, z); return Ok(()) }; + let Some(chain) = chain else { + match remapped_grid(grid, super::pso_dispatch_remap(pso)) { + Some([x, y, z]) => list.Dispatch(x, y, z), + None => { + list.SetPipelineState(&super::remap_fallback::whole(pso)?); + list.Dispatch(x, y, z); + } + } + return Ok(()) + }; if grid.contains(&0) { return Ok(()); } // A title Reset can switch to a different PC allocator while this // recording is still submitted on the old one. Retain by backing. @@ -274,6 +296,24 @@ mod tests { const MB: u64 = 1 << 20; + #[test] + fn remapped_grid_scales_only_its_dimension_and_refuses_overflow() { + assert_eq!(remapped_grid([3, 5, 7], Some((4, 1))), Some([3, 20, 7])); + assert_eq!(remapped_grid([3, 5, 7], None), Some([3, 5, 7])); + assert_eq!(remapped_grid([32_768, 1, 1], Some((2, 0))), None); + assert_eq!(remapped_grid([u32::MAX, 1, 1], Some((2, 0))), None); + assert_eq!(remapped_grid([1, 1, 1], Some((2, 3))), None); + } + + #[test] + fn released_pipeline_does_not_lend_its_remap_to_address_reuse() { + let pso = 0x7E57_6400usize; + super::super::note_pso_dispatch_remap(pso as *mut c_void, Some((4, 0))); + assert_eq!(super::super::pso_dispatch_remap(pso), Some((4, 0))); + super::super::forget_pso_for_test(pso); + assert_eq!(super::super::pso_dispatch_remap(pso), None); + } + #[test] fn a_list_recorded_after_another_goes_on_in_its_scratch() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; @@ -345,4 +385,18 @@ mod tests { assert_eq!(whole.get_or_build(at + WHOLE_RETRY * 2, || { calls += 1; Ok(8) }), Ok(7)); assert_eq!(calls, 2, "the successful retry is retained"); } + + #[test] + fn remap_compile_oom_retries_but_deterministic_failure_is_final() { + let at = std::time::Instant::now(); + let oom = super::super::remap_fallback::compile_error_hr("DXC: E_OUTOFMEMORY (0x8007000E)"); + let whole: WholeBuild = WholeBuild::new(); + assert_eq!(whole.get_or_build(at, || Err(oom)), Err(crate::util::E_OUTOFMEMORY)); + assert_eq!(whole.get_or_build(at + WHOLE_RETRY, || Ok(7)), Ok(7)); + + let compile = super::super::remap_fallback::compile_error_hr("dxc: invalid operation"); + let deterministic: WholeBuild = WholeBuild::new(); + assert_eq!(deterministic.get_or_build(at, || Err(compile)), Err(crate::util::E_INVALIDARG)); + assert_eq!(deterministic.get_or_build(at + WHOLE_RETRY, || Ok(8)), Err(crate::util::E_INVALIDARG)); + } } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 633805fcd8..ef5fca9440 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1141,7 +1141,7 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl unsafe { dev9.ShaderCacheControl(cache_kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) } .map_err(|e| Unavailable(format!("cannot disable the driver cache (Windows Developer Mode is required): {e}")))?; let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::pso::wave32_only_for_device(&pipeline.dev)); - let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?; + let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split, false).map_err(|e| Failed(format!("{name}: {e}")))?; let dxc_start = std::time::Instant::now(); let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?; let dxc_ms = dxc_start.elapsed().as_millis(); @@ -1272,7 +1272,7 @@ mod pipeline_cap_tests { pipelines.max_dxil = dxil.len() - 1; let start = Instant::now(); - pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![] }, Some(path.clone())); + pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![], dispatch_remap: None }, Some(path.clone())); let elapsed = start.elapsed(); let capped = pipelines.capped.load(Ordering::Relaxed); let made = pipelines.made.load(Ordering::Relaxed); @@ -1353,6 +1353,7 @@ mod pipeline_cap_tests { })), dxil: whole.clone(), samplers: vec![], + dispatch_remap: None, }; pipelines.max_dxil = max_piece; From e564cbb71fd5bef54f632f4bf01755ace42e8aa0 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:51:11 -0800 Subject: [PATCH 098/265] D3D12.X: prepare asynchronous texture downloads Add a non-activated immutable plan for copying selected GPU-owned texture subresources into a retained readback resource. Validate exact XG element geometry, driver footprints, explicit states, source/queue device identity, and direct-queue ownership before execution.\n\nSubmission transfers every referenced COM object into a fence ticket before ExecuteCommandLists. Incomplete, signal-failed, or device-removed tickets fail closed by retaining GPU-owned objects; completed mapping is nonblocking and fallibly allocated. Selection validation is bounded and linear.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 394 ++++++++++++++++++++ crates/xcl/src/hle/xg.rs | 2 + 2 files changed, 396 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 8479e120c5..67c97e8eca 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1872,6 +1872,311 @@ pub(super) fn reverse_layout_subresource( Ok(()) } +#[derive(Clone, Copy, Debug)] +#[allow(dead_code)] +pub(super) struct DownloadSubresource { + pub subresource: u32, + pub state: D3D12_RESOURCE_STATES, + pub footprint: ReadbackFootprint, +} + +/// Validate driver footprints against the immutable XG layout and explicit tracked states. +/// The driver may add only the required D3D row/placement alignment, never enlarge the work. +fn validate_download_layout( + tex: &xg::Texture, + desc: &D3D12_RESOURCE_DESC, + format: u32, + selected: &[(u32, D3D12_RESOURCE_STATES)], + driver: &[(D3D12_PLACED_SUBRESOURCE_FOOTPRINT, u32, u64)], +) -> Result<(Vec, usize), String> { + let surface = tex.texels().ok_or("no texel surface")?; + let (elem_log2, side) = xg::element(format).ok_or("unsupported texture format")?; + if tex.main != 0 + || tex.planes.len() != 1 + || surface.bpe != 1u32 << elem_log2 + || surface.side != side + || desc.Dimension.0 as u32 != tex.dimension() + || desc.SampleDesc.Count != 1 + || desc.SampleDesc.Quality != 0 + || desc.Format.0 as u32 != format + { + return Err("unsupported metadata, samples, or format conversion".into()); + } + let mips = surface.chain.levels.len(); + let layers = if surface.depth > 0 { surface.depth } else { surface.array }; + if desc.Width != surface.width as u64 + || desc.Height != surface.height + || desc.DepthOrArraySize as u32 != layers + || desc.MipLevels as usize != mips + || selected.is_empty() + || selected.len() != driver.len() + { + return Err("resource shape or selection differs from the retained layout".into()); + } + let subresources = if surface.depth > 0 { mips } else { mips.checked_mul(surface.array as usize).ok_or("subresource count overflow")? }; + let mut seen = Vec::new(); + seen.try_reserve_exact(subresources).map_err(|_| "cannot allocate download selection")?; + seen.resize(subresources, false); + let mut out = Vec::new(); + out.try_reserve_exact(selected.len()).map_err(|_| "cannot allocate download layout")?; + let mut total = 0usize; + for (&(subresource, state), &(placed, rows, driver_row_bytes)) in selected.iter().zip(driver) { + if state.0 < 0 { + return Err("invalid tracked resource state".into()); + } + let sub = subresource as usize; + let (mip, depth) = if surface.depth > 0 { + if sub >= mips { return Err("subresource out of range".into()) } + (sub, (surface.depth >> sub).max(1)) + } else { + let count = mips.checked_mul(surface.array as usize).ok_or("subresource count overflow")?; + if sub >= count { return Err("subresource out of range".into()) } + (sub % mips, 1) + }; + if std::mem::replace(&mut seen[sub], true) { return Err("duplicate subresource".into()) } + let level = &surface.chain.levels[mip]; + let width = (surface.width >> mip).max(1); + let height = (surface.height >> mip).max(1); + let row_bytes = level.width.checked_mul(surface.bpe as usize).ok_or("row size overflow")?; + let expected_pitch = row_bytes.checked_next_multiple_of(256).ok_or("row pitch overflow")?; + let expected_offset = total.checked_next_multiple_of(512).ok_or("footprint offset overflow")?; + if placed.Offset != expected_offset as u64 + || placed.Footprint.Format.0 as u32 != format + || placed.Footprint.Width != width + || placed.Footprint.Height != height + || placed.Footprint.Depth != depth + || placed.Footprint.RowPitch as usize != expected_pitch + || rows as usize != level.height + || driver_row_bytes != row_bytes as u64 + || level.depth != depth as usize + { + return Err("driver footprint differs from the exact subresource".into()); + } + let slice_pitch = expected_pitch.checked_mul(level.height).ok_or("slice pitch overflow")?; + let used = slice_pitch + .checked_mul(level.depth.saturating_sub(1)) + .and_then(|n| n.checked_add(expected_pitch.checked_mul(level.height.saturating_sub(1))?)) + .and_then(|n| n.checked_add(row_bytes)) + .ok_or("footprint size overflow")?; + total = expected_offset.checked_add(used).ok_or("download size overflow")?; + out.push(DownloadSubresource { + subresource, + state, + footprint: ReadbackFootprint { offset: expected_offset, size: used, row_pitch: expected_pitch, width, height, depth, format }, + }); + } + Ok((out, total)) +} + +struct DownloadObjects { + _source: ID3D12Resource, + readback: ID3D12Resource, + _allocator: ID3D12CommandAllocator, + list: ID3D12CommandList, + _queue: ID3D12CommandQueue, + _fence_hold: ID3D12Fence, +} + +/// A closed command list and every object it may reference. The caller must hold its state/order +/// serialization from the supplied state snapshot until `submit` inserts this list immediately +/// after the writers represented by that snapshot; otherwise the recorded barriers are stale. +#[allow(dead_code)] +pub(super) struct TextureDownloadPlan { + device: ID3D12Device, + tex: Arc, + source: ID3D12Resource, + readback: ID3D12Resource, + allocator: ID3D12CommandAllocator, + list: ID3D12CommandList, + fence: ID3D12Fence, + footprints: Vec, + bytes: usize, +} + +#[allow(dead_code)] +pub(super) struct SubmittedDownload { + pub ticket: PendingDownload, + /// `Some` means Execute had no reportable result and the following Signal failed. The ticket + /// can never be mapped and deliberately retains/leaks its objects rather than releasing them. + pub signal_error: Option, +} + +#[allow(dead_code)] +pub(super) struct PendingDownload { + tex: Arc, + objects: Option, + fence: ID3D12Fence, + fence_value: Option, + footprints: Vec, + bytes: usize, +} + +impl Drop for PendingDownload { + fn drop(&mut self) { + let done = self.fence_value.is_some_and(|v| { + let got = unsafe { self.fence.GetCompletedValue() }; + got != u64::MAX && got >= v + }); + if !done { + if let Some(objects) = self.objects.take() { + std::mem::forget(objects); + } + } + } +} + +#[allow(dead_code)] +impl PendingDownload { + pub fn is_complete(&self) -> bool { + self.fence_value.is_some_and(|v| { + let got = unsafe { self.fence.GetCompletedValue() }; + got != u64::MAX && got >= v + }) + } + + /// Copy the mapped readback only after the submission fence is observed. No wait is done. + pub unsafe fn readback_bytes(&self) -> Result>, String> { + if !self.is_complete() { + return Ok(None); + } + let objects = self.objects.as_ref().ok_or("download objects unavailable")?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(self.bytes).map_err(|_| "cannot allocate completed texture download")?; + let mut p = std::ptr::null_mut(); + objects + .readback + .Map(0, Some(&D3D12_RANGE { Begin: 0, End: self.bytes }), Some(&mut p)) + .map_err(|e| e.to_string())?; + if p.is_null() { + objects.readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + return Err("readback Map returned no address".into()); + } + bytes.extend_from_slice(std::slice::from_raw_parts(p as *const u8, self.bytes)); + objects.readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + Ok(Some(bytes)) + } + + pub fn footprints(&self) -> &[DownloadSubresource] { &self.footprints } + pub fn layout(&self) -> &xg::Texture { &self.tex } +} + +#[allow(dead_code)] +impl TextureDownloadPlan { + /// Execute the already-closed list at the caller's serialized queue position. Ownership is + /// transferred to the pending ticket before Execute because ExecuteCommandLists has no status. + pub unsafe fn submit(self, queue: &ID3D12CommandQueue) -> Result { + let mut queue_device: Option = None; + queue.GetDevice(&mut queue_device).map_err(|e| e.to_string())?; + if queue.GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT + || queue_device.as_ref().is_none_or(|d| d.as_raw() != self.device.as_raw()) + { + return Err("texture download requires a direct queue from its source device".into()); + } + let mut pending = PendingDownload { + tex: self.tex, + objects: Some(DownloadObjects { + _source: self.source, + readback: self.readback, + _allocator: self.allocator, + list: self.list, + _queue: queue.clone(), + _fence_hold: self.fence.clone(), + }), + fence: self.fence, + fence_value: None, + footprints: self.footprints, + bytes: self.bytes, + }; + let list = pending.objects.as_ref().unwrap().list.clone(); + queue.ExecuteCommandLists(&[Some(list)]); + let signal_error = match queue.Signal(&pending.fence, 1) { + Ok(()) => { pending.fence_value = Some(1); None } + Err(e) => Some(e.to_string()), + }; + Ok(SubmittedDownload { ticket: pending, signal_error }) + } +} + +/// Build but do not submit a download. Preparation performs no global lookup or queue operation. +#[allow(dead_code)] +pub(super) unsafe fn prepare_texture_download( + dev: &ID3D12Device, + source: &ID3D12Resource, + tex: Arc, + format: u32, + selected: &[(u32, D3D12_RESOURCE_STATES)], +) -> Result { + let mut source_device: Option = None; + source.GetDevice(&mut source_device).map_err(|e| e.to_string())?; + if source_device.as_ref().is_none_or(|d| d.as_raw() != dev.as_raw()) { + return Err("texture download source belongs to another device".into()); + } + let desc = source.GetDesc(); + let mut queried = Vec::new(); + queried.try_reserve_exact(selected.len()).map_err(|_| "cannot allocate driver footprints")?; + let mut base = 0u64; + for &(subresource, _) in selected { + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut ignored_total) = (0u32, 0u64, 0u64); + dev.GetCopyableFootprints(&desc, subresource, 1, base, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut ignored_total)); + queried.push((fp, rows, row_bytes)); + let pitch = fp.Footprint.RowPitch as u64; + let slice_pitch = pitch.checked_mul(rows as u64).ok_or("driver footprint overflow")?; + base = fp.Offset + .checked_add(slice_pitch.checked_mul(fp.Footprint.Depth.saturating_sub(1) as u64).ok_or("driver footprint overflow")?) + .and_then(|n| n.checked_add(pitch.checked_mul(rows.saturating_sub(1) as u64)?)) + .and_then(|n| n.checked_add(row_bytes)) + .ok_or("driver footprint overflow")?; + } + let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?; + let allocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(|e| e.to_string())?; + let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).map_err(|e| e.to_string())?; + let mut readback = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ).map_err(|e| e.to_string())?; + let readback = readback.ok_or("no readback resource")?; + let barrier = |subresource, before, after| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(source), Subresource: subresource, StateBefore: before, StateAfter: after, + }) }, + }; + for sub in &footprints { + if sub.state != D3D12_RESOURCE_STATE_COPY_SOURCE { + graphics.ResourceBarrier(&[barrier(sub.subresource, sub.state, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + } + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: sub.footprint.offset as u64, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(format as i32), Width: sub.footprint.width, Height: sub.footprint.height, Depth: sub.footprint.depth, RowPitch: sub.footprint.row_pitch as u32 }, + } } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(source), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub.subresource } }; + graphics.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + if sub.state != D3D12_RESOURCE_STATE_COPY_SOURCE { + graphics.ResourceBarrier(&[barrier(sub.subresource, D3D12_RESOURCE_STATE_COPY_SOURCE, sub.state)]); + } + } + graphics.Close().map_err(|e| e.to_string())?; + let list: ID3D12CommandList = graphics.cast().map_err(|e| e.to_string())?; + let fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| e.to_string())?; + Ok(TextureDownloadPlan { device: dev.clone(), tex, source: source.clone(), readback, allocator, list, fence, footprints, bytes }) +} + #[cfg(test)] mod tests { @@ -2597,6 +2902,95 @@ mod tests { (ReadbackFootprint { offset: 512, size, row_pitch, width: w, height: h, depth, format }, readback, linear) } + fn driver_download_layout( + tex: &xg::Texture, + format: u32, + selected: &[(u32, D3D12_RESOURCE_STATES)], + ) -> Vec<(D3D12_PLACED_SUBRESOURCE_FOOTPRINT, u32, u64)> { + let s = tex.texels().unwrap(); + let mips = s.chain.levels.len(); + let mut end = 0usize; + selected + .iter() + .map(|&(sub, _)| { + let mip = if s.depth > 0 { sub as usize } else { sub as usize % mips }; + let l = &s.chain.levels[mip]; + let row_bytes = l.width * s.bpe as usize; + let pitch = row_bytes.next_multiple_of(256); + let offset = end.next_multiple_of(512); + end = offset + pitch * l.height * (l.depth - 1) + pitch * (l.height - 1) + row_bytes; + ( + D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset as u64, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(format as i32), + Width: (s.width >> mip).max(1), + Height: (s.height >> mip).max(1), + Depth: if s.depth > 0 { (s.depth >> mip).max(1) } else { 1 }, + RowPitch: pitch as u32, + }, + }, + l.height as u32, + row_bytes as u64, + ) + }) + .collect() + } + + #[test] + fn download_layout_preserves_explicit_states_and_bounds_array_and_volume_footprints() { + let array_desc = console_desc(3, 17, 9, 2, 3, 28, 0x105); + let array = xg::Texture::new(&array_desc).unwrap(); + let desc: D3D12_RESOURCE_DESC = unsafe { std::ptr::read_unaligned(super::super::device_x::pc_resource_desc(&array_desc).as_ptr() as *const _) }; + let selected = [(0, D3D12_RESOURCE_STATE_COMMON), (5, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]; + let driver = driver_download_layout(&array, 28, &selected); + let (layout, bytes) = validate_download_layout(&array, &desc, 28, &selected, &driver).unwrap(); + assert_eq!(layout.iter().map(|s| (s.subresource, s.state)).collect::>(), selected); + assert_eq!(bytes, layout.last().unwrap().footprint.offset + layout.last().unwrap().footprint.size); + + let volume_desc = console_desc(4, 32, 16, 8, 4, 28, 0x105); + let volume = xg::Texture::new(&volume_desc).unwrap(); + let desc: D3D12_RESOURCE_DESC = unsafe { std::ptr::read_unaligned(super::super::device_x::pc_resource_desc(&volume_desc).as_ptr() as *const _) }; + let selected = [(0, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), (2, D3D12_RESOURCE_STATE_COPY_SOURCE)]; + let driver = driver_download_layout(&volume, 28, &selected); + let (layout, _) = validate_download_layout(&volume, &desc, 28, &selected, &driver).unwrap(); + assert!(layout[1].footprint.offset >= layout[0].footprint.offset + layout[0].footprint.size); + assert_eq!((layout[1].footprint.width, layout[1].footprint.height, layout[1].footprint.depth), (8, 4, 2)); + } + + #[test] + fn download_layout_rejects_stale_or_driver_enlarged_selections() { + let bytes = console_desc(3, 16, 8, 2, 2, 28, 0x105); + let tex = xg::Texture::new(&bytes).unwrap(); + let desc: D3D12_RESOURCE_DESC = unsafe { std::ptr::read_unaligned(super::super::device_x::pc_resource_desc(&bytes).as_ptr() as *const _) }; + let selected = [(0, D3D12_RESOURCE_STATE_COMMON), (3, D3D12_RESOURCE_STATE_RENDER_TARGET)]; + let exact = driver_download_layout(&tex, 28, &selected); + let mut bad = exact.clone(); + bad[1].0.Footprint.RowPitch += 256; + assert!(validate_download_layout(&tex, &desc, 28, &selected, &bad).is_err()); + let mut bad = exact.clone(); + bad[0].2 += 4; + assert!(validate_download_layout(&tex, &desc, 28, &selected, &bad).is_err()); + let duplicate = [(0, D3D12_RESOURCE_STATE_COMMON), (0, D3D12_RESOURCE_STATE_RENDER_TARGET)]; + assert!(validate_download_layout(&tex, &desc, 28, &duplicate, &driver_download_layout(&tex, 28, &duplicate)).is_err()); + let invalid_state = [(0, D3D12_RESOURCE_STATES(-1))]; + assert!(validate_download_layout(&tex, &desc, 28, &invalid_state, &driver_download_layout(&tex, 28, &invalid_state)).is_err()); + assert!(validate_download_layout(&tex, &desc, 28, &selected[..1], &exact).is_err()); + let mut wrong_dimension = desc; + wrong_dimension.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D; + assert!(validate_download_layout(&tex, &wrong_dimension, 28, &selected, &exact).is_err()); + + let rgba = xg::Texture::new(&console_desc(3, 4, 4, 1, 1, 28, 0x105)).unwrap(); + let bc = console_desc(3, 4, 4, 1, 1, 77, 0x105); // both rows are 16 bytes; block side differs + let bc_desc: D3D12_RESOURCE_DESC = unsafe { std::ptr::read_unaligned(super::super::device_x::pc_resource_desc(&bc).as_ptr() as *const _) }; + let one = [(0, D3D12_RESOURCE_STATE_RENDER_TARGET)]; + assert!(validate_download_layout(&rgba, &bc_desc, 77, &one, &driver_download_layout(&rgba, 77, &one)).is_err()); + let mut rt = console_desc(3, 16, 8, 1, 1, 28, 0x105); + rt[0x30..0x34].copy_from_slice(&1u32.to_le_bytes()); + let rt = xg::Texture::new(&rt).unwrap(); + assert!(validate_download_layout(&rt, &desc, 28, &one, &driver_download_layout(&rt, 28, &one)).is_err()); + } + #[test] fn reverse_layout_tiles_an_edge_array_mip_without_touching_guards() { let tex = xg::Texture::new(&console_desc(3, 17, 9, 2, 3, 28, 0x105)).unwrap(); diff --git a/crates/xcl/src/hle/xg.rs b/crates/xcl/src/hle/xg.rs index 0eec7dc16e..be12ded2ab 100644 --- a/crates/xcl/src/hle/xg.rs +++ b/crates/xcl/src/hle/xg.rs @@ -132,6 +132,8 @@ fn micro(e: u32) -> (usize, usize) { } impl Texture { + pub(crate) fn dimension(&self) -> u32 { self.dimension } + /// From a D3D12_RESOURCE_DESC (0x38 bytes) as the console's. pub fn new(d: &[u8; 0x38]) -> Result { Self::with_pipes(d, crate::gpu::texture::console_pipes()) From fafeee3e8e02ae0967b0b2a0aefdd0b432c431ef Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 22:57:14 -0800 Subject: [PATCH 099/265] D3D12.X: match texture downloads to writer queues Carry the source writer queue type in immutable texture download plans. Record and submit on the same DIRECT or COMPUTE type, while rejecting COPY queues and type/device mismatches before ownership transfer or execution.\n\nThis remains a non-activated preparation for ordered pre-Signal downloads.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 26 +++++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 67c97e8eca..0be066a76e 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1983,6 +1983,7 @@ struct DownloadObjects { #[allow(dead_code)] pub(super) struct TextureDownloadPlan { device: ID3D12Device, + queue_type: D3D12_COMMAND_LIST_TYPE, tex: Arc, source: ID3D12Resource, readback: ID3D12Resource, @@ -2067,10 +2068,10 @@ impl TextureDownloadPlan { pub unsafe fn submit(self, queue: &ID3D12CommandQueue) -> Result { let mut queue_device: Option = None; queue.GetDevice(&mut queue_device).map_err(|e| e.to_string())?; - if queue.GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT + if queue.GetDesc().Type != self.queue_type || queue_device.as_ref().is_none_or(|d| d.as_raw() != self.device.as_raw()) { - return Err("texture download requires a direct queue from its source device".into()); + return Err("texture download queue type or source device differs from its plan".into()); } let mut pending = PendingDownload { tex: self.tex, @@ -2097,15 +2098,23 @@ impl TextureDownloadPlan { } } +fn download_queue_type_supported(ty: D3D12_COMMAND_LIST_TYPE) -> bool { + matches!(ty, D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE) +} + /// Build but do not submit a download. Preparation performs no global lookup or queue operation. #[allow(dead_code)] pub(super) unsafe fn prepare_texture_download( dev: &ID3D12Device, source: &ID3D12Resource, + queue_type: D3D12_COMMAND_LIST_TYPE, tex: Arc, format: u32, selected: &[(u32, D3D12_RESOURCE_STATES)], ) -> Result { + if !download_queue_type_supported(queue_type) { + return Err("texture download requires a direct or compute queue".into()); + } let mut source_device: Option = None; source.GetDevice(&mut source_device).map_err(|e| e.to_string())?; if source_device.as_ref().is_none_or(|d| d.as_raw() != dev.as_raw()) { @@ -2129,8 +2138,8 @@ pub(super) unsafe fn prepare_texture_download( .ok_or("driver footprint overflow")?; } let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?; - let allocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(|e| e.to_string())?; - let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).map_err(|e| e.to_string())?; + let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?; + let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?; let mut readback = None; dev.CreateCommittedResource( &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, @@ -2174,7 +2183,7 @@ pub(super) unsafe fn prepare_texture_download( graphics.Close().map_err(|e| e.to_string())?; let list: ID3D12CommandList = graphics.cast().map_err(|e| e.to_string())?; let fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| e.to_string())?; - Ok(TextureDownloadPlan { device: dev.clone(), tex, source: source.clone(), readback, allocator, list, fence, footprints, bytes }) + Ok(TextureDownloadPlan { device: dev.clone(), queue_type, tex, source: source.clone(), readback, allocator, list, fence, footprints, bytes }) } @@ -2937,6 +2946,13 @@ mod tests { .collect() } + #[test] + fn download_plans_use_writer_capable_queue_types() { + assert!(download_queue_type_supported(D3D12_COMMAND_LIST_TYPE_DIRECT)); + assert!(download_queue_type_supported(D3D12_COMMAND_LIST_TYPE_COMPUTE)); + assert!(!download_queue_type_supported(D3D12_COMMAND_LIST_TYPE_COPY)); + } + #[test] fn download_layout_preserves_explicit_states_and_bounds_array_and_volume_footprints() { let array_desc = console_desc(3, 17, 9, 2, 3, 28, 0x105); From e3a52f43c5830c2ffac0a8f0d8548b1545d6061e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:01:37 -0800 Subject: [PATCH 100/265] D3D12.X: preserve extended rasterizer stream state Adapt the native graphics stream path from PR #2621 so fractional depth bias and Rasterizer2 line modes are not lost through the legacy pipeline descriptor. Unknown or unreadable streams fail closed, and rect-list fallback is limited to E_INVALIDARG. The native stream deliberately remains outside the driver-blob cache; cache lifecycle support is a separate stacked change. Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 289 ++++++++++++++++++++++++++++-- 1 file changed, 279 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 1f70d899b7..7eb2ea974c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6103,7 +6103,9 @@ unsafe fn build_compute(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); - matches!(translated_mesh_stream(dev.0 as *mut c_void, d.ptr(), &iid, out), Some(hr) if hr >= 0) + let this = dev.0 as *mut c_void; + let hr = translated_mesh_stream(this, d.ptr(), &iid, out).or_else(|| translated_graphics_stream(this, d.ptr(), &iid, out)); + matches!(hr, Some(hr) if hr >= 0) } pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { @@ -6780,11 +6782,15 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { const RECT_LIST_TYPE: i32 = 19; /// `create(copy)`, and once more without the generated rect list GS (`rect_gs`) when the driver -/// refuses the pipeline with it: each rect is then drawn as the triangle of its three vertices, +/// refuses the pipeline with E_INVALIDARG: each rect is then drawn as the triangle of its three vertices, /// as without the GS, rather than not at all (the untranslated fallback's dummy shaders). +fn rejected_rect_list_gs(hr: HRESULT, rect_gs: bool) -> bool { + rect_gs && hr == E_INVALIDARG +} + fn retry_without_rect_gs(copy: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect_gs: bool, mut create: impl FnMut(&D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> HRESULT) -> HRESULT { let hr = create(copy); - if hr >= 0 || !rect_gs { + if !rejected_rect_list_gs(hr, rect_gs) { return hr; } note_translation_error(format!("the driver rejected the PSO with the rect list GS ({hr:#x}): rect list drawn as triangles")); @@ -7087,11 +7093,33 @@ mod pso_blend_and_tsharp_tests { enum StreamPipeline { Graphics(Box, bool), + GraphicsStream, Compute(Box), /// neither with console shaders (or not readable) Unknown, } +unsafe fn read_sub(p: &[u8]) -> T { + let mut d: T = std::mem::zeroed(); + put(&mut d, p); + d +} + +fn depth_bias_is_exact_i32(b: f32) -> bool { + b.is_finite() && b >= i32::MIN as f32 && b < 2147483648.0 && b.fract() == 0.0 +} + +unsafe fn stream_needs_extended_rasterizer(subs: &[(u32, &[u8])]) -> bool { + subs.iter().any(|&(ty, p)| match ty { + 27 => !depth_bias_is_exact_i32(read_sub::(p).DepthBias), + 28 => { + let d: D3D12_RASTERIZER_DESC2 = read_sub(p); + !depth_bias_is_exact_i32(d.DepthBias) || d.LineRasterizationMode != D3D12_LINE_RASTERIZATION_MODE_ALIASED + } + _ => false, + }) +} + /// A pipeline stream with a console VS (+ PS / GS) or CS as the plain pipeline desc, which is /// translated like any other (`dev_create_graphics_pso`). The stream itself must not reach the /// driver: AMD's shader compiler fails on the console's stripped DXIL and takes the device with @@ -7107,6 +7135,9 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { return StreamPipeline::Unknown; } let (subs, cacheable) = known_subobjects_checked(std::slice::from_raw_parts(base as *const u8, size)); + if subobjects_have_unreadable_shader(&subs) { + return StreamPipeline::Unknown; + } let console = |ty: u32| subs.iter().find(|s| s.0 == ty).and_then(|s| payload_shader(s.1)).is_some_and(is_console); if console(6) { let mut c: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::mem::zeroed(); @@ -7124,6 +7155,11 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { if !console(1) { return StreamPipeline::Unknown; } + // Unknown/truncated suffixes retain Stage 1's conservative projected, uncacheable path: + // rewriting cannot preserve bytes whose layout is unknown. Console GS needs its two-pass path. + if cacheable && !console(5) && stream_needs_extended_rasterizer(&subs) { + return StreamPipeline::GraphicsStream; + } let mut g: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::mem::zeroed(); // what a stream leaves out has the PC's defaults g.SampleMask = u32::MAX; @@ -7248,14 +7284,138 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { StreamPipeline::Graphics(Box::new(g), cacheable) } +unsafe fn patch_sub(out: &mut StreamOut, ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, payload: &[u8], f: impl FnOnce(&mut T)) { + let mut v: T = std::ptr::read_unaligned(payload.as_ptr() as *const T); + f(&mut v); + out.put(ty, &v); +} + +/// Native stream translation adapted from PR #2621 by Decodere. +unsafe fn rewrite_graphics_stream( + subs: &[(u32, &[u8])], rs: *mut c_void, vs_dxil: &[u8], ps_dxil: Option<&[u8]>, rect_gs: Option<&[u8]>, no_stencil: bool, no_cull: bool, +) -> StreamOut { + let mut out = StreamOut::default(); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &(rs as usize)); + out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, vs_dxil); + if let Some(ps) = ps_dxil { out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps); } + if let Some(gs) = rect_gs { out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, gs); } + let (mut rt_count, mut rt_formats) = (0u32, [windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(0); 8]); + if let Some((_, p)) = subs.iter().find(|(ty, p)| *ty == 15 && p.len() >= 36) { + for (k, ch) in p[..32].chunks_exact(4).enumerate() { + rt_formats[k] = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_target_format(u32::from_le_bytes(ch.try_into().unwrap())) as i32); + } + rt_count = u32::from_le_bytes(p[32..36].try_into().unwrap()); + } + let default_topo = if subs.iter().any(|(ty, p)| *ty == 4 && payload_shader(p).is_some()) { D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH } else { D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE }; + let (mut saw_topology, mut saw_rasterizer) = (false, false); + for &(ty, payload) in subs { + if matches!(ty, 0 | 1 | 2 | 19) || (ty == 5 && rect_gs.is_some()) { continue; } + if matches!(ty, 10 | 27 | 28) { saw_rasterizer = true; } + let (_, palign) = super::null::subobject_payload(ty).unwrap_or((0, 4)); + match ty { + 8 if payload.len() >= std::mem::size_of::() => patch_sub::(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, payload, |b| sanitize_integer_rt_blend(b, rt_count, &rt_formats)), + 10 if no_cull && payload.len() >= std::mem::size_of::() => patch_sub::(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, payload, |r| r.CullMode = D3D12_CULL_MODE_NONE), + 27 if no_cull && payload.len() >= std::mem::size_of::() => patch_sub::(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1, payload, |r| r.CullMode = D3D12_CULL_MODE_NONE), + 28 if no_cull && payload.len() >= std::mem::size_of::() => patch_sub::(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2, payload, |r| r.CullMode = D3D12_CULL_MODE_NONE), + 11 if no_stencil && payload.len() >= std::mem::size_of::() => patch_sub::(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, payload, |d| d.StencilEnable = false.into()), + 21 if no_stencil && payload.len() >= std::mem::size_of::() => patch_sub::(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, payload, |d| d.StencilEnable = false.into()), + 26 if no_stencil && payload.len() >= std::mem::size_of::() => patch_sub::(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2, payload, |d| d.StencilEnable = false.into()), + 14 if payload.len() >= 4 => { + saw_topology = true; + let t = i32::from_le_bytes(payload[0..4].try_into().unwrap()); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, &if (1..=4).contains(&t) { D3D12_PRIMITIVE_TOPOLOGY_TYPE(t) } else { default_topo }); + } + 15 if payload.len() >= 32 => { + let mut p = payload.to_vec(); + for ch in p[..32].chunks_exact_mut(4) { + let f = super::device_x::pc_target_format(u32::from_le_bytes(ch.try_into().unwrap())); + ch.copy_from_slice(&f.to_le_bytes()); + } + out.raw(15, &p, false); + } + 16 if payload.len() >= 4 => out.raw(16, &super::device_x::pc_view_format(u32::from_le_bytes(payload[0..4].try_into().unwrap())).to_le_bytes(), false), + _ => out.raw(ty, payload, palign == 8), + } + } + if !saw_topology { out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, &default_topo); } + if no_cull && !saw_rasterizer { + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, &D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() + }); + } + out +} + +unsafe fn translated_graphics_stream(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + with_switch_fallback(|| translated_graphics_stream_once(this, desc, riid, ppv)) +} + +unsafe fn translated_graphics_stream_once(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; + if !crate::gpu::shader::readable(desc as usize, 16) { return None; } + let (size, base) = (*(desc as *const usize), *((desc as usize + 8) as *const usize)); + if !crate::gpu::shader::readable(base, size) { return None; } + let (subs, cacheable) = known_subobjects_checked(std::slice::from_raw_parts(base as *const u8, size)); + if !cacheable { return None; } + if subobjects_have_unreadable_shader(&subs) { return Some(E_INVALIDARG); } + let vs = subs.iter().find(|s| s.0 == 1).and_then(|s| payload_shader(s.1)).filter(|b| is_console(b))?; + if subs.iter().any(|s| matches!(s.0, 3 | 4) && payload_shader(s.1).is_some()) { + note_translation_error("graphics stream with HS/DS – not supported yet".into()); + return Some(E_INVALIDARG); + } + if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { return None; } + let split = graphics_wave32(this); + let vs_c = match console_to_dxil_for(vs, Stage::Vertex, 0, split) { Ok(b) => b, Err(e) => { note_translation_error(format!("VS: {e}")); return Some(E_INVALIDARG); } }; + let mut samplers = vs_c.samplers; + let console_ps = subs.iter().find(|s| s.0 == 2).and_then(|s| payload_shader(s.1)); + let ps_dxil = match console_ps { + Some(p) if is_console(p) => match console_to_dxil_for(p, Stage::Pixel, samplers.len() as u32, split) { + Ok(b) => { samplers.extend(b.samplers); Some(b.dxil) } + Err(e) => { note_translation_error(format!("PS: {e}")); return Some(E_INVALIDARG); } + }, + Some(p) => Some(p.to_vec()), + None => None, + }; + let is_rect = subs.iter().find(|s| s.0 == 14 && s.1.len() >= 4).is_some_and(|s| i32::from_le_bytes(s.1[0..4].try_into().unwrap()) == RECT_LIST_TYPE); + let rect_gs = if is_rect && !subs.iter().any(|s| s.0 == 5 && payload_shader(s.1).is_some()) { rect_list_gs(vs, console_ps).map_err(|e| note_translation_error(format!("rect list drawn as triangles: {e}"))).ok() } else { None }; + let Some(rs) = abi_rs_for(this, &samplers) else { return Some(E_INVALIDARG) }; + let ps_hash = console_ps.map_or(0, crate::gpu::shader::fnv64); + let (no_stencil, no_cull) = (debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash), debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash)); + let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); + let submit = |out: &StreamOut| { + let d = [out.0.len(), out.0.as_ptr() as usize]; + driver_compile("graphics stream", out.shader_bytes(), true, || finish_pso(this, fs, d.as_ptr() as *const c_void, riid, ppv)) + }; + let mut hr = submit(&rewrite_graphics_stream(&subs, rs, &vs_c.dxil, ps_dxil.as_deref(), rect_gs.as_deref(), no_stencil, no_cull)); + let mut used_rect_gs = rect_gs.is_some(); + if rejected_rect_list_gs(hr, used_rect_gs) { + note_translation_error(format!("the driver rejected the graphics stream with the rect list GS ({hr:#x}): rect list drawn as triangles")); + hr = submit(&rewrite_graphics_stream(&subs, rs, &vs_c.dxil, ps_dxil.as_deref(), None, no_stencil, no_cull)); + used_rect_gs = false; + } + if hr < 0 { + note_translation_error(format!("the driver rejected the graphics stream with the translated shaders ({hr:#x})")); + return Some(hr); + } + let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + if !ppv.is_null() && !(*ppv).is_null() { + note_pso_rs(*ppv, rs); + super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", console_ps)]); + TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + if used_rect_gs { RECT_LIST_GS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); } + } + if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: graphics stream PSO from translated console shaders (#{})", n + 1); } + Some(hr) +} + /// The bytes of a stream payload as a desc field (no references counted: the desc only borrows). unsafe fn put(to: &mut T, from: &[u8]) { let n = std::mem::size_of::().min(from.len()); std::ptr::copy_nonoverlapping(from.as_ptr(), to as *mut T as *mut u8, n); } -/// True when a pipeline stream carries a shader subobject whose non-null, non-empty bytecode -/// pointer is not readable (handing it to D3D12Core would access-violate instead of failing). +/// True when a pipeline stream carries a shader subobject whose non-empty bytecode has a null or +/// unreadable pointer (handing it to D3D12Core would access-violate instead of failing). unsafe fn stream_has_unreadable_shader(desc: *const c_void) -> bool { if !crate::gpu::shader::readable(desc as usize, 16) { return false; @@ -7265,11 +7425,15 @@ unsafe fn stream_has_unreadable_shader(desc: *const c_void) -> bool { return false; } let buf = std::slice::from_raw_parts(base as *const u8, size); - known_subobjects(buf).into_iter().any(|(ty, p)| { + subobjects_have_unreadable_shader(&known_subobjects(buf)) +} + +fn subobjects_have_unreadable_shader(subs: &[(u32, &[u8])]) -> bool { + subs.iter().any(|(ty, p)| { matches!(ty, 1..=6 | 24 | 25) && p.len() >= 16 && { let ptr = u64::from_le_bytes(p[0..8].try_into().unwrap()) as usize; let len = u64::from_le_bytes(p[8..16].try_into().unwrap()) as usize; - ptr != 0 && len != 0 && !crate::gpu::shader::readable(ptr, len) + (ptr == 0 && len != 0) || (ptr != 0 && len != 0 && !crate::gpu::shader::readable(ptr, len)) } }) } @@ -7290,6 +7454,16 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void } match stream_pipeline(desc) { StreamPipeline::Graphics(d, cacheable) => return graphics_pso(this, &*d as *const _ as *const c_void, riid, ppv, true, cacheable), + StreamPipeline::GraphicsStream => { + let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_stream(this, desc, riid, ppv)) } else { (translated_graphics_stream(this, desc, riid, ppv), false) }; + if missed { + if let Some(hr) = own_stream(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_stream, stream_key, build_stream)) { + return hr; + } + return translated_graphics_stream(this, desc, riid, ppv).unwrap_or(E_INVALIDARG); + } + return translated.unwrap_or(E_INVALIDARG); + } StreamPipeline::Compute(d) => return dev_create_compute_pso(this, &*d as *const _ as *const c_void, riid, ppv), StreamPipeline::Unknown => {} } @@ -8030,6 +8204,17 @@ mod rect_list_pso_tests { REFUSED ); assert!(n == 1 && !copy.GS.pShaderBytecode.is_null()); + + for rejected in [E_OUTOFMEMORY, 0x887A_0005u32 as i32, 0x8000_4005u32 as i32] { + let mut copy = with_gs(&gs); + let mut n = 0; + assert_eq!(retry_without_rect_gs(&mut copy, true, |_| { n += 1; rejected }), rejected); + assert_eq!(n, 1, "{rejected:#x} must not be treated as a rect-GS rejection"); + } + let mut copy = with_gs(&gs); + let mut n = 0; + assert_eq!(retry_without_rect_gs(&mut copy, true, |_| { n += 1; if n == 1 { E_INVALIDARG } else { E_OUTOFMEMORY } }), E_OUTOFMEMORY); + assert_eq!(n, 2, "the retry's HRESULT is returned unchanged"); } /// `has_rect_list_gs`: a pipeline made with the rect list GS, not one made again without it @@ -8819,7 +9004,7 @@ mod map_tests { FillMode: D3D12_FILL_MODE_WIREFRAME, CullMode: D3D12_CULL_MODE_FRONT, FrontCounterClockwise: true.into(), - DepthBias: 7.75, + DepthBias: 7.0, DepthBiasClamp: 2.5, SlopeScaledDepthBias: 1.5, DepthClipEnable: false.into(), @@ -8838,11 +9023,11 @@ mod map_tests { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, FrontCounterClockwise: false.into(), - DepthBias: -3.25, + DepthBias: -3.0, DepthBiasClamp: 3.5, SlopeScaledDepthBias: -0.5, DepthClipEnable: true.into(), - LineRasterizationMode: D3D12_LINE_RASTERIZATION_MODE_QUADRILATERAL_WIDE, + LineRasterizationMode: D3D12_LINE_RASTERIZATION_MODE_ALIASED, ForcedSampleCount: 8, ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON, }; @@ -8853,6 +9038,90 @@ mod map_tests { assert_eq!((got.ForcedSampleCount, got.ConservativeRaster), (8, r2.ConservativeRaster)); } + #[test] + fn extended_rasterizer_state_stays_in_native_stream() { + let vs = crate::gpu::xbox::tests::sample( + 1, + &[crate::gpu::xbox::tests::fssm(&crate::gpu::xbox::tests::CODE, &[])], + ); + let parse = |stream: &StreamOut| unsafe { + stream_pipeline([stream.0.len(), stream.0.as_ptr() as usize].as_ptr() as *const c_void) + }; + let make = |ty, payload: &[u8]| { + let mut stream = StreamOut::default(); + stream.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs); + stream.raw(ty, payload, false); + stream + }; + let bytes = |p: *const u8, n| unsafe { std::slice::from_raw_parts(p, n) }; + + let r1 = D3D12_RASTERIZER_DESC1 { DepthBias: 1.5, FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_BACK, ..Default::default() }; + let s1 = make(27, bytes(&r1 as *const _ as *const u8, std::mem::size_of_val(&r1))); + assert!(matches!(parse(&s1), StreamPipeline::GraphicsStream)); + + let r2_fractional = D3D12_RASTERIZER_DESC2 { DepthBias: -2.25, LineRasterizationMode: D3D12_LINE_RASTERIZATION_MODE_ALIASED, ..Default::default() }; + let s2_fractional = make(28, bytes(&r2_fractional as *const _ as *const u8, std::mem::size_of_val(&r2_fractional))); + assert!(matches!(parse(&s2_fractional), StreamPipeline::GraphicsStream)); + + let r2 = D3D12_RASTERIZER_DESC2 { + DepthBias: -2.0, + FillMode: D3D12_FILL_MODE_WIREFRAME, + CullMode: D3D12_CULL_MODE_FRONT, + LineRasterizationMode: D3D12_LINE_RASTERIZATION_MODE_QUADRILATERAL_NARROW, + ForcedSampleCount: 4, + ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON, + ..Default::default() + }; + let mut s2 = make(28, bytes(&r2 as *const _ as *const u8, std::mem::size_of_val(&r2))); + s2.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, &D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: vs.as_ptr() as *const c_void, CachedBlobSizeInBytes: vs.len(), + }); + assert!(matches!(parse(&s2), StreamPipeline::GraphicsStream)); + + let (subs, cacheable) = known_subobjects_checked(&s2.0); + assert!(cacheable); + let rewritten = unsafe { rewrite_graphics_stream(&subs, 0x1234usize as *mut c_void, b"PC VS", None, None, false, false) }; + let rewritten = stream_subobjects(&rewritten.0).expect("valid rewritten stream"); + assert!(rewritten.iter().all(|(ty, _)| *ty != 19), "cached PSO is never copied"); + assert_eq!(u64::from_le_bytes(rewritten.iter().find(|(ty, _)| *ty == 0).unwrap().1[..8].try_into().unwrap()), 0x1234); + assert_eq!(unsafe { payload_shader(rewritten.iter().find(|(ty, _)| *ty == 1).unwrap().1) }, Some(&b"PC VS"[..])); + let got: D3D12_RASTERIZER_DESC2 = unsafe { read_sub(rewritten.iter().find(|(ty, _)| *ty == 28).unwrap().1) }; + assert_eq!(got.DepthBias, -2.0); + assert_eq!(got.LineRasterizationMode, D3D12_LINE_RASTERIZATION_MODE_QUADRILATERAL_NARROW); + assert_eq!((got.ForcedSampleCount, got.ConservativeRaster), (4, D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON)); + + let vi = D3D12_VIEW_INSTANCING_DESC { ViewInstanceCount: 1, ..Default::default() }; + let vi_only = make(22, bytes(&vi as *const _ as *const u8, std::mem::size_of_val(&vi))); + assert!(matches!(parse(&vi_only), StreamPipeline::Graphics(_, true)), "VIEW_INSTANCING remains Stage 3"); + + let mut unknown = s1.0.clone(); + unknown.extend_from_slice(&999u32.to_le_bytes()); + unknown.extend_from_slice(&0u32.to_le_bytes()); + let desc = [unknown.len(), unknown.as_ptr() as usize]; + assert!(matches!(unsafe { stream_pipeline(desc.as_ptr() as *const c_void) }, StreamPipeline::Graphics(_, false)), + "an unknown suffix retains Stage 1's uncacheable projected path"); + + for ty in [2, 5] { + let mut unreadable = StreamOut::default(); + unreadable.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs); + unreadable.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(ty), &D3D12_SHADER_BYTECODE { + pShaderBytecode: 0x1000usize as *const c_void, BytecodeLength: 64, + }); + unreadable.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1, &r1); + let desc = [unreadable.0.len(), unreadable.0.as_ptr() as usize]; + assert!(unsafe { stream_has_unreadable_shader(desc.as_ptr() as *const c_void) }); + assert!(matches!(parse(&unreadable), StreamPipeline::Unknown), "unreadable shader type {ty} must fail closed"); + } + let mut null_ps = StreamOut::default(); + null_ps.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs); + null_ps.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, &D3D12_SHADER_BYTECODE { + pShaderBytecode: std::ptr::null(), BytecodeLength: 64, + }); + let desc = [null_ps.0.len(), null_ps.0.as_ptr() as usize]; + assert!(unsafe { stream_has_unreadable_shader(desc.as_ptr() as *const c_void) }); + assert!(matches!(parse(&null_ps), StreamPipeline::Unknown)); + } + #[test] fn stream_pipeline_defaults_depth_enable_from_dsv_format() { let console_vs = crate::gpu::xbox::tests::sample( From 5dd2ef789b63d4d90bbdc6203e09bfd5c653ae3a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:08:15 -0800 Subject: [PATCH 101/265] D3D12.X: report memory by tracked owner Adapt PR #2697 so sparse CPU commit is counted from committed 4 KiB pages and every owner is scoped to the current device. Committed texture attribution is deliberately named as the tracked sampled subset because fallback resources and late-release physical lifetime are outside this diagnostic. Totals saturate, local and non-local query failures remain independent, and the existing activity memory line stays stable. Assisted-by: Claude Code (Claude Opus 5.5) Assisted-by: Codex (GPT-5.6-sol) --- README.md | 6 +- crates/xcl/src/hle/d3d12x/memory_report.rs | 197 ++++++++++++++++++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/sparse.rs | 48 +++++ crates/xcl/src/hle/d3d12x/title_textures.rs | 69 ++++++- crates/xcl/src/hle/d3d12x/vram.rs | 12 +- crates/xcl/src/host.rs | 17 +- 7 files changed, 333 insertions(+), 17 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/memory_report.rs diff --git a/README.md b/README.md index 4bee9d209f..e28d3ea86c 100644 --- a/README.md +++ b/README.md @@ -313,8 +313,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder is not a whole number is ignored. - `XCL_ACTIVITY=1` (any value turns it on): every 2 seconds `xcl.log` gets an `activity (2 s)` line with what the title did in that time (presents, submits, draws, dispatches, frame-event - waits, DirectStorage requests), and a `memory:` line with the process's commit and the video - memory in use. Where the lines stop changing is where the title stopped. + waits, DirectStorage requests), a `memory:` line with the process's commit and video memory in + use, and a `memory by owner` line splitting the known XCL allocations from `other`. A negative + `other` exposes an overlapping or stale sample; unavailable adapter segments say `unknown`. + Where the lines stop changing is where the title stopped. - `XCL_THREAD_DUMP_AT=s1,s2,…`: at each of those seconds after the start, the state of every thread of the title goes into `xcl.log`, for a title that stalls. - `XCL_TRACE_FAULTS=1` (any value): the first 32 access violations are logged as they are raised diff --git a/crates/xcl/src/hle/d3d12x/memory_report.rs b/crates/xcl/src/hle/d3d12x/memory_report.rs new file mode 100644 index 0000000000..c80f950b41 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -0,0 +1,197 @@ +//! Process and adapter memory against their budgets, split into XCL-owned parts (#2697). + +pub fn enabled() -> bool { + static ENABLED: std::sync::OnceLock = std::sync::OnceLock::new(); + *ENABLED.get_or_init(|| std::env::var_os("XCL_ACTIVITY").is_some()) +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Kind { + Video, + NonLocal, + Commit, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Part { + pub owner: &'static str, + pub kind: Kind, + pub bytes: u64, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Segment { + pub usage: u64, + pub budget: u64, +} + +#[derive(Clone, Debug, Default)] +pub struct Snapshot { + pub commit: Option, + pub local: Option, + pub non_local: Option, + pub parts: Vec, +} + +impl Snapshot { + pub fn counted(&self, kind: Kind) -> u64 { + self.parts.iter().filter(|p| p.kind == kind).fold(0, |bytes, p| bytes.saturating_add(p.bytes)) + } + + /// A negative remainder exposes aliasing, a stale sample, or a part charged to the wrong side. + pub fn other(&self, kind: Kind) -> Option { + let total = match kind { + Kind::Video => self.local?.usage, + Kind::NonLocal => self.non_local?.usage, + Kind::Commit => self.commit?, + }; + let difference = i128::from(total) - i128::from(self.counted(kind)); + Some(difference.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64) + } + + pub fn line(&self) -> String { + let mb = |b: u64| b >> 20; + let smb = |b: i64| b / (1 << 20); + let parts = |kind: Kind| { + let mut out: Vec = self.parts.iter().filter(|p| p.kind == kind) + .map(|p| format!("{} {}", p.owner, mb(p.bytes))).collect(); + if let Some(other) = self.other(kind) { + out.push(format!("other {}", smb(other))); + } + out.join(", ") + }; + let segment = |name: &str, value: Option, kind: Kind| match value { + Some(s) => format!("{name} {} of a {} budget ({})", mb(s.usage), mb(s.budget), parts(kind)), + None => format!("{name} unknown ({})", parts(kind)), + }; + let commit = match self.commit { + Some(bytes) => format!("commit {} ({})", mb(bytes), parts(Kind::Commit)), + None => format!("commit unknown ({})", parts(Kind::Commit)), + }; + format!("memory by owner (MB): {commit}; {}; {}", + segment("video memory", self.local, Kind::Video), + segment("non-local", self.non_local, Kind::NonLocal)) + } +} + +fn process_commit() -> Option { + unsafe { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; + let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); + c.cb = std::mem::size_of_val(&c) as u32; + (K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb) != 0) + .then(|| u64::try_from(c.PrivateUsage).unwrap_or(u64::MAX)) + } +} + +fn video_memory(raw: *mut std::ffi::c_void) -> (Option, Option) { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D12::ID3D12Device; + use windows::Win32::Graphics::Dxgi::*; + let Some(dev) = (unsafe { ID3D12Device::from_raw_borrowed(&raw) }) else { return (None, None) }; + unsafe { + let Ok(factory) = CreateDXGIFactory1::() else { return (None, None) }; + let Ok(adapter) = factory.EnumAdapterByLuid::(dev.GetAdapterLuid()) else { return (None, None) }; + let query = |group| { + let mut i = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + adapter.QueryVideoMemoryInfo(0, group, &mut i).ok() + .map(|_| Segment { usage: i.CurrentUsage, budget: i.Budget }) + }; + (query(DXGI_MEMORY_SEGMENT_GROUP_LOCAL), query(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)) + } +} + +pub fn snapshot() -> Snapshot { + let raw = super::real::device_raw(); + let device = raw as usize; + let (pages, page_pools) = super::vram::page_bytes_for(device); + let arenas = super::vram::arena_bytes_for(device); + let (pools, mapped, retired, sparse_commit) = super::sparse::memory_bytes_for(device); + let (_, committed_textures) = super::title_textures::committed_bytes_for(device); + let (local, non_local) = video_memory(raw); + let uma = crate::gpu::uma::get().map_or(0, |u| u64::try_from(u.size()).unwrap_or(u64::MAX)); + let b = |n: usize| u64::try_from(n).unwrap_or(u64::MAX); + let parts = vec![ + Part { owner: "UMA window", kind: Kind::Commit, bytes: uma }, + Part { owner: "sparse CPU copy", kind: Kind::Commit, bytes: b(sparse_commit) }, + Part { owner: "target pages", kind: Kind::Video, bytes: b(pages) }, + Part { owner: "target pools free", kind: Kind::Video, bytes: b(page_pools.saturating_sub(pages)) }, + Part { owner: "arenas", kind: Kind::Video, bytes: b(arenas) }, + Part { owner: "sparse tiles", kind: Kind::Video, bytes: b(mapped) }, + Part { owner: "sparse pools free", kind: Kind::Video, bytes: b(pools.saturating_sub(mapped)) }, + Part { owner: "sparse pools retired", kind: Kind::Video, bytes: b(retired) }, + Part { owner: "tracked committed sampled textures", kind: Kind::Video, bytes: committed_textures }, + ]; + Snapshot { commit: process_commit(), local, non_local, parts } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn remainder_and_partial_query_failure_are_explicit() { + const M: u64 = 1 << 20; + let s = Snapshot { + commit: Some(10_000 * M), + local: Some(Segment { usage: 9_000 * M, budget: 11_000 * M }), + non_local: None, + parts: vec![ + Part { owner: "UMA window", kind: Kind::Commit, bytes: 4_096 * M }, + Part { owner: "target pages", kind: Kind::Video, bytes: 5_000 * M }, + Part { owner: "upload staging", kind: Kind::NonLocal, bytes: 400 * M }, + ], + }; + assert_eq!(s.other(Kind::Video), Some(4_000 * M as i64)); + assert_eq!(s.other(Kind::NonLocal), None); + assert_eq!(s.line(), "memory by owner (MB): commit 10000 (UMA window 4096, other 5904); video memory 9000 of a 11000 budget (target pages 5000, other 4000); non-local unknown (upload staging 400)"); + let over = Snapshot { non_local: Some(Segment { usage: 300 * M, budget: 16_000 * M }), ..s }; + assert_eq!(over.other(Kind::NonLocal), Some(-(100 * M as i64))); + let unknown = Snapshot { commit: None, ..over }; + assert!(unknown.line().contains("commit unknown (UMA window 4096)")); + + let reverse = Snapshot { + local: None, + non_local: Some(Segment { usage: 700 * M, budget: 2_000 * M }), + ..unknown + }; + let line = reverse.line(); + assert!(line.contains("video memory unknown (target pages 5000)"), "{line}"); + assert!(line.contains("non-local 700 of a 2000 budget (upload staging 400, other 300)"), "{line}"); + } + + #[test] + fn signed_remainders_truncate_and_saturate() { + let tiny = Snapshot { + local: Some(Segment { usage: (1 << 20) - 1, budget: 1 << 20 }), + parts: vec![Part { owner: "one MiB", kind: Kind::Video, bytes: 1 << 20 }], + ..Default::default() + }; + assert_eq!(tiny.other(Kind::Video), Some(-1)); + assert!(tiny.line().contains("other 0"), "{}", tiny.line()); + + let large = Snapshot { + commit: Some(0), + parts: vec![ + Part { owner: "large", kind: Kind::Commit, bytes: u64::MAX }, + Part { owner: "saturated", kind: Kind::Commit, bytes: 1 }, + ], + ..Default::default() + }; + assert_eq!(large.counted(Kind::Commit), u64::MAX); + assert_eq!(large.other(Kind::Commit), Some(i64::MIN)); + } + + #[test] + fn device_snapshot_has_budget_and_all_owners() { + if super::super::backend() != super::super::Backend::Real { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let s = snapshot(); + assert!(s.local.expect("local video memory").budget > 0, "{}", s.line()); + assert!(s.commit.is_some()); + for owner in ["UMA window", "sparse CPU copy", "target pages", "target pools free", "arenas", "sparse tiles", "sparse pools free", "sparse pools retired", "tracked committed sampled textures"] { + assert!(s.parts.iter().any(|p| p.owner == owner), "{owner} missing: {}", s.line()); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index c221345c66..b536b2eb67 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -25,6 +25,7 @@ pub mod guard; mod late_release; pub mod layout; pub mod list_x; +pub mod memory_report; pub mod null; pub mod present; pub mod pso_async; diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index bec8a1bcf3..25925c1262 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -447,6 +447,43 @@ pub fn pool_bytes() -> (usize, usize) { let pools = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize * TILE; (pools, pools.saturating_sub(s.free.len() * TILE)) } + +/// Active pool bytes, occupied tile bytes, retired pool bytes, and committed CPU page bytes for +/// `device`, from one state lock so a pool moving to the retired list cannot be counted twice. +pub(super) fn memory_bytes_for(device: usize) -> (usize, usize, usize, usize) { + let g = lock_state(); + let Some(s) = g.as_ref() else { return (0, 0, 0, 0) }; + memory_byte_counts( + device, + s.dev.as_raw() as usize, + s.pools.iter().filter(|p| p.is_some()).count(), + s.free.len(), + s.retired.len(), + s.mapped.values().map(|e| e.holes), + ) +} + +fn memory_byte_counts( + device: usize, + owner: usize, + active_pools: usize, + free_tiles: usize, + retired_pools: usize, + mapped_holes: impl Iterator, +) -> (usize, usize, usize, usize) { + if device != owner { + return (0, 0, 0, 0); + } + let pool_bytes = (POOL_TILES as usize).saturating_mul(TILE); + let pools = active_pools.saturating_mul(pool_bytes); + let occupied = pools.saturating_sub(free_tiles.saturating_mul(TILE)); + let retired = retired_pools.saturating_mul(pool_bytes); + let committed = mapped_holes.fold(0usize, |bytes, holes| { + let pages = PAGES_PER_TILE.saturating_sub(holes.count_ones() as usize); + bytes.saturating_add(pages.saturating_mul(PAGE)) + }); + (pools, occupied, retired, committed) +} /// commits before the device existed: the pages committed, as disjoint page ranges (start → /// end) merged with their neighbours, so a commit or decommit costs O(log n) and not a scan of /// every page committed so far. Like `committed` / `decommitted` with a state, a range counts @@ -1774,6 +1811,17 @@ fn forget_in(s: &mut State, res: usize) { mod tests { use super::*; + #[test] + fn memory_counts_committed_pages_and_separates_devices_and_retired_pools() { + let holes = [0xFFFE, 0xFFF0].into_iter(); // one committed page, then four + let (pools, occupied, retired, committed) = memory_byte_counts(7, 7, 1, 60, 1, holes); + assert_eq!(pools, POOL_TILES as usize * TILE); + assert_eq!(occupied, 4 * TILE, "occupied video tiles are independent of CPU page commitment"); + assert_eq!(retired, POOL_TILES as usize * TILE, "the retired pool is not also active"); + assert_eq!(committed, 5 * PAGE, "holes in a 64 KiB tile do not consume CPU commit"); + assert_eq!(memory_byte_counts(8, 7, 1, 60, 1, [0].into_iter()), (0, 0, 0, 0)); + } + /// `queue()` answers while the state's lock is held: a resource's last `Release` asks for /// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be /// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`). diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 67c97e8eca..82bb05fce4 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -65,6 +65,8 @@ struct GpuWriter { struct Entry { device: usize, + /// PC allocation size of a committed resource (zero for placed resources and test entries) + committed_bytes: u64, /// the title's address of the texture va: usize, /// where its bytes are read and its CPU writes watched: `va`, or – for a texture in a GPU @@ -310,6 +312,11 @@ impl Table { by_res.get_mut(&res).or_else(|| shadowed.get_mut(&res)) } + fn committed_bytes_for(&self, device: usize) -> (usize, u64) { + self.by_res.values().chain(self.shadowed.values()).filter(|e| e.device == device && !e.placed) + .fold((0usize, 0u64), |(n, bytes), e| (n.saturating_add(1), bytes.saturating_add(e.committed_bytes))) + } + fn overlapping(&self, va: usize, len: usize) -> Vec<(usize, usize)> { self.active_overlaps(va, va.saturating_add(len)).into_iter().take(4).map(|(ova, ores, _)| (ores, ova)).collect() } @@ -351,6 +358,21 @@ pub fn counts() -> (usize, u64) { (TEXTURES_LEN.load(Ordering::Relaxed), UPLOADS.load(Ordering::Relaxed)) } +/// Sampled textures tracked for CPU coherency on `device` that use committed resources: count and +/// their PC allocation bytes. This deliberately excludes untracked render/depth/UAV fallbacks. +/// Shadowed resources remain live and are included once until the title releases them. +pub(super) fn committed_bytes_for(device: usize) -> (usize, u64) { + TEXTURES.lock().unwrap().committed_bytes_for(device) +} + +unsafe fn committed_allocation_bytes(device: *mut c_void, resource: *mut c_void, placed: bool) -> u64 { + if placed || !super::memory_report::enabled() { return 0 } + let Some(dev) = ID3D12Device::from_raw_borrowed(&device) else { return 0 }; + let Some(res) = ID3D12Resource::from_raw_borrowed(&resource) else { return 0 }; + let bytes = dev.GetResourceAllocationInfo(0, &[res.GetDesc()]).SizeInBytes; + if bytes == u64::MAX { 0 } else { bytes } +} + fn update_lengths(t: &Table) { TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); CPU_TEXTURES_LEN.store(t.by_res.values().filter(|e| e.cpu_backed).count(), Ordering::Relaxed); @@ -410,8 +432,10 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, } } let in_gpu_view = crate::hle::kernelx::mirrors::source(va).is_some(); + let placed = super::vram::is_placed_texture(res as usize); let e = Entry { device: device as usize, + committed_bytes: committed_allocation_bytes(device, res, placed), va, src, in_gpu_view, @@ -421,7 +445,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, gpu_written: false, gpu_writers: Vec::new(), cpu_backed: true, - placed: super::vram::is_placed_texture(res as usize), + placed, unmapped: false, generation: 0, }; @@ -491,6 +515,7 @@ pub(super) unsafe fn register_gpu_owned( let src = mirror_source(va); let e = Entry { device: device as usize, + committed_bytes: 0, va, src, in_gpu_view: crate::hle::kernelx::mirrors::source(va).is_some(), @@ -2513,7 +2538,7 @@ mod tests { d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); d[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); let tex = Arc::new(xg::Texture::new(&d).unwrap()); - let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }; + let mut e = Entry { device: 0, committed_bytes: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }; assert_eq!(e.src, cpu + 0x2_0000); assert!(!recheck_source(&mut e), "nothing changed yet"); assert_eq!(kernelx::MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, at); @@ -2637,6 +2662,7 @@ mod tests { let res = 0x7E57_1000_1000usize; let entry = |tex: &Arc| Entry { device: 0, + committed_bytes: 0, va: 0x7E57_1000_0000, src: 0x7E57_1000_0000, in_gpu_view: false, @@ -2712,7 +2738,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, committed_bytes: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().by_res.get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); @@ -2877,6 +2903,39 @@ mod tests { d } + #[test] + fn committed_sampled_bytes_follow_device_shadowing_and_release() { + const M: u64 = 1 << 20; + let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); + let entry = |device, va, committed_bytes, placed| Entry { + device, + committed_bytes, + va, + src: va, + in_gpu_view: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written: false, + gpu_writers: Vec::new(), + cpu_backed: true, + placed, + unmapped: false, + generation: 0, + }; + let mut table = Table::new(); + table.insert(1, entry(7, 0x10_0000, 3 * M, false)); + table.insert(2, entry(7, 0x10_2000, 2 * M, false)); // shadows 1, which remains live + table.insert(3, entry(7, 0x20_0000, 8 * M, true)); // shared pages, not committed + table.insert(4, entry(8, 0x30_0000, 11 * M, false)); + assert_eq!(table.committed_bytes_for(7), (2, 5 * M)); + assert_eq!(table.committed_bytes_for(8), (1, 11 * M)); + assert!(table.remove(2).0); + assert_eq!(table.committed_bytes_for(7), (1, 3 * M), "the uncovered sampled texture is counted once"); + assert!(table.remove(1).0); + assert_eq!(table.committed_bytes_for(7), (0, 0), "logical release removes the partial diagnostic owner"); + } + fn readback_for(tex: &xg::Texture, format: u32, subresource: u32) -> (ReadbackFootprint, Vec, Vec) { let s = tex.texels().unwrap(); let mips = s.chain.levels.len(); @@ -3060,6 +3119,7 @@ mod tests { assert_eq!((tex_16k.size(), tex_64k.size()), (0x4000, 0x1_0000)); let entry = |va: usize, tex: &Arc, pending: bool, placed: bool| Entry { device: 0, + committed_bytes: 0, va, src: va, in_gpu_view: false, @@ -3465,6 +3525,7 @@ mod tests { let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); let entry = |cpu_backed: bool| Entry { device: 0, + committed_bytes: 0, va: 0x20_0000, src: 0x20_0000, in_gpu_view: false, @@ -3506,6 +3567,7 @@ mod tests { let e_stream = Entry { device: 0, + committed_bytes: 0, va, src: va, in_gpu_view: false, @@ -3521,6 +3583,7 @@ mod tests { }; let e_gpu = Entry { device: 0, + committed_bytes: 0, va: va + size, src: va, in_gpu_view: false, diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 8d39240c49..312262e4eb 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -108,6 +108,9 @@ impl Arenas { } fn bytes(&self) -> usize { self.list.iter().map(|a| a.size).sum() } + fn bytes_for(&self, dev: usize) -> usize { + self.list.iter().filter(|a| a.dev == dev).fold(0, |bytes, a| bytes.saturating_add(a.size)) + } } // D3D12 heaps are free-threaded @@ -123,6 +126,10 @@ static MADE_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsi pub fn arena_bytes() -> (usize, usize) { (ARENAS.lock().unwrap().bytes(), MADE_BYTES.load(std::sync::atomic::Ordering::Relaxed)) } + +pub(super) fn arena_bytes_for(device: usize) -> usize { + ARENAS.lock().unwrap().bytes_for(device) +} static PLACED_TEXTURES: Mutex>> = Mutex::new(None); /// A texture backed by one of the aliasable D3D12 heaps. @@ -1293,11 +1300,12 @@ pub(super) fn mapped_tiles_for(device: usize, resource: usize) -> Option<(Vec<(u (used.len() + extra.len() == target.total as usize).then_some((used, extra)) } -#[cfg(test)] pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { let g = PAGES.lock().unwrap(); let Some(Some(p)) = g.get(&device) else { return (0, 0) }; - ((p.pages.len() + p.extra_pages.len()) * PAGE, p.pools.len() * POOL_PAGES as usize * PAGE) + let pages = p.pages.len().saturating_add(p.extra_pages.len()).saturating_mul(PAGE); + let pools = p.pools.len().saturating_mul(POOL_PAGES as usize).saturating_mul(PAGE); + (pages, pools) } /// Pool/tile identities used by one mapped resource: title pages, then extra pages. diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 84a7fce1d0..31b2de8894 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -45,7 +45,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::hle::d3d12x::real::log_dispatch_chain_counts(); }); // `XCL_ACTIVITY=1`: every 2 s what the title did since (a timeline of where it stops) - if std::env::var_os("XCL_ACTIVITY").is_some() { + if crate::hle::d3d12x::memory_report::enabled() { let _ = std::thread::Builder::new().name("xcl-activity".into()).spawn(|| { let snap = || { let (p, e) = crate::hle::d3d12x::present::activity(); @@ -64,21 +64,17 @@ pub fn host_main(boot_path: &Path) -> i32 { d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8], d[9], d[10] ); // where the memory is: the process's commit, video memory, and XCL's parts of it - let private = unsafe { - use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; - let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); - c.cb = std::mem::size_of_val(&c) as u32; - K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb); - c.PrivateUsage - }; - let (local, non_local) = crate::hle::d3d12x::real::video_memory().unwrap_or((0, 0)); + let owner = crate::hle::d3d12x::memory_report::snapshot(); + let private = owner.commit.unwrap_or(0); + let local = owner.local.map_or(0, |s| s.usage); + let non_local = owner.non_local.map_or(0, |s| s.usage); let (arenas, arenas_made) = crate::hle::d3d12x::vram::arena_bytes(); let (pools, pools_mapped) = crate::hle::d3d12x::sparse::pool_bytes(); let (pages, page_pools) = crate::hle::d3d12x::vram::page_bytes(); let mb = |b: u64| b >> 20; crate::xlog_info!( "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped)", - mb(private as u64), + mb(private), mb(local), mb(non_local), mb(pages as u64), @@ -88,6 +84,7 @@ pub fn host_main(boot_path: &Path) -> i32 { mb(pools as u64), mb(pools_mapped as u64) ); + crate::xlog_info!("{}", owner.line()); last = now; } }); From ba65996331cc68cefa887721972d51d74e03131c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 18:15:05 -0700 Subject: [PATCH 102/265] D3D12.X: launch DispatchX thread dimensions safely DispatchX USE_THREAD_DIMENSIONS now reaches deferred replay, converts thread counts to whole group counts, and masks the partial last groups in both compute emitters. Oversized D3D grids and unknown group shapes are skipped before binding or recording. Multidimensional kernels use HLSL for console-linear wave ordering; ordinary direct-DXIL dispatches avoid the partial-group ballot. Transient limits are consumed once and cleared on Reset. Co-Authored-By: Claude Opus 5.5 Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/build.rs | 2 +- crates/xcl/src/gpu/dxil/kernel.rs | 37 ++++++ crates/xcl/src/gpu/recomp/emit.rs | 18 ++- crates/xcl/src/gpu/recomp/mod.rs | 5 + crates/xcl/src/gpu/recomp/pso.rs | 26 +++- crates/xcl/src/gpu/recomp/tests.rs | 67 +++++++++- crates/xcl/src/hle/d3d12x/bind.rs | 125 +++++++++++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 14 +- crates/xcl/src/hle/d3d12x/real.rs | 26 +++- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 10 ++ 10 files changed, 310 insertions(+), 20 deletions(-) diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 22b136da8e..65ab22ece0 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; // `pso.rs` also contains cache storage and pipeline setup. Keep it out of the source hash so // those changes do not discard translations; bump this only when its container parsing, // translation options, profiles, or post-translation HLSL changes. -const TRANSLATION_GLUE_REVISION: &str = "pso-glue-v2"; +const TRANSLATION_GLUE_REVISION: &str = "pso-glue-v3"; const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/dxbc.rs", diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..c97248189a 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -741,7 +741,44 @@ pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) } let zero = lw.c(0); sgpr.insert(VAR_SCC, zero); + let io = lw.init.io.expect("the I/O buffer"); + let mut dispatch_limited = lw.s.m.i1c(false); + let mut limits = Vec::new(); + for (k, _) in cs.threads.iter().enumerate().filter(|(_, &threads)| threads > 1) { + let off = lw.c((crate::gpu::recomp::IO_THREAD_LIMIT[k] * 4) as u32); + let limit = lw.s.raw_load(io, off, 1)[0]; + let zero = lw.c(0); + let limited = lw.cmp(Pred::Ne, limit, zero); + dispatch_limited = lw.lor(dispatch_limited, limited); + limits.push((k, limit)); + } let (lo, hi) = entry_exec(lw, total, tid); + let (exec_lo, exec_hi) = (lw.tmp_var(), lw.tmp_var()); + lw.wr(exec_lo, lo); + lw.wr(exec_hi, hi); + let _ = lw.guarded(dispatch_limited, &mut |lw| { + let mut dispatch_live = lw.s.m.i1c(true); + for &(k, limit) in &limits { + let zero = lw.c(0); + let unlimited = lw.cmp(Pred::Eq, limit, zero); + let group = lw.s.group_id(k as u32); + let width = lw.c(cs.threads[k]); + let base = lw.mul(group, width); + let id = lw.add(base, gtid[k]); + let inside = lw.cmp(Pred::ULt, id, limit); + let axis_live = lw.lor(unlimited, inside); + dispatch_live = lw.land(dispatch_live, axis_live); + } + let (dispatch_lo, dispatch_hi) = lw.ballot(dispatch_live); + let old_lo = lw.rd(exec_lo); + let old_hi = lw.rd(exec_hi); + let lo = lw.and(old_lo, dispatch_lo); + let hi = lw.and(old_hi, dispatch_hi); + lw.wr(exec_lo, lo); + lw.wr(exec_hi, hi); + Ok(()) + }); + let (lo, hi) = (lw.rd(exec_lo), lw.rd(exec_hi)); sgpr.insert(126, lo); sgpr.insert(127, hi); let mut vgpr = HashMap::new(); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 7d259d55ac..a99bb5a715 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5082,7 +5082,23 @@ impl Em { // waves in the group: a last, partial wave counts (96 threads: 2 of 64) let _ = writeln!(h, " {} = {}u | ((gi / {lanes}u) << 6);", sname(next).unwrap(), (x * y * z).div_ceil(lanes)); } - let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}(true); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn()); + h.push_str(" bool xcl_dispatch_limited = false;\n"); + for (k, c) in ["x", "y", "z"].iter().enumerate().filter(|(k, _)| cs.threads[*k] > 1) { + let slot = super::IO_THREAD_LIMIT[k] * 4; + let _ = writeln!(h, " uint xcl_limit_{c} = io.Load({slot}u);\n xcl_dispatch_limited = xcl_dispatch_limited || xcl_limit_{c} != 0u;"); + } + let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0;"); + let _ = writeln!(h, " if (xcl_dispatch_limited) {{\n bool xcl_dispatch_live = true;"); + for (k, c) in ["x", "y", "z"].iter().enumerate().filter(|(k, _)| cs.threads[*k] > 1) { + let group = match remap { + Some((ratio, dim, _)) if dim == k => format!("(gid.{c} / {ratio}u)"), + _ => format!("gid.{c}"), + }; + let threads = cs.threads[k]; + let _ = writeln!(h, " xcl_dispatch_live = xcl_dispatch_live && (xcl_limit_{c} == 0u || {group} * {threads}u + gtid.{c} < xcl_limit_{c});"); + } + let ballot = self.ballot_fn(); + let _ = writeln!(h, " e0 = {ballot}(xcl_dispatch_live);\n }} else {{\n e0 = {ballot}(true);\n }}\n exec_lo = e0.x; exec_hi = e0.y; }}"); for &v in &self.vgprs { let init = match v { 0 => "gtid.x", diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 3a7b0520fb..b888923bd0 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -209,6 +209,11 @@ pub const GS_PRIMS_PER_GROUP: u32 = 21; pub const IO_GS_PRIMS: usize = 110; pub const IO_GS_VERTICES: usize = 111; pub const IO_UMA_BASE_HI: usize = 112; +/// io slots of a `DispatchX` with thread dimensions (flag 0x20): the thread count of each axis +/// when it is not a whole number of groups (0: the last group is whole), so the program can leave +/// the lanes past it out of EXEC. Written by D3D12.X and read by both compute backends. +/// (113 is left for the group-limit slot of #1428.) +pub const IO_THREAD_LIMIT: [usize; 3] = [114, 115, 116]; impl GsInterface { /// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index ea5597d4d4..8084d5cdb4 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1012,13 +1012,19 @@ fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { /// s0…s3 are the driver's, so what is above 4 is the root arguments its compiler passed in /// registers. None: not a console compute shader. pub fn compute_user_sgprs(blob: &[u8]) -> Option { + compute_interface(blob).map(|cs| cs.user_sgprs) +} + +/// The dispatch ABI of a console compute program: its user SGPRs and the console's group shape +/// (`numthreads`). None: not a console compute program. +pub fn compute_interface(blob: &[u8]) -> Option { if let Some(f) = fspx(blob) { - return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2).user_sgprs); + return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2)); } let sh = xbox::parse(blob)?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; match interface(blob, &sh, f)? { - Mode::Compute(cs) => Some(cs.user_sgprs), + Mode::Compute(cs) => Some(cs), _ => None, } } @@ -1048,6 +1054,9 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo let sh = xbox::parse(blob).ok_or("not a console shader container")?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)).ok_or("no hardware CS variant")?; let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) }; + if direct_compute_needs_hlsl(&cs) { + return Err("multidimensional groups need the HLSL console-linear thread reorder".into()); + } let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; let wave64 = super::fssm_wave64(f, code); @@ -1071,6 +1080,19 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) } +fn direct_compute_needs_hlsl(cs: &super::CsInterface) -> bool { + cs.threads[1] > 1 || cs.threads[2] > 1 +} + +#[cfg(test)] +#[test] +fn direct_compute_routes_multidimensional_thread_groups_to_hlsl() { + let cs = |threads| super::CsInterface { threads, user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 3 }; + assert!(!direct_compute_needs_hlsl(&cs([64, 1, 1]))); + assert!(direct_compute_needs_hlsl(&cs([8, 8, 1]))); + assert!(direct_compute_needs_hlsl(&cs([4, 4, 4]))); +} + /// `XCL_DXIL_DUMP=[,…]` (`[SHADER]` hashes, or `all`): writes the direct path's /// DXIL to `%TEMP%\xcl-dxil-dump\.dxil` (with `XCL_TRANSLATED_CACHE=0`, so cached /// translations are redone). diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 37fd347cd4..8c264943f0 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5178,10 +5178,19 @@ fn gpu_compute_mode_dispatch_abi() { ("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 128)], None), ("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 9), ("DATA", 11), ("SADDR", 0x7D)], None), ]); - let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); + let opt = on_gpu(Options { mode: Mode::Compute(cs.clone()), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); - let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); + let hlsl_dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let split = opt.wave64 && (opt.split_wave64 || runner::split_wave64()); + let direct_dxil = crate::gpu::dxil::kernel::translate_compute( + &p, + crate::gpu::dxil::kernel::KernelOptions { wave64: opt.wave64, split, mem_windows: opt.mem_windows, sampler_base: opt.static_sampler_base }, + &cs, + ) + .unwrap_or_else(|e| panic!("direct DXIL: {e}")) + .dxil; + let dxil = if direct_enabled(&opt) { direct_dxil.clone() } else { hlsl_dxil.clone() }; let (w, h, base) = (32usize, 24usize, 0x100usize); let mut io = vec![0u32; 128]; io[0] = base as u32; @@ -5196,6 +5205,24 @@ fn gpu_compute_mode_dispatch_abi() { assert_eq!(out[at + 1], (px | py << 16) as u32, "({x}, {y}): value of thread {} through LDS", 127 - i); } } + + // DispatchX thread limits seed EXEC in both backends. The hardware groups still contain + // 32x24 threads, but only the 20x17 console dispatch rectangle may reach memory. + for (backend, dxil) in [("HLSL", hlsl_dxil), ("direct DXIL", direct_dxil)] { + let mut limited_io = io.clone(); + limited_io[super::IO_THREAD_LIMIT[0]] = 20; + limited_io[super::IO_THREAD_LIMIT[1]] = 17; + let sentinel = 0xA5A5_5A5Au32; + let out = runner::dispatch(&dxil, [2, 3, 1], &limited_io, &vec![sentinel; (base + w * h * 8) / 4]).unwrap(); + for y in 0..h { + for x in 0..w { + let at = (base + (y * w + x) * 8) / 4; + let written = x < 20 && y < 17; + assert_eq!(out[at] != sentinel, written, "{backend} ({x}, {y}) own write"); + assert_eq!(out[at + 1] != sentinel, written, "{backend} ({x}, {y}) partner write"); + } + } + } } /// A wave32 program in a 64-lane hardware wave (what VS / PS may get from the driver): the @@ -7439,6 +7466,42 @@ fn wave_local_remap_decision_and_console_ids() { assert!(fallback.hlsl.contains("numthreads(128, 1, 1)") && fallback.hlsl.contains("#define XCL_X_SPIN 1")); } +#[test] +fn dispatch_thread_limits_seed_compute_exec_for_native_and_remapped_groups() { + use super::{CsInterface, Mode, Options}; + let p = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 0), ("SADDR", 0x7D)], None), + ]); + let translated = |threads, split_wave64| { + translate( + &p, + &Options { + mode: Mode::Compute(CsInterface { threads, user_sgprs: 2, tgid: [true; 3], tg_size: false, tid_components: 3 }), + wave64: true, + split_wave64, + ..Default::default() + }, + ) + .unwrap() + }; + + let native = translated([8, 8, 1], false); + assert!(native.hlsl.contains("uint xcl_limit_x = io.Load(456u);")); + assert!(native.hlsl.contains("gid.x * 8u + gtid.x < xcl_limit_x")); + assert!(native.hlsl.contains("uint xcl_limit_y = io.Load(460u);")); + assert!(native.hlsl.contains("gid.y * 8u + gtid.y < xcl_limit_y")); + assert!(!native.hlsl.contains("xcl_limit_z"), "a one-thread axis is always whole"); + assert!(native.hlsl.contains("if (xcl_dispatch_limited)")); + assert!(native.hlsl.contains("ballot(xcl_dispatch_live)")); + assert!(native.hlsl.contains("ballot(true)"), "ordinary Dispatch keeps the original entry ballot"); + + let remapped = translated([128, 1, 1], true); + assert_eq!(remapped.dispatch_remap, Some((2, 0))); + assert!(remapped.hlsl.contains("(gid.x / 2u) * 128u + gtid.x < xcl_limit_x")); + assert!(remapped.hlsl.contains("xcl_x_ballot(xcl_dispatch_live)")); +} + /// What the split wave64 form costs (`cargo test --release -- --ignored bench_split_wave64 /// --nocapture`): a loop of a few VALU instructions and one mask (`v_cmp`, an exchange in the /// split form), plus a readfirstlane (another exchange) in the second variant, as a wave32 diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index cdd26ca9bf..02c43da04e 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -34,6 +34,9 @@ struct State { uma: Vec, /// where the next draw's io and argument table go (blocks in `uma`) arena: crate::gpu::uma::Arena, + /// the next dispatch's thread limits (`IO_THREAD_LIMIT`; a `DispatchX` with thread + /// dimensions), taken by its `bind_abi` + limits: [u32; 3], } static STATES: Mutex>> = Mutex::new(None); @@ -82,6 +85,7 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + s.limits = [0; 3]; (old, std::mem::take(&mut s.uma)) }); console_list::hold_until_reset(old, blocks); @@ -906,8 +910,35 @@ pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { + dispatch_flags(this, x, y, z, 0); +} + +/// `DispatchX` flag: x, y, z are thread counts, not group counts; the console launches whole +/// groups and leaves the lanes past the count out of EXEC (0x8000, wave32, needs nothing here) +const DISPATCH_THREAD_DIMENSIONS: u32 = 0x20; +const MAX_DISPATCH_GROUPS: u32 = 65_535; + +fn valid_dispatch_grid(groups: [u32; 3]) -> bool { + groups.into_iter().all(|n| n <= MAX_DISPATCH_GROUPS) +} + +/// What a dispatch of `dims` with `flags` launches on pipeline `pso`: its groups and the thread +/// limits for `IO_THREAD_LIMIT` (0: that axis ends on a whole group). None: it cannot be run +/// as the console would (thread dimensions with a group shape not known). +fn dispatch_groups(pso: usize, dims: [u32; 3], flags: u32) -> Option<([u32; 3], [u32; 3])> { + if flags & DISPATCH_THREAD_DIMENSIONS == 0 { + return Some((dims, [0; 3])); + } + let threads = super::real::pso_threads(pso)?.map(|t| t.max(1)); + let groups = std::array::from_fn(|k| dims[k].div_ceil(threads[k])); + let limits = std::array::from_fn(|k| if dims[k] % threads[k] != 0 { dims[k] } else { 0 }); + Some((groups, limits)) +} + +/// `Dispatch` / `DispatchX(x, y, z, flags)`. +pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { let pso = with(this, |s| s.pso); - if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z)) { + if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z, flags)) { return super::pso_async::need_by_submit(pso); } let pso = super::pso_async::resolve_wait(pso); @@ -922,7 +953,34 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, count(DISPATCHES_SKIPPED); return; } - match translated_dispatch(this, list, pso, x, y, z) { + let Some((groups, limits)) = dispatch_groups(pso, [x, y, z], flags) else { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: DispatchX of {x}x{y}x{z} threads (flags {flags:#x}) with a pipeline whose group shape is not known ({pso:#x}) skipped"); + } + count(DISPATCHES_SKIPPED); + return; + }; + if !valid_dispatch_grid(groups) { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: Dispatch of {}x{}x{} groups exceeds the PC limit of {MAX_DISPATCH_GROUPS} on one axis and was skipped", groups[0], groups[1], groups[2]); + } + count(DISPATCHES_SKIPPED); + return; + } + if flags != 0 { + // each kind of flags once: what titles pass, and what it launches + static SEEN: Mutex> = Mutex::new(Vec::new()); + let first = { let mut g = SEEN.lock().unwrap(); !g.contains(&flags) && { g.push(flags); true } }; + if first { + crate::xlog_info!("D3D12.X: DispatchX with flags {flags:#x}: {x}x{y}x{z} launched as {}x{}x{} groups (thread limits {limits:?})", groups[0], groups[1], groups[2]); + } + } + with(this, |s| s.limits = limits); + let done = translated_dispatch(this, list, pso, groups[0], groups[1], groups[2]); + with(this, |s| s.limits = [0; 3]); + match done { Ok(()) => count(DISPATCHES), Err(e) => { count(DISPATCHES_SKIPPED); @@ -1075,6 +1133,11 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi }; io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; + if !gfx { + for (k, l) in take_dispatch_limits(this).into_iter().enumerate() { + io[crate::gpu::recomp::IO_THREAD_LIMIT[k]] = l; + } + } let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; let res_at = copy(&[0u8; 256])?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); @@ -1099,6 +1162,10 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi Ok(()) } +fn take_dispatch_limits(list: *mut c_void) -> [u32; 3] { + with(list, |s| std::mem::take(&mut s.limits)) +} + #[cfg(test)] pub(super) fn last_draw_args() -> (bool, u32, u32, u32, i32) { DRAW_ARGS.with(|d| d.get()) @@ -1476,6 +1543,60 @@ void main(uint t : SV_GroupIndex) { (*(this as *const FakeAdoptedList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); } + /// `DispatchX` with thread dimensions (flag 0x20, as the BVH builder's rehydration passes + /// use it): the console launches whole groups of the pipeline's `numthreads` and leaves + /// the lanes past the count out; without the flag the counts are groups. With the flag + /// and a group shape not known, nothing is launched (the counts as groups was the bug). + #[test] + fn dispatch_x_with_thread_dimensions_launches_whole_groups() { + let pso = 0x7300_0001usize; + real::register_threads_for_test(pso, [64, 1, 1]); + // 640 threads in groups of 64: 10 groups, the last one whole + assert_eq!(dispatch_groups(pso, [640, 1, 1], 0x20), Some(([10, 1, 1], [0, 0, 0]))); + // 100 threads: 2 groups, and the lanes past 100 to leave out + assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x20), Some(([2, 1, 1], [100, 0, 0]))); + // the wave32 bit (0x8000) changes nothing here + assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x8020), Some(([2, 1, 1], [100, 0, 0]))); + // a 2-D group shape + let pso2 = 0x7300_0002usize; + real::register_threads_for_test(pso2, [8, 8, 1]); + assert_eq!(dispatch_groups(pso2, [20, 16, 3], 0x20), Some(([3, 2, 3], [20, 0, 0]))); + // group counts (Dispatch, DispatchX without the flag) are launched as they are + assert_eq!(dispatch_groups(pso, [7, 2, 1], 0), Some(([7, 2, 1], [0, 0, 0]))); + assert_eq!(dispatch_groups(pso, [7, 2, 1], 0x8000), Some(([7, 2, 1], [0, 0, 0]))); + // no threads: no groups + assert_eq!(dispatch_groups(pso, [0, 1, 1], 0x20), Some(([0, 1, 1], [0, 0, 0]))); + // thread dimensions on a pipeline whose group shape is not known: not launched + assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0x20), None); + assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0), Some(([100, 1, 1], [0, 0, 0]))); + + let last = MAX_DISPATCH_GROUPS * 64; + let at_limit = dispatch_groups(pso, [last, 1, 1], 0x20).unwrap().0; + let past_limit = dispatch_groups(pso, [last + 1, 1, 1], 0x20).unwrap().0; + assert!(valid_dispatch_grid(at_limit)); + assert!(!valid_dispatch_grid(past_limit)); + for k in 0..3 { + let mut grid = [1; 3]; + grid[k] = MAX_DISPATCH_GROUPS; + assert!(valid_dispatch_grid(grid), "axis {k} at the D3D12 limit"); + grid[k] += 1; + assert!(!valid_dispatch_grid(grid), "axis {k} past the D3D12 limit"); + } + } + + #[test] + fn deferred_dispatch_limits_are_consumed_once_and_reset_with_the_list() { + let list = 0x7301_0001usize as *mut c_void; + with(list, |s| s.limits = [100, 17, 0]); + assert_eq!(take_dispatch_limits(list), [100, 17, 0]); + assert_eq!(take_dispatch_limits(list), [0; 3], "a later ordinary dispatch must not inherit deferred limits"); + + with(list, |s| s.limits = [9, 8, 7]); + reset(list, 0x7301_1000, 0); + assert_eq!(take_dispatch_limits(list), [0; 3], "Reset drops an unconsumed deferred dispatch state"); + forget(list); + } + #[test] fn async_compute_pso_success_and_failure_in_dispatch_and_execute_indirect() { let mut orig_vt = [0usize; 64]; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index eaabfbc28e..d4c4c78eb2 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -774,7 +774,8 @@ struct ListState { /// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. pub(super) enum Deferred { - Dispatch(u32, u32, u32), + /// x, y, z and `DispatchX`'s flags (0 for `Dispatch`) + Dispatch(u32, u32, u32, u32), Indirect(usize, u32, usize, u64, usize, u64), } @@ -3240,7 +3241,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { real::dispatch_chain::list_follows(last as usize, seg as usize); } match what { - Deferred::Dispatch(x, y, z) => super::bind::dispatch(seg, x, y, z), + Deferred::Dispatch(x, y, z, flags) => super::bind::dispatch_flags(seg, x, y, z, flags), Deferred::Indirect(sig, max, args, args_off, count_buf, count_off) => super::bind::execute_indirect(seg, sig, max, args, args_off, count_buf, count_off), } let ext = *(seg as *const usize); @@ -3666,8 +3667,8 @@ pub(super) unsafe extern "system" fn set_depth_bounds_x(this: *mut c_void, min: } /// command list #78 DispatchX(x, y, z, flags) -pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, _flags: u32) { - super::bind::dispatch(this, x, y, z); +pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + super::bind::dispatch_flags(this, x, y, z, flags); } /// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH @@ -5982,7 +5983,10 @@ mod tests { fn segment_reasons_keep_the_existing_segment_costs() { assert_eq!(SegmentReason::WaitAfterWrite64.extra_segments(), 1); assert_eq!(SegmentReason::WaitAfterCpuWrite.extra_segments(), 1); - assert_eq!(SegmentReason::DeferredDispatch(Deferred::Dispatch(1, 2, 3)).extra_segments(), 2); + let deferred = SegmentReason::DeferredDispatch(Deferred::Dispatch(1, 2, 3, 0x8020)); + let SegmentReason::DeferredDispatch(Deferred::Dispatch(x, y, z, flags)) = &deferred else { unreachable!() }; + assert_eq!((*x, *y, *z, *flags), (1, 2, 3, 0x8020), "deferred replay retains DispatchX flags"); + assert_eq!(deferred.extra_segments(), 2); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fbfc536ca3..c51366553d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3933,15 +3933,27 @@ fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) { } } -/// user SGPRs of the console CS of a translated compute pipeline -static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); +/// user SGPRs and the console's `numthreads` of the console CS of a translated compute pipeline +static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); static PSO_DISPATCH_REMAP: Mutex>> = Mutex::new(None); /// How many user SGPRs the console compute shader of a translated pipeline has (None: not /// known). What is above the driver's four holds root arguments (`console_list::inline_for`). pub fn pso_user_sgprs(pso: usize) -> Option { let pso = super::pso_async::resolve(pso); - PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).map(|e| e.0) +} + +/// The console's group shape (`numthreads`) of a translated compute pipeline (None: not known). +pub fn pso_threads(pso: usize) -> Option<[u32; 3]> { + let pso = super::pso_async::resolve(pso); + PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).map(|e| e.1) +} + +/// (tests) A translated compute pipeline with this console group shape. +#[cfg(test)] +pub(crate) fn register_threads_for_test(pso: usize, threads: [u32; 3]) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, (0, threads)); } pub fn pso_dispatch_remap(pso: usize) -> Option<(u32, u32)> { @@ -4428,8 +4440,8 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const LAST_COMPUTE_RS.with(|c| c.set(rs)); note_pso_rs(*ppv, rs as *mut c_void); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_translated_compute(0, ppv); TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); @@ -4465,8 +4477,8 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_pso_dispatch_remap(*ppv, compiled.dispatch_remap); remap_fallback::note(*ppv as usize, this, f, rs as usize, d.Flags, d.NodeMask, record, cs, diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 8b84548a04..a7fba17f21 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -235,6 +235,9 @@ unsafe fn scratch_buffer(dev: &ID3D12Device, bytes: u64) -> Option) -> Option<[u32; 3]> { + if grid.into_iter().any(|n| n > 65_535) { + return None; + } if let Some((ratio, dim)) = remap { let count = grid.get_mut(dim as usize)?; let scaled = count.checked_mul(ratio)?; @@ -251,6 +254,9 @@ fn remapped_grid(mut grid: [u32; 3], remap: Option<(u32, u32)>) -> Option<[u32; /// common to every piece and the whole fallback. Choose before recording any /// part of the dispatch, including when scratch allocation fails. pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, grid: [u32; 3]) -> Result<(), String> { + if grid.into_iter().any(|n| n > 65_535) { + return Err("dispatch group count exceeds 65535 on one axis".into()); + } let [x, y, z] = grid; let chain = CHAINS.lock().unwrap().get(&pso).cloned(); let Some(chain) = chain else { @@ -300,6 +306,10 @@ mod tests { fn remapped_grid_scales_only_its_dimension_and_refuses_overflow() { assert_eq!(remapped_grid([3, 5, 7], Some((4, 1))), Some([3, 20, 7])); assert_eq!(remapped_grid([3, 5, 7], None), Some([3, 5, 7])); + assert_eq!(remapped_grid([65_535, 1, 1], None), Some([65_535, 1, 1])); + assert_eq!(remapped_grid([65_536, 1, 1], None), None); + assert_eq!(remapped_grid([1, 65_536, 1], None), None); + assert_eq!(remapped_grid([1, 1, 65_536], None), None); assert_eq!(remapped_grid([32_768, 1, 1], Some((2, 0))), None); assert_eq!(remapped_grid([u32::MAX, 1, 1], Some((2, 0))), None); assert_eq!(remapped_grid([1, 1, 1], Some((2, 3))), None); From 87b55ac8289615430926ec75550e224c9364e2df Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:11:32 -0800 Subject: [PATCH 103/265] D3D12.X: serialize each queue submission turn Give every command queue a re-entrant per-generation lease. Native ExecuteCommandLists and its allocator, write, and texture-state publication now form one turn, while refresh and cross-queue preparation stay outside to avoid lock cycles. Signal, Wait, and SignalX use the same ordering primitive; final Release cannot remove a replacement queue generation at a reused address. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/queue_submit.rs | 175 ++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 53 ++++--- 3 files changed, 208 insertions(+), 21 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/queue_submit.rs diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index c221345c66..e8caeb3629 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -28,6 +28,7 @@ pub mod list_x; pub mod null; pub mod present; pub mod pso_async; +mod queue_submit; pub mod real; mod shader_cache_session; pub mod sparse; diff --git a/crates/xcl/src/hle/d3d12x/queue_submit.rs b/crates/xcl/src/hle/d3d12x/queue_submit.rs new file mode 100644 index 0000000000..4f84f86e95 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/queue_submit.rs @@ -0,0 +1,175 @@ +//! Per-command-queue ordering for title and XCL submissions. +//! +//! XCL sometimes issues setup work from inside a title queue call. The lease is therefore +//! re-entrant on one thread, but excludes another thread until the whole ordered operation ends. + +use std::collections::HashMap; +use std::sync::{Arc, Condvar, Mutex, OnceLock, RwLock}; +use std::thread::ThreadId; + +#[derive(Default)] +struct State { + owner: Option, + depth: usize, + #[cfg(test)] + waiters: usize, +} + +#[derive(Default)] +struct Lease { + state: Mutex, + changed: Condvar, +} + +impl Lease { + fn enter(self: &Arc) -> Guard { + let me = std::thread::current().id(); + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + while state.owner.is_some_and(|owner| owner != me) { + #[cfg(test)] + { + state.waiters += 1; + } + state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); + #[cfg(test)] + { + state.waiters -= 1; + } + } + state.owner = Some(me); + state.depth += 1; + drop(state); + Guard(Arc::clone(self)) + } +} + +struct Guard(Arc); + +impl Drop for Guard { + fn drop(&mut self) { + let mut state = self.0.state.lock().unwrap_or_else(|e| e.into_inner()); + debug_assert_eq!(state.owner, Some(std::thread::current().id())); + debug_assert!(state.depth > 0); + state.depth -= 1; + if state.depth == 0 { + state.owner = None; + self.0.changed.notify_one(); + } + } +} + +fn leases() -> &'static RwLock>> { + static LEASES: OnceLock>>> = OnceLock::new(); + LEASES.get_or_init(|| RwLock::new(HashMap::new())) +} + +fn lease(queue: usize) -> Arc { + if let Some(lease) = leases().read().unwrap_or_else(|e| e.into_inner()).get(&queue).cloned() { + return lease; + } + let mut leases = leases().write().unwrap_or_else(|e| e.into_inner()); + Arc::clone(leases.entry(queue).or_default()) +} + +/// Start a new raw-address generation before the newly created queue is returned to its caller. +pub(super) fn created(queue: usize) { + if queue != 0 { + leases().write().unwrap_or_else(|e| e.into_inner()).insert(queue, Arc::new(Lease::default())); + } +} + +/// Run one ordered queue operation. Calls made recursively by XCL setup work retain the same turn. +pub(super) fn with(queue: usize, f: impl FnOnce() -> R) -> R { + if queue == 0 { + return f(); + } + let _guard = lease(queue).enter(); + f() +} + +/// Forward Release and discard the raw-address lease after a final native release. Pointer +/// identity prevents a newly created generation at the same address from being removed. +pub(super) fn release(queue: usize, f: impl FnOnce() -> u32) -> u32 { + let old = leases().read().unwrap_or_else(|e| e.into_inner()).get(&queue).cloned(); + let n = f(); + if n == 0 { + let mut leases = leases().write().unwrap_or_else(|e| e.into_inner()); + if old.as_ref().is_some_and(|old| leases.get(&queue).is_some_and(|current| Arc::ptr_eq(old, current))) { + leases.remove(&queue); + } + } + n +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + use std::time::Duration; + + #[test] + fn same_queue_is_reentrant_but_excludes_another_thread() { + let queue = 0x5151_0001; + let (entered_tx, entered_rx) = mpsc::channel(); + let (leave_tx, leave_rx) = mpsc::channel(); + let first = std::thread::spawn(move || { + with(queue, || { + with(queue, || entered_tx.send(()).unwrap()); + leave_rx.recv().unwrap(); + }); + }); + entered_rx.recv().unwrap(); + let (ready_tx, ready_rx) = mpsc::channel(); + let (second_tx, second_rx) = mpsc::channel(); + let second = std::thread::spawn(move || { + ready_tx.send(()).unwrap(); + with(queue, || second_tx.send(()).unwrap()) + }); + ready_rx.recv().unwrap(); + let start = std::time::Instant::now(); + while old_waiter_count(queue) == 0 && start.elapsed() < Duration::from_secs(1) { + std::thread::yield_now(); + } + assert_eq!(old_waiter_count(queue), 1, "the second thread reached the held lease"); + assert!(second_rx.try_recv().is_err()); + leave_tx.send(()).unwrap(); + second_rx.recv_timeout(Duration::from_secs(1)).unwrap(); + first.join().unwrap(); + second.join().unwrap(); + release(queue, || 0); + } + + #[test] + fn different_queues_do_not_share_a_turn() { + let (entered_tx, entered_rx) = mpsc::channel(); + let (leave_tx, leave_rx) = mpsc::channel(); + let first = std::thread::spawn(move || with(0x5151_0002, || { + entered_tx.send(()).unwrap(); + leave_rx.recv().unwrap(); + })); + entered_rx.recv().unwrap(); + with(0x5151_0003, || {}); + leave_tx.send(()).unwrap(); + first.join().unwrap(); + release(0x5151_0002, || 0); + release(0x5151_0003, || 0); + } + + #[test] + fn an_old_final_release_does_not_remove_a_reused_address() { + let queue = 0x5151_0004; + created(queue); + let old = lease(queue); + let n = release(queue, || { + created(queue); + 0 + }); + assert_eq!(n, 0); + assert!(!Arc::ptr_eq(&old, &lease(queue))); + release(queue, || 0); + } + + fn old_waiter_count(queue: usize) -> usize { + lease(queue).state.lock().unwrap_or_else(|e| e.into_inner()).waiters + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 82afd43530..ad45bd4592 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3197,6 +3197,9 @@ macro_rules! creator { } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { adopt(*ppv, $kind); + if $kind == Kind::CommandQueue { + super::queue_submit::created(*ppv as usize); + } } hr } @@ -7776,7 +7779,7 @@ fn forget_command_list(list: *mut c_void) { unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); + let n = super::queue_submit::release(this as usize, || f(this)); if n == 0 { super::list_x::on_queue_release(this as usize); } else if n == 1 { @@ -7917,7 +7920,7 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a let pc = |s: usize| orig_fn(this, s); match older { // Signal / Wait take a fence: anything else is not one of them - 14 | 15 if is_fence(a1) => { + 14 | 15 if is_fence(a1) => super::queue_submit::with(this as usize, || { if older == 14 { super::list_x::break_cycles_before_title_signal(this as usize, a1, a2 as u64); } @@ -7933,7 +7936,7 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a } } hr as u32 as usize - } + }), 16 => { let f: unsafe extern "system" fn(*mut c_void, usize) -> i32 = std::mem::transmute(pc(PC_TIMESTAMP_FREQUENCY)); f(this, a1) as u32 as usize @@ -8013,6 +8016,10 @@ queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, /// nothing left Fortnite's render fences pending: its render thread waited, textures were /// never released, and the garbage collector ended the game after 10 s.) unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, value: u64, _flags: u32) -> HRESULT { + super::queue_submit::with(this as usize, || q_signal_x_serialized(this, fence, value)) +} + +unsafe fn q_signal_x_serialized(this: *mut c_void, fence: *mut c_void, value: u64) -> HRESULT { const PC_SIGNAL: usize = 14; super::list_x::break_cycles_before_title_signal(this as usize, fence as usize, value); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, PC_SIGNAL)); @@ -8036,7 +8043,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteCommandLists"))); if n == 0 || lists.is_null() { - f(this, n, lists); + super::queue_submit::with(this as usize, || f(this, n, lists)); stop_if_device_removed(); return; } @@ -8070,25 +8077,29 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis let mut gate = super::alloc_pool::SubmissionGate::default(); let mut submitted = Vec::with_capacity(mapped.len()); let _ = super::list_x::execute_submission_plan_until_failure_on(this, &plan, |chunk| { - let lists = chunk.lists(); - if !gate.submit( - this, - lists, - || { - let _ = super::alloc_pool::note_resubmits(this, lists); - }, - || f(this, lists.len() as u32, lists.as_ptr()), - ) { - return (false, None); - } - chunks += 1; - submitted.extend_from_slice(lists); - super::list_x::copy_scratch_submitted(this, lists); - (true, chunk.submit_effects(this)) + super::queue_submit::with(this as usize, || { + let lists = chunk.lists(); + if !gate.submit( + this, + lists, + || { + let _ = super::alloc_pool::note_resubmits(this, lists); + }, + || f(this, lists.len() as u32, lists.as_ptr()), + ) { + return (false, None); + } + chunks += 1; + submitted.extend_from_slice(lists); + super::list_x::copy_scratch_submitted(this, lists); + let completion = chunk.submit_effects(this); + // State and last-writer publication belong to the same queue turn as execution; + // a following Signal must not observe only half of this submission. + super::title_textures::submitted(lists); + (true, completion) + }) }); super::alloc_pool::note_execute_call(chunks); - // the next uploads into textures kept in step start from the states these lists leave - super::title_textures::submitted(&submitted); super::present::note_execute(this, &submitted); stop_if_device_removed(); } From 9e82e2aa2541928dc6e6254eb7b085a3c14b3f74 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:14:02 -0800 Subject: [PATCH 104/265] D3D12.X: cache native extended graphics streams Give translated extended graphics streams a canonical pointer-free identity and reuse driver blobs from bounded RAM or disk caches. Cached-blob refusal is retried before rect-list GS fallback, while unrelated failures preserve their HRESULT and cache generation. Exact-generation invalidation prevents a delayed rejection from evicting a newer RAM replacement; the no-GS fallback deliberately remains uncached under the with-GS identity. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 239 ++++++++++++++++-- .../src/hle/d3d12x/real/two_pass_identity.rs | 46 +++- 2 files changed, 266 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 82afd43530..6a277b69a5 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5158,7 +5158,7 @@ pub(crate) mod driver_cache { /// A bounded set of driver blobs plus capture/publication ownership for duplicate builders. struct DriverBlobs { blobs: Mutex>>, usize)>>, - keeping: Mutex, HashSet)>>, + keeping: Mutex, HashMap>>)>>, } impl DriverBlobs { @@ -5175,27 +5175,55 @@ impl DriverBlobs { return false; } let mut guard = self.keeping.lock().unwrap(); - let (active, persisted) = guard.get_or_insert_with(|| (HashSet::new(), HashSet::new())); - !persisted.contains(&key) && active.insert(key) + let (active, persisted) = guard.get_or_insert_with(|| (HashSet::new(), HashMap::new())); + !persisted.contains_key(&key) && active.insert(key) } fn finish(&self, key: K, blob: Option>>, limit: usize, persisted: bool) { + let mut generation = None; if let Some(blob) = blob { let mut guard = self.blobs.lock().unwrap(); let (map, total) = guard.get_or_insert_with(|| (HashMap::new(), 0)); if !map.contains_key(&key) && blob.len() <= limit.saturating_sub(*total) { *total += blob.len(); map.insert(key, blob); + generation = map.get(&key).map(std::sync::Arc::downgrade); } } let mut guard = self.keeping.lock().unwrap(); let (active, stored) = guard.as_mut().unwrap(); active.remove(&key); if persisted { - stored.insert(key); + stored.insert(key, generation.unwrap_or_default()); } } + /// Remove only the generation that a rejected lookup actually used. A builder may have + /// published a replacement under the same key while that driver call was in flight. + fn forget_if(&self, key: K, expected: &std::sync::Arc>) -> bool { + let removed = if let Some((map, total)) = self.blobs.lock().unwrap().as_mut() { + if map.get(&key).is_some_and(|blob| std::sync::Arc::ptr_eq(blob, expected)) { + let blob = map.remove(&key).unwrap(); + *total -= blob.len(); + true + } else { + false + } + } else { + false + }; + if removed { + if let Some((_, persisted)) = self.keeping.lock().unwrap().as_mut() { + if persisted.get(&key).and_then(std::sync::Weak::upgrade) + .is_some_and(|blob| std::sync::Arc::ptr_eq(&blob, expected)) + { + persisted.remove(&key); + } + } + } + removed + } + fn forget(&self, key: K) { if let Some((map, total)) = self.blobs.lock().unwrap().as_mut() { if let Some(blob) = map.remove(&key) { @@ -5302,6 +5330,33 @@ mod compute_blob_tests { assert!(super::compute_blob(key).is_none()); assert_eq!(super::COMPUTE_BLOBS.blobs.lock().unwrap().as_ref().unwrap().1, before - 3); } + + #[test] + fn delayed_rejection_cannot_remove_a_replacement_generation() { + let cache = std::sync::Arc::new(super::DriverBlobs::new()); + assert!(cache.reserve(7u64)); + cache.finish(7, Some(std::sync::Arc::new(b"old".to_vec())), 32, false); + let old = cache.get(7).unwrap(); + let release = std::sync::Arc::new(std::sync::Barrier::new(2)); + let worker = { + let (cache, release, old) = (cache.clone(), release.clone(), old.clone()); + std::thread::spawn(move || { + release.wait(); + cache.forget_if(7, &old) + }) + }; + + // Another rejection removes the old value and a builder publishes its replacement + // before the delayed driver call reports its result. + cache.forget(7); + assert!(cache.reserve(7)); + let fresh = std::sync::Arc::new(b"fresh".to_vec()); + cache.finish(7, Some(fresh.clone()), 32, false); + release.wait(); + assert!(!worker.join().unwrap()); + assert!(std::sync::Arc::ptr_eq(&cache.get(7).unwrap(), &fresh)); + assert!(cache.forget_if(7, &fresh), "the exact generation remains invalidatable"); + } } /// Read `GetCachedBlob` from either an adopted or raw PC `ID3D12PipelineState`. @@ -5362,6 +5417,10 @@ fn forget_graphics_blob(key: (u64, usize)) { GRAPHICS_BLOBS.forget(key); } +fn forget_graphics_blob_if(key: (u64, usize), expected: &std::sync::Arc>) -> bool { + GRAPHICS_BLOBS.forget_if(key, expected) +} + /// Deterministic FNV-1a digest of every field in a translated PC graphics PSO (shaders, static /// samplers, blend/rasterizer/depth-stencil state, input layout, render target / depth formats, /// sample desc, topology, flags) for in-memory and on-disk driver blob caching. @@ -5647,6 +5706,70 @@ mod graphics_blob_tests { assert!(!build.cache_eligible); assert!(!copy.GS.pShaderBytecode.is_null()); } + + #[test] + fn native_stream_drops_stale_cache_before_rect_gs_fallback() { + let mut with_gs = StreamOut::default(); + with_gs.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, b"vs"); + with_gs.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, b"gs"); + let mut without_gs = StreamOut::default(); + without_gs.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, b"vs"); + let mut stale = 0; + let mut attempts = Vec::new(); + let build = create_graphics_stream_cached( + &with_gs, + Some(&without_gs), + Some(b"stale blob"), + || stale += 1, + |_, cached, stream| { + let subs = stream_subobjects(&stream.0).unwrap(); + let gs = subs.iter().any(|(ty, _)| *ty == 5); + let has_blob = subs.iter().any(|(ty, _)| *ty == 19); + attempts.push((cached, has_blob, gs)); + let hr = if cached || gs { E_INVALIDARG } else { S_OK }; + (hr, std::time::Duration::from_millis(1)) + }, + ); + assert_eq!(build.hr, S_OK); + assert_eq!(stale, 1); + assert_eq!(attempts, [(true, true, true), (false, false, true), (false, false, false)]); + assert!(!build.cache_eligible, "the no-GS fallback has a different identity"); + assert!(!build.used_rect_gs); + } + + #[test] + fn native_stream_retries_only_cached_blob_refusals() { + let mut stream = StreamOut::default(); + stream.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, b"vs"); + for failure in [E_OUTOFMEMORY, 0x887a_0005u32 as i32, 0x8000_4005u32 as i32] { + let (mut calls, mut evictions) = (0, 0); + let build = create_graphics_stream_cached( + &stream, + None, + Some(b"blob"), + || evictions += 1, + |_, _, _| { calls += 1; (failure, std::time::Duration::ZERO) }, + ); + assert_eq!(build.hr, failure); + assert_eq!((calls, evictions), (1, 0), "{failure:#x} is not evidence of a stale blob"); + } + + for stale in [E_INVALIDARG, 0x887e_0001u32 as i32, 0x887e_0002u32 as i32] { + let (mut calls, mut evictions) = (0, 0); + let build = create_graphics_stream_cached( + &stream, + None, + Some(b"blob"), + || evictions += 1, + |_, cached, _| { + calls += 1; + (if cached { stale } else { E_OUTOFMEMORY }, std::time::Duration::ZERO) + }, + ); + assert_eq!(build.hr, E_OUTOFMEMORY, "the final retry HRESULT is preserved"); + assert_eq!((calls, evictions), (2, 1)); + } + } } struct GraphicsPsoBuild { @@ -6366,7 +6489,7 @@ const SHADER_SUBOBJECTS: [D3D12_PIPELINE_STATE_SUBOBJECT_TYPE; 8] = [ /// A pipeline state stream being written: subobjects aligned as D3D12 expects /// (type, payload at 4 or 8, size rounded to 8). -#[derive(Default)] +#[derive(Clone, Default)] struct StreamOut(Vec, usize); impl StreamOut { @@ -6519,7 +6642,7 @@ fn passthrough_mesh_stream_accepts_a_triangle_driver_blob() { } } -#[allow(dead_code)] // Consumed by the stacked driver-cache integration. +#[allow(dead_code)] // Two-pass identities are consumed by the next stacked cache stage. mod two_pass_identity; /// The console PS of a two-pass pipeline (a PC PS passes as it is). @@ -7441,6 +7564,67 @@ unsafe fn rewrite_graphics_stream( out } +struct GraphicsStreamBuild { + hr: HRESULT, + built_in_driver: std::time::Duration, + reused: bool, + cache_eligible: bool, + used_rect_gs: bool, +} + +/// HRESULTs documented for a cached pipeline made by another adapter or driver, plus the +/// invalid-argument result D3D12Core returns for an otherwise unreadable cached blob. +fn stale_cached_pso_refusal(hr: HRESULT) -> bool { + matches!(hr as u32, 0x8007_0057 | 0x887e_0001 | 0x887e_0002) +} + +fn create_graphics_stream_cached( + stream: &StreamOut, + without_rect_gs: Option<&StreamOut>, + cached: Option<&[u8]>, + mut on_stale_cache: impl FnMut(), + mut run: impl FnMut(&str, bool, &StreamOut) -> (HRESULT, std::time::Duration), +) -> GraphicsStreamBuild { + if let Some(blob) = cached { + let mut with_cache = stream.clone(); + with_cache.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, &D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: blob.as_ptr() as *const c_void, + CachedBlobSizeInBytes: blob.len(), + }); + let (hr, took) = run("graphics stream", true, &with_cache); + if hr >= 0 { + return GraphicsStreamBuild { hr, built_in_driver: took, reused: true, cache_eligible: false, used_rect_gs: without_rect_gs.is_some() }; + } + if !stale_cached_pso_refusal(hr) { + return GraphicsStreamBuild { hr, built_in_driver: took, reused: false, cache_eligible: false, used_rect_gs: without_rect_gs.is_some() }; + } + // A cached blob describes the stream including its rect-list GS. Discard it before + // deciding whether the driver objects to that GS rather than to the stale blob. + on_stale_cache(); + } + let label = if cached.is_some() { "graphics stream retry" } else { "graphics stream" }; + let (hr, took) = run(label, false, stream); + if rejected_rect_list_gs(hr, without_rect_gs.is_some()) { + note_translation_error(format!("the driver rejected the graphics stream with the rect list GS ({hr:#x}): rect list drawn as triangles")); + let (fallback, fallback_took) = run("graphics stream without rect GS", false, without_rect_gs.unwrap()); + return GraphicsStreamBuild { + hr: fallback, + built_in_driver: fallback_took, + reused: false, + // The fallback is a different pipeline and must never replace the with-GS key. + cache_eligible: false, + used_rect_gs: false, + }; + } + GraphicsStreamBuild { + hr, + built_in_driver: took, + reused: false, + cache_eligible: hr >= 0, + used_rect_gs: without_rect_gs.is_some(), + } +} + unsafe fn translated_graphics_stream(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { with_switch_fallback(|| translated_graphics_stream_once(this, desc, riid, ppv)) } @@ -7477,16 +7661,41 @@ unsafe fn translated_graphics_stream_once(this: *mut c_void, desc: *const c_void let ps_hash = console_ps.map_or(0, crate::gpu::shader::fnv64); let (no_stencil, no_cull) = (debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash), debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash)); let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); - let submit = |out: &StreamOut| { + let stream = rewrite_graphics_stream(&subs, rs, &vs_c.dxil, ps_dxil.as_deref(), rect_gs.as_deref(), no_stencil, no_cull); + let without_rect_gs = rect_gs.as_ref().map(|_| rewrite_graphics_stream(&subs, rs, &vs_c.dxil, ps_dxil.as_deref(), None, no_stencil, no_cull)); + let key = two_pass_identity::graphics_stream_key(&stream.0, &samplers, crate::gpu::recomp::pso::mem_windows()); + let mut cached = key.and_then(graphics_blob); + let disk = key.and_then(|k| driver_cache::graphics_path(k.0, k.1)); + let from_disk = key.is_some() && cached.is_none(); + let mut loaded = None; + if from_disk { + loaded = disk.as_deref().and_then(driver_cache::load); + cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); + } + let submit = |label: &str, has_cached: bool, out: &StreamOut| { let d = [out.0.len(), out.0.as_ptr() as usize]; - driver_compile("graphics stream", out.shader_bytes(), true, || finish_pso(this, fs, d.as_ptr() as *const c_void, riid, ppv)) + driver_compile_identified(label, out.shader_bytes(), gate_compute_driver_compile(has_cached), Some((ps_hash, has_cached)), + || finish_pso(this, fs, d.as_ptr() as *const c_void, riid, ppv)) }; - let mut hr = submit(&rewrite_graphics_stream(&subs, rs, &vs_c.dxil, ps_dxil.as_deref(), rect_gs.as_deref(), no_stencil, no_cull)); - let mut used_rect_gs = rect_gs.is_some(); - if rejected_rect_list_gs(hr, used_rect_gs) { - note_translation_error(format!("the driver rejected the graphics stream with the rect list GS ({hr:#x}): rect list drawn as triangles")); - hr = submit(&rewrite_graphics_stream(&subs, rs, &vs_c.dxil, ps_dxil.as_deref(), None, no_stencil, no_cull)); - used_rect_gs = false; + let rejected_generation = cached.clone(); + let build = create_graphics_stream_cached( + &stream, + without_rect_gs.as_ref(), + cached.as_deref().map(Vec::as_slice), + || { + if let (Some(k), Some(expected)) = (key, rejected_generation.as_ref()) { + forget_graphics_blob_if(k, expected); + } + if from_disk { driver_cache::note(false, loaded.take()); } + }, + submit, + ); + let hr = build.hr; + if let Some(k) = key.filter(|_| build.cache_eligible) { + keep_driver_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, k, stream.shader_bytes(), disk.as_deref(), build.built_in_driver, + || read_pso_cached_blob(*ppv)); + } else if build.reused && from_disk { + driver_cache::note(true, loaded.take()); } if hr < 0 { note_translation_error(format!("the driver rejected the graphics stream with the translated shaders ({hr:#x})")); @@ -7497,7 +7706,7 @@ unsafe fn translated_graphics_stream_once(this: *mut c_void, desc: *const c_void note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", console_ps)]); TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); - if used_rect_gs { RECT_LIST_GS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); } + if build.used_rect_gs { RECT_LIST_GS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); } } if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: graphics stream PSO from translated console shaders (#{})", n + 1); } Some(hr) diff --git a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs index 6ca0572281..3bfe808dde 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -4,6 +4,8 @@ use windows::Win32::Graphics::Direct3D12::*; /// Bump on any change to two-pass cache key fields or ABI root-signature layout to invalidate stale disk entries. const TWO_PASS_CACHE_SCHEMA: u32 = 2; +/// Native extended graphics streams have a separate identity namespace from two-pass streams. +const GRAPHICS_STREAM_CACHE_SCHEMA: u32 = 1; /// ABI root signature layout tag for two-pass pipelines (`graphics = true`: 6 root UAVs + directly indexed heaps + IA flag). const TWO_PASS_ABI_RS_TAG: u32 = 0x5253_0001; @@ -176,7 +178,10 @@ unsafe fn hash_depth_stencil(h: &mut Fnv64, ty: u32, p: &[u8]) -> Option<()> { /// Canonical cache key `(hash, total_shader_bytes)` for a two-pass mesh/PS pipeline stream, /// hashing referenced shader bytecodes and normalized fixed-function state (never pointers or /// struct padding). Shader pointers in the stream must refer to live shader bytecode. Returns `None` if an unsupported, duplicate, or unknown subobject is active. -pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gpu::recomp::pso::StaticSampler], driver_id: u64, mem_windows: u32) -> Option<(u64, usize)> { +unsafe fn stream_key( + stream: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], schema: u32, + kind: u32, driver_id: u64, mem_windows: u32, +) -> Option<(u64, usize)> { let mut subs = stream_subobjects(stream)?; let total = subs.iter().map(|(ty, payload)| { let (_, align) = super::super::null::subobject_payload(*ty).unwrap(); @@ -190,12 +195,12 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp return None; } let mut h = Fnv64::new(); - h.u32(TWO_PASS_CACHE_SCHEMA); - h.u32(1); // stream kind + h.u32(schema); + h.u32(kind); h.u32(TWO_PASS_ABI_RS_TAG); h.u32(mem_windows); h.u64(driver_id); - samplers_hash_into(&mut h, ps_samplers); + samplers_hash_into(&mut h, samplers); let mut shader_bytes = 0usize; for (ty, payload) in subs { match ty { @@ -237,6 +242,16 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp Some((h.finish(), shader_bytes)) } +pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gpu::recomp::pso::StaticSampler], driver_id: u64, mem_windows: u32) -> Option<(u64, usize)> { + stream_key(stream, ps_samplers, TWO_PASS_CACHE_SCHEMA, 1, driver_id, mem_windows) +} + +/// Canonical identity for a translated native graphics stream. The distinct schema/kind prevents +/// its driver blobs from aliasing either legacy graphics descriptors or two-pass mesh streams. +pub(super) unsafe fn graphics_stream_key(stream: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], mem_windows: u32) -> Option<(u64, usize)> { + stream_key(stream, samplers, GRAPHICS_STREAM_CACHE_SCHEMA, 3, 0, mem_windows) +} + pub(super) fn two_pass_cs_key(cs: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], driver_id: u64, mem_windows: u32) -> u64 { let mut h = Fnv64::new(); h.u32(TWO_PASS_CACHE_SCHEMA); @@ -333,6 +348,29 @@ mod tests { } } + #[test] + fn graphics_stream_key_is_canonical_distinct_and_pointer_free() { + let vs = [1u8, 2, 3, 4]; + let mut a = StreamOut::default(); + a.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs); + a.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &7u32); + let mut b = StreamOut::default(); + b.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &7u32); + b.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs); + unsafe { + let ga = graphics_stream_key(&a.0, &[], 1).unwrap(); + assert_eq!(ga, graphics_stream_key(&b.0, &[], 1).unwrap()); + assert_ne!(ga, two_pass_stream_key(&a.0, &[], 0, 1).unwrap()); + assert_ne!(ga, graphics_stream_key(&a.0, &[([1, 2, 3, 4], false)], 1).unwrap()); + + let mut pointer = StreamOut(a.0.clone(), a.1); + pointer.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, &D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: 0x1234 as *const _, NumElements: 1, + }); + assert_eq!(graphics_stream_key(&pointer.0, &[], 1), None); + } + } + #[test] fn two_pass_keys_cover_mem_windows_invalid_counts_and_duplicates() { let mut s = StreamOut::default(); From f34a5eab01e9b36d41747d914cdc375fe6311f6e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:16:14 -0800 Subject: [PATCH 105/265] D3D12.X: measure contended queue submission turns Record the wait under the existing lock-contention stall category only when another thread owns the same queue lease. Uncontended queue operations do not start a recorder span. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/queue_submit.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/queue_submit.rs b/crates/xcl/src/hle/d3d12x/queue_submit.rs index 4f84f86e95..b7a6f2314b 100644 --- a/crates/xcl/src/hle/d3d12x/queue_submit.rs +++ b/crates/xcl/src/hle/d3d12x/queue_submit.rs @@ -25,6 +25,9 @@ impl Lease { fn enter(self: &Arc) -> Guard { let me = std::thread::current().id(); let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + let _stall = state.owner.is_some_and(|owner| owner != me) + .then(|| crate::stall::span(crate::stall::StallKind::LockContention)) + .flatten(); while state.owner.is_some_and(|owner| owner != me) { #[cfg(test)] { From 89343644f5e9d418c0c64b651eb9c0d42255b845 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:19:37 -0800 Subject: [PATCH 106/265] D3D12.X: call native queue slots for internal work Route XCL-owned Execute, Signal, and Wait operations through the original PC queue slots so adopted console layouts cannot turn them into shifted wrappers or successful stubs. Keep every operation inside the reentrant per-queue submission turn and cover the shifted-vtable case with a synthetic queue.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/texture.rs | 13 +++-- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 2 +- crates/xcl/src/hle/d3d12x/cpu_writes.rs | 2 +- crates/xcl/src/hle/d3d12x/late_release.rs | 2 +- crates/xcl/src/hle/d3d12x/list_x.rs | 6 +-- crates/xcl/src/hle/d3d12x/present.rs | 6 +-- crates/xcl/src/hle/d3d12x/queue_submit.rs | 48 ++++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 56 +++++++++++++++++++-- crates/xcl/src/hle/d3d12x/sparse.rs | 14 +++--- crates/xcl/src/hle/d3d12x/title_textures.rs | 9 ++-- crates/xcl/src/hle/d3d12x/vram.rs | 10 ++-- 11 files changed, 135 insertions(+), 33 deletions(-) diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index 4a6159ea1d..b68e3d5a6c 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -195,7 +195,8 @@ pub unsafe fn upload(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D1 let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; let staging = record_upload(dev, &list, res, subs, before, after)?; list.Close().map_err(err)?; - queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]); + let list = windows::core::Interface::cast(&list).map_err(err)?; + crate::hle::d3d12x::real::native_queue_execute(queue, &list); let r = wait(dev, queue); drop(staging); r @@ -305,10 +306,11 @@ pub(crate) unsafe fn upload_batch_with_zero_mips( record_into(&up.list, res, subs, &l, states, states, &staging, mapped, offsets); } up.list.Close().map_err(err)?; - queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&up.list).map_err(err)?)]); + let list = windows::core::Interface::cast(&up.list).map_err(err)?; + crate::hle::d3d12x::real::native_queue_execute(queue, &list); up.value += 1; let copy_error = |e| format!("texture copy: {e}"); - queue.Signal(&up.fence, up.value).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?; + crate::hle::d3d12x::real::native_queue_signal(queue, &up.fence, up.value).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?; if let Err(e) = fence::wait(&up.fence, up.value, dev, None, 10_000) { // the GPU may still read the upload buffer and run the list: they stay alive (a fresh // uploader next time) – freeing them under the GPU removed the device @@ -386,7 +388,8 @@ pub(crate) unsafe fn submit_batch_with_zero_mips( } staging.Unmap(0, None); list.Close().map_err(err)?; - queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]); + let cmd = windows::core::Interface::cast(&list).map_err(err)?; + crate::hle::d3d12x::real::native_queue_execute(queue, &cmd); Ok((failed, Some(InFlight { _alloc: alloc, _list: list, _staging: staging, bytes: zero.end }))) } @@ -592,7 +595,7 @@ pub unsafe fn wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue) -> Result<(), let copy_error = |e| format!("texture copy: {e}"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) .map_err(|e| copy_error(fence::api_error(dev, "CreateFence", e)))?; - queue.Signal(&fence, 1).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?; + crate::hle::d3d12x::real::native_queue_signal(queue, &fence, 1).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?; fence::wait(&fence, 1, dev, None, 10_000).map_err(copy_error) } diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 1ffd5bcf6c..0c39bca2ee 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -390,7 +390,7 @@ impl PendingSubmit { let (fence, value) = { let (fence, value) = s.fences.get_mut(&key).unwrap(); SUBMIT.signal_attempts.fetch_add(1, Ordering::Relaxed); - if q.Signal(&*fence, *value + 1).is_err() { + if super::real::native_queue_signal(q, &*fence, *value + 1).is_err() { SUBMIT.signal_failures.fetch_add(1, Ordering::Relaxed); return false; } diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index f9dd01ada3..1d8f484f7d 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -214,7 +214,7 @@ unsafe fn schedule(queue: *mut c_void, writes: Vec, completion: bool) -> } }; entry.value += 1; - if q.Signal(&entry.fence, entry.value).is_err() { + if super::real::native_queue_signal(q, &entry.fence, entry.value).is_err() { return None; } Job { fence: entry.fence.clone(), value: entry.value, writes, done } diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 74ed1fbd0a..2c5e07afd1 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -62,7 +62,7 @@ impl Held { self.fences.insert(key, (f, 0)); } let (fence, value) = self.fences.get_mut(&key).unwrap(); - if q.Signal(&*fence, *value + 1).is_err() { + if super::real::native_queue_signal(q, &*fence, *value + 1).is_err() { ok = false; break; } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index d4c4c78eb2..00c1e896c3 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2258,7 +2258,7 @@ unsafe fn signal_write64_pairs(queue: *mut c_void, pairs: &[(u64, u64)]) { match action { SignalAction::Skip => {} SignalAction::GpuSignal => { - if let Err(e) = q.Signal(&fence, val) { + if let Err(e) = super::real::native_queue_signal(q, &fence, val) { crate::xlog_warn!("D3D12.X: Write64 fence Signal({va:#x}, {val:#x}) failed ({e}) – signalling on CPU"); let _ = fence.Signal(val); } @@ -2414,7 +2414,7 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, (pre_ok.0, pre_ok.1, pre_ok.2, wait_seq) }; - if let Err(e) = q.Wait(&fence, w.value) { + if let Err(e) = super::real::native_queue_wait(q, &fence, w.value) { let mut g = SYNC_GRAPH.lock().unwrap(); if let Some(cell) = g.as_mut().and_then(|gr| gr.cells.get_mut(&w.va)) { if let Some(pos) = cell.armed_waits.iter().rposition(|aw| aw.val == w.value && aw.waiting_queue == q_raw && aw.wait_seq == wait_seq) { @@ -2827,7 +2827,7 @@ pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_ } let (fence, value) = cache.fences.get_mut(&key)?; let next = *value + 1; - q.Signal(&*fence, next).ok()?; + super::real::native_queue_signal(q, &*fence, next).ok()?; *value = next; Some((fence.clone(), next)) })(); diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 1c75ca0781..54d02f5fad 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -627,7 +627,7 @@ pub(super) unsafe fn retire_released_queue(raw: usize) { let mut dev: Option = None; queue.GetDevice(&mut dev).ok()?; let fence = dev?.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()?; - queue.Signal(&fence, 1).ok()?; + super::real::native_queue_signal(&queue, &fence, 1).ok()?; Some(QueueRetirementMark { fence, value: 1 }) })(); let Some(mark) = mark else { @@ -1540,11 +1540,11 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, let qraw = queue as *mut c_void; let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qraw) else { return }; let Ok(cl) = p.list.cast::() else { return }; - q.ExecuteCommandLists(&[Some(cl)]); + super::real::native_queue_execute(q, &cl); p.copy_sources = resolved.into_iter().map(|(r, _, _)| r).collect(); p.dumps = dumps; p.value += 1; - if let Err(e) = q.Signal(&p.fence, p.value) { + if let Err(e) = super::real::native_queue_signal(q, &p.fence, p.value) { // The copy is already submitted. Without its signal, keep its resources and allocator. p.disabled = true; let e = fence::api_error(&p.dev, "Signal", e); diff --git a/crates/xcl/src/hle/d3d12x/queue_submit.rs b/crates/xcl/src/hle/d3d12x/queue_submit.rs index 4f84f86e95..ebc9284831 100644 --- a/crates/xcl/src/hle/d3d12x/queue_submit.rs +++ b/crates/xcl/src/hle/d3d12x/queue_submit.rs @@ -104,8 +104,25 @@ pub(super) fn release(queue: usize, f: impl FnOnce() -> u32) -> u32 { #[cfg(test)] mod tests { use super::*; + use std::ffi::c_void; use std::sync::mpsc; + use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D12::{ID3D12CommandQueue, ID3D12Fence}; + + static NATIVE_SIGNAL: AtomicU64 = AtomicU64::new(0); + static WRAPPER_SIGNAL: AtomicU64 = AtomicU64::new(0); + + unsafe extern "system" fn fake_native_signal(_: *mut c_void, _: *mut c_void, value: u64) -> i32 { + NATIVE_SIGNAL.store(value, Ordering::Relaxed); + 0 + } + + unsafe extern "system" fn fake_shifted_wrapper(_: *mut c_void, _: *mut c_void, value: u64) -> i32 { + WRAPPER_SIGNAL.store(value, Ordering::Relaxed); + 0 + } #[test] fn same_queue_is_reentrant_but_excludes_another_thread() { @@ -169,6 +186,37 @@ mod tests { release(queue, || 0); } + #[test] + fn internal_signal_reenters_the_lease_and_uses_the_native_slot() { + NATIVE_SIGNAL.store(0, Ordering::Relaxed); + WRAPPER_SIGNAL.store(0, Ordering::Relaxed); + let mut original = vec![0usize; 16]; + original[14] = fake_native_signal as usize; + let mut extended = vec![0usize; 17]; + extended[0] = original.as_ptr() as usize; + extended[15] = fake_shifted_wrapper as usize; // ext[14], as a shifted title layout sees it + let ext = unsafe { extended.as_mut_ptr().add(1) }; + struct Registered(usize); + impl Drop for Registered { + fn drop(&mut self) { super::super::real::register_test_queue_vtable(self.0, false); } + } + super::super::real::register_test_queue_vtable(ext as usize, true); + let _registered = Registered(ext as usize); + let mut queue_object = [ext as usize]; + let mut fence_object = [0usize]; + let queue_raw = queue_object.as_mut_ptr() as *mut c_void; + let fence_raw = fence_object.as_mut_ptr() as *mut c_void; + let queue = unsafe { ID3D12CommandQueue::from_raw_borrowed(&queue_raw).unwrap() }; + let fence = unsafe { ID3D12Fence::from_raw_borrowed(&fence_raw).unwrap() }; + + with(queue_raw as usize, || unsafe { + super::super::real::native_queue_signal(queue, fence, 0x5151).unwrap(); + }); + assert_eq!(NATIVE_SIGNAL.load(Ordering::Relaxed), 0x5151); + assert_eq!(WRAPPER_SIGNAL.load(Ordering::Relaxed), 0, "the adopted title wrapper must be bypassed"); + release(queue_raw as usize, || 0); + } + fn old_waiter_count(queue: usize) -> usize { lease(queue).state.lock().unwrap_or_else(|e| e.into_inner()).waiters } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 96870e0f30..425db7bc70 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -265,8 +265,9 @@ unsafe fn check_uma_import(device: &ID3D12Device, u: &crate::gpu::uma::Uma, bufs } let run = || -> Result, String> { list.Close().map_err(|e| format!("check not run: Close: {e}"))?; - queue.ExecuteCommandLists(&[Some(list.cast::().map_err(|e| e.to_string())?)]); - queue.Signal(&fence, 1).map_err(|e| format!("check not run: Signal: {e}"))?; + let list = list.cast::().map_err(|e| e.to_string())?; + native_queue_execute(&queue, &list); + native_queue_signal(&queue, &fence, 1).map_err(|e| format!("check not run: Signal: {e}"))?; crate::gpu::fence::wait(&fence, 1, device, None, 2000).map_err(|e| format!("check not run: {e}"))?; let mut m = std::ptr::null_mut(); readback.Map(0, None, Some(&mut m)).map_err(|e| format!("check not run: Map: {e}"))?; @@ -637,6 +638,55 @@ pub unsafe fn orig_fn(this: *mut c_void, slot: usize) -> usize { *orig.add(slot) } +unsafe fn native_queue_fn(queue: *mut c_void, slot: usize) -> usize { + let table = vt(queue); + if is_ext(table as usize) { orig_fn(queue, slot) } else { *table.add(slot) } +} + +/// Submit XCL's own list through the PC queue slot, never through the title-facing wrapper. +/// The queue lease makes this one ordered operation, and is re-entrant when a title submit is +/// already publishing its effects. +pub(crate) unsafe fn native_queue_execute(queue: &ID3D12CommandQueue, list: &ID3D12CommandList) { + let raw = queue.as_raw(); + type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let f = native_queue_fn(raw, 10); + super::queue_submit::with(raw as usize, || { + let f: F = std::mem::transmute(f); + let list = list.as_raw(); + f(raw, 1, &list); + }); +} + +/// Signal through the PC queue slot. Console queue layouts remap public slots 14+, so an +/// internal COM call on an adopted queue is not a reliable way to reach native Signal. +pub(crate) unsafe fn native_queue_signal(queue: &ID3D12CommandQueue, fence: &ID3D12Fence, value: u64) -> windows::core::Result<()> { + let raw = queue.as_raw(); + type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT; + let f = native_queue_fn(raw, 14); + super::queue_submit::with(raw as usize, || { + let f: F = std::mem::transmute(f); + windows::core::HRESULT(f(raw, fence.as_raw(), value)).ok() + }) +} + +/// Wait through the PC queue slot, bypassing the title's shifted queue layout. +pub(crate) unsafe fn native_queue_wait(queue: &ID3D12CommandQueue, fence: &ID3D12Fence, value: u64) -> windows::core::Result<()> { + let raw = queue.as_raw(); + type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT; + let f = native_queue_fn(raw, 15); + super::queue_submit::with(raw as usize, || { + let f: F = std::mem::transmute(f); + windows::core::HRESULT(f(raw, fence.as_raw(), value)).ok() + }) +} + +#[cfg(test)] +pub(super) fn register_test_queue_vtable(ext: usize, add: bool) { + let mut tables = EXTS.lock().unwrap(); + let tables = tables.get_or_insert_with(HashSet::new); + if add { tables.insert(ext); } else { tables.remove(&ext); } +} + fn module_of(addr: usize) -> usize { use windows_sys::Win32::System::LibraryLoader::{ GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, @@ -8130,7 +8180,7 @@ pub fn drain_gpu() { let submit = || { let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) .map_err(|e| fence::api_error(dev, "CreateFence", e))?; - q.Signal(&f, 1).map_err(|e| fence::api_error(dev, "Signal", e))?; + native_queue_signal(&q, &f, 1).map_err(|e| fence::api_error(dev, "Signal", e))?; Ok(f) }; match submit() { diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 25925c1262..8571e71455 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -889,7 +889,7 @@ impl State { #[inline] unsafe fn signal(&mut self) { self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); } #[inline] @@ -945,7 +945,7 @@ impl State { if closed { if let Ok(l) = self.slots[idx].list.cast::() { super::title_textures::own_work(|| { - self.queue.ExecuteCommandLists(&[Some(l)]); + super::real::native_queue_execute(&self.queue, &l); }); } } @@ -1096,7 +1096,7 @@ impl State { if s.rb_list.Close().is_ok() { if let Ok(l) = s.rb_list.cast::() { super::title_textures::own_work(|| { - s.queue.ExecuteCommandLists(&[Some(l)]); + super::real::native_queue_execute(&s.queue, &l); }); } } @@ -1332,8 +1332,8 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz } s.rb_value += 1; let v = s.rb_value; - if queue.Signal(&s.rb_fence, v).is_ok() { - let _ = s.queue.Wait(&s.rb_fence, v); + if super::real::native_queue_signal(queue, &s.rb_fence, v).is_ok() { + let _ = super::real::native_queue_wait(&s.queue, &s.rb_fence, v); super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); } s.readback_ranges(&merged); @@ -1517,7 +1517,7 @@ impl State { }, }; let next = entry.1 + 1; - if q.Signal(&entry.0, next).is_ok() { + if super::real::native_queue_signal(&q, &entry.0, next).is_ok() { entry.1 = next; marks.push((entry.0.clone(), next)); } else { @@ -1713,7 +1713,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: s.scratch_runs = dirty_runs; let q = queue.as_raw() as usize; if s.value > 0 && s.waited.get(&q).copied().unwrap_or(0) < s.value { - let _ = queue.Wait(&s.fence, s.value); + let _ = super::real::native_queue_wait(queue, &s.fence, s.value); super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &s.fence, s.value); s.waited.insert(q, s.value); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 697ef0de08..47dc84c92d 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1352,7 +1352,7 @@ unsafe fn submit_on_title_queue( } let q = g.get_mut(&key).unwrap(); q.value += 1; - if let Err(e) = queue.Signal(&q.fence, q.value) { + if let Err(e) = super::real::native_queue_signal(queue, &q.fence, q.value) { q.value -= 1; texture::wait(dev, queue)?; drop(f); @@ -1554,7 +1554,8 @@ pub unsafe fn probe_gpu_content(res: usize) { list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, srv)]); list.Close().map_err(|e| e.to_string())?; - queue.ExecuteCommandLists(&[Some(list.cast().map_err(|e| e.to_string())?)]); + let list = list.cast().map_err(|e| e.to_string())?; + super::real::native_queue_execute(&queue, &list); texture::wait(dev, &queue)?; let mut p: *mut c_void = std::ptr::null_mut(); rb.Map(0, None, Some(&mut p)).map_err(|e| e.to_string())?; @@ -2114,8 +2115,8 @@ impl TextureDownloadPlan { bytes: self.bytes, }; let list = pending.objects.as_ref().unwrap().list.clone(); - queue.ExecuteCommandLists(&[Some(list)]); - let signal_error = match queue.Signal(&pending.fence, 1) { + super::real::native_queue_execute(queue, &list); + let signal_error = match super::real::native_queue_signal(queue, &pending.fence, 1) { Ok(()) => { pending.fence_value = Some(1); None } Err(e) => Some(e.to_string()), }; diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 312262e4eb..b35a310514 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -726,7 +726,7 @@ impl Pages { ); } self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); } /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return @@ -751,7 +751,7 @@ impl Pages { D3D12_TILE_MAPPING_FLAG_NONE, ); self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); } fn release_tiles(&mut self, used: Vec, used_extra: Vec<(usize, usize)>, now: std::time::Instant, immediate_cool: bool) { @@ -1214,7 +1214,7 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla if newly_reclaimed.is_empty() && !map.contains_key(&dev_key) { return; } let rq = map.entry(dev_key).or_insert_with(RetireQueue::new); let before = rq.batches.len(); - let immediate = rq.retire_with(newly_reclaimed, unmap_mark, &queues, || dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok(), |q, f, v| q.Signal(f, v).is_ok()); + let immediate = rq.retire_with(newly_reclaimed, unmap_mark, &queues, || dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok(), |q, f, v| super::real::native_queue_signal(q, f, v).is_ok()); let (done, pruned) = rq.sweep_with(&live_keys, |f| f.GetCompletedValue()); RETIRING_BATCHES.fetch_add(rq.batches.len().wrapping_sub(before), std::sync::atomic::Ordering::AcqRel); (immediate, done, pruned) @@ -1241,7 +1241,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { if let Some(Some(pages)) = g.get_mut(&dev_key) { let key = queue.as_raw() as usize; if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { - let _ = queue.Wait(&pages.fence, pages.value); + let _ = super::real::native_queue_wait(queue, &pages.fence, pages.value); super::list_x::note_internal_wait(key, "texture page mappings", &pages.fence, pages.value); pages.waited.insert(key, pages.value); } @@ -1274,7 +1274,7 @@ pub(super) unsafe fn note_mapping_for_test(dev: &ID3D12Device) -> Option { let mut g = PAGES.lock().unwrap(); let pages = g.entry(dev.as_raw() as usize).or_insert_with(|| Pages::new(dev)).as_mut()?; pages.value += 1; - pages.queue.Signal(&pages.fence, pages.value).ok()?; + super::real::native_queue_signal(&pages.queue, &pages.fence, pages.value).ok()?; Some(pages.value) } From b0442a224f0634d6a3faf20b4f5ba3e2272c86ba Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:20:25 -0800 Subject: [PATCH 107/265] D3D12.X: capture texture transitions in submission plans Move tracked texture transitions from mutable list-address notes into generation-tagged physical-segment effects. Publish state transitions and GPU-writer ownership atomically only after the native submission gate accepts each chunk, preserving reset, replay, split, repeat, and wait-split chronology.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/console_list.rs | 4 +- crates/xcl/src/hle/d3d12x/list_x.rs | 132 ++++++++++++++----- crates/xcl/src/hle/d3d12x/real.rs | 6 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 138 +++++++++----------- 4 files changed, 161 insertions(+), 119 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 7726419583..c675e58e97 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -748,7 +748,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { } // the whole recording is replayed into the PC list here: its transitions of textures kept // in step are these - super::title_textures::list_reset(st.pc); + super::list_x::clear_texture_transitions(st.pc); super::dred::reset(st.pc as *mut c_void); let windows = super::real::uma_window_vas(); let va = |p: usize| super::real::uma_va_of(p).unwrap_or(uma_va); @@ -805,7 +805,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { // each barrier: type | flags, resource, subresource | before, after let t: Vec<(usize, u32, D3D12_RESOURCE_STATES)> = b.chunks_exact(4).filter(|c| c[0] as u32 == 0).map(|c| (c[1] as usize, c[2] as u32, D3D12_RESOURCE_STATES(c[3] as u32 as i32))).collect(); - super::title_textures::note_transitions(st.pc, &t); + super::list_x::note_texture_transitions(st.pc, &t); } list.ResourceBarrier(std::slice::from_raw_parts(b.as_ptr() as *const D3D12_RESOURCE_BARRIER, n)); } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index d4c4c78eb2..8f903830c6 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -750,6 +750,8 @@ struct ListState { sparse_writes: Vec<(usize, usize)>, /// Writes into title textures produced by this physical segment. texture_writes: Vec, + /// Ordered state transitions of tracked textures in this physical segment. + texture_transitions: Vec, /// Non-timestamp 64-bit `(va, value)` writes recorded by `Write64BitValue{Bottom,Top}OfPipeX` /// so `ExecuteCommandLists` / `KickoffX` can signal per-address GPU fences for cross-queue /// `Wait64BitValueX` without blocking the submitter thread on the CPU. @@ -867,10 +869,29 @@ impl ListState { } } +/// Record immutable tracked-texture transitions on the physical segment that contains them. +pub(super) fn note_texture_transitions(list: usize, transitions: &[(usize, u32, D3D12_RESOURCE_STATES)]) { + let captured = super::title_textures::capture_transitions(transitions); + if captured.is_empty() { + return; + } + if let Some(state) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { + state.texture_transitions.extend(captured); + } +} + +/// Discard transitions when a translated physical list is about to be recorded from the start. +pub(super) fn clear_texture_transitions(list: usize) { + if let Some(state) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { + state.texture_transitions.clear(); + } +} + struct KickoffEffects { waits: Vec, sparse_writes: Vec<(usize, usize)>, texture_writes: Vec, + texture_transitions: Vec, write64_signals: Vec<(u64, u64)>, cpu_writes: Vec, } @@ -880,6 +901,7 @@ fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { waits: std::mem::take(&mut state.pending_waits), sparse_writes: state.clear_sparse_writes(), texture_writes: std::mem::take(&mut state.texture_writes), + texture_transitions: std::mem::take(&mut state.texture_transitions), write64_signals: state.clear_write64_signals(), cpu_writes: std::mem::take(&mut state.cpu_writes), }; @@ -1006,6 +1028,7 @@ pub(super) struct SegmentEffects { write64_signals: Vec<(u64, u64)>, sparse_writes: Vec<(usize, usize)>, texture_writes: Vec, + texture_transitions: Vec, cpu_writes: Vec, } @@ -1041,6 +1064,7 @@ impl SubmissionPlan { write64_signals: s.write64_signals.clone(), sparse_writes: s.sparse_writes.clone(), texture_writes: s.texture_writes.clone(), + texture_transitions: s.texture_transitions.clone(), cpu_writes: s.cpu_writes.clone(), }) .unwrap_or_default() @@ -1238,7 +1262,6 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C old }; drop(old); - super::title_textures::list_reset(key); // 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 { @@ -1256,7 +1279,6 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C pub(super) fn on_release(list: usize) { super::alloc_pool::forget_list(list); release_copy_scratch(list); - super::title_textures::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { if !old.sparse_writes.is_empty() { @@ -1276,7 +1298,6 @@ pub(super) fn on_release(list: usize) { /// Clear per-recording sync/write tracking on a split segment moved into `title_list`'s spare pool. pub(super) fn clear_segment_state(list: usize) { - super::title_textures::list_reset(list); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { s.occlusion = Occlusion::default(); s.written_ranges.clear(); @@ -1285,6 +1306,7 @@ pub(super) fn clear_segment_state(list: usize) { s.clear_write64_signals(); s.clear_waits(); s.texture_writes.clear(); + s.texture_transitions.clear(); s.cpu_writes.clear(); s.predication = None; s.pred_in_state = false; @@ -2536,9 +2558,8 @@ pub(super) fn submission_plan(lists: &[*mut c_void]) -> SubmissionPlan { /// Publish the effects of an already-submitted chunk in the same order as the legacy consumers. unsafe fn submit_segment_effects(queue: *mut c_void, effects: &[SegmentEffects], needs_cpu_completion: bool) -> Option { let texture_writes: Vec<_> = effects.iter().flat_map(|e| e.texture_writes.iter().copied()).collect(); - if let Some(id) = queue_identity(queue as usize) { - super::title_textures::publish_gpu_writes(id, &texture_writes); - } + let texture_transitions: Vec<_> = effects.iter().flat_map(|e| e.texture_transitions.iter().copied()).collect(); + super::title_textures::publish_submission_effects(queue_identity(queue as usize), &texture_writes, &texture_transitions); let write64_signals: Vec<(u64, u64)> = effects.iter().flat_map(|e| e.write64_signals.iter().copied()).collect(); signal_write64_pairs(queue, &write64_signals); @@ -3430,7 +3451,6 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - old }; drop(old_next); - super::title_textures::list_reset(next_pc as usize); super::bind::install_prepared_split(next_bindings); restore_bindings(next_pc, bindings, ty); @@ -3944,10 +3964,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let effects = match preclose_effects { Some(effects) => effects, None => LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).map(take_kickoff_effects).unwrap_or(KickoffEffects { - waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), write64_signals: Vec::new(), cpu_writes: Vec::new(), + waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), write64_signals: Vec::new(), cpu_writes: Vec::new(), }), }; - let KickoffEffects { waits, sparse_writes, texture_writes, write64_signals, cpu_writes } = effects; + let KickoffEffects { waits, sparse_writes, texture_writes, texture_transitions, write64_signals, cpu_writes } = effects; if let Some(wrapper) = super::title_list::wrapper_of(this) { record_deferred(wrapper); } @@ -3969,18 +3989,21 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { wait_after_cpu_write = plan.cpu_producer_overlaps(&waits, plan.effects.len()); let mut submitted = Vec::with_capacity(prior.len()); let (completions, _) = execute_submission_plan_with_completions(q_raw, &plan, &waits, |chunk| { - let lists = chunk.lists(); - if !gate.submit(q_raw, lists, || {}, || exec(q_raw, lists.len() as u32, lists.as_ptr())) { - return (false, None); - } - submitted.extend_from_slice(lists); - copy_scratch_submitted(q_raw, lists); - (true, chunk.submit_effects(q_raw)) + super::queue_submit::with(q_raw as usize, || { + let lists = chunk.lists(); + if !gate.submit(q_raw, lists, || {}, || exec(q_raw, lists.len() as u32, lists.as_ptr())) { + return (false, None); + } + submitted.extend_from_slice(lists); + copy_scratch_submitted(q_raw, lists); + (true, chunk.submit_effects(q_raw)) + }) }); prior_cpu_completions = completions; - super::title_textures::submitted(&submitted); for &p in &submitted { - super::title_textures::list_reset(p as usize); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(p as usize))) { + s.texture_transitions.clear(); + } } } } @@ -3994,28 +4017,27 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } let one = [this]; - let current_submitted = gate.submit(q_raw, &one, || {}, || exec(q_raw, 1, one.as_ptr())); - if current_submitted { - copy_scratch_submitted(q_raw, &one); - if let Some(id) = queue_identity(q_raw as usize) { - super::title_textures::publish_gpu_writes(id, &texture_writes); - } - signal_write64_pairs(q_raw, &write64_signals); - // what ran is in the textures' states; the list records anew after its Reset below - super::title_textures::submitted(&one); - if !sparse_writes.is_empty() { - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { - super::sparse::readback_after_execute(q, &sparse_writes); + let current_submitted = super::queue_submit::with(q_raw as usize, || { + let submitted = gate.submit(q_raw, &one, || {}, || exec(q_raw, 1, one.as_ptr())); + if submitted { + copy_scratch_submitted(q_raw, &one); + super::title_textures::publish_submission_effects(queue_identity(q_raw as usize), &texture_writes, &texture_transitions); + signal_write64_pairs(q_raw, &write64_signals); + if !sparse_writes.is_empty() { + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { + super::sparse::readback_after_execute(q, &sparse_writes); + } } + super::cpu_writes::after(q_raw, cpu_writes); } - super::cpu_writes::after(q_raw, cpu_writes); - } else { + submitted + }); + if !current_submitted { if once(&ERR, 8) { crate::xlog_warn!("D3D12.X: KickoffX – could not reserve submission retirement state; resetting the unsubmitted recording"); } } // Submitted or discarded, `this` starts a new recording in the common Reset tail. - super::title_textures::list_reset(this as usize); let target = if let Some((primary, _, reclaimed)) = kickoff_split { let (ended_early, pred_buf_obj, bindings_copy) = { @@ -4751,13 +4773,13 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.clear_write64_signals(); s.clear_waits(); s.texture_writes.clear(); + s.texture_transitions.clear(); 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) }; - super::title_textures::list_reset(this as usize); super::bind::reset(this, alloc, pso); if !is_bundle && pso != 0 { if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) { @@ -4854,7 +4876,7 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 if super::title_textures::any() { let t: Vec<(usize, u32, D3D12_RESOURCE_STATES)> = out.iter().filter(|b| b[0] == 0).map(|b| ((b[2] as u64 | (b[3] as u64) << 32) as usize, b[4], D3D12_RESOURCE_STATES(b[6] as i32))).collect(); - super::title_textures::note_transitions(this as usize, &t); + note_texture_transitions(this as usize, &t); } if !out.is_empty() { pc::(this, PC_RESOURCE_BARRIER)(this, out.len() as u32, out.as_ptr()); @@ -5748,6 +5770,12 @@ mod tests { write64_signals: vec![(0x1000 + i as u64, 10 + i as u64)], sparse_writes: vec![(0x2000 + i, 4 + i)], texture_writes: vec![super::super::title_textures::GpuWrite { res: 0x2500 + i, generation: 20 + i as u64, subresource: i as u32 }], + texture_transitions: vec![super::super::title_textures::Transition { + res: 0x2600 + i, + generation: 30 + i as u64, + subresource: i as u32, + after: D3D12_RESOURCE_STATE_COPY_DEST, + }], cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x3000 + i, vec![i as u32])], ..Default::default() }, @@ -5769,6 +5797,7 @@ mod tests { assert_eq!(effects.write64_signals, vec![(0x1000 + i as u64, 10 + i as u64)]); assert_eq!(effects.sparse_writes, vec![(0x2000 + i, 4 + i)]); assert_eq!(effects.texture_writes, vec![super::super::title_textures::GpuWrite { res: 0x2500 + i, generation: 20 + i as u64, subresource: i as u32 }]); + assert_eq!(effects.texture_transitions.iter().map(|t| t.res).collect::>(), vec![0x2600 + i]); match effects.cpu_writes.as_slice() { [super::super::cpu_writes::Write::Immediate(va, words)] => assert_eq!((*va, words.as_slice()), (0x3000 + i, &[i as u32][..])), _ => panic!("unexpected CPU write snapshot"), @@ -5800,6 +5829,12 @@ mod tests { write64_signals: vec![(0x4000, 4)], sparse_writes: vec![(0x5000, 8)], texture_writes: vec![super::super::title_textures::GpuWrite { res: 0x5500, generation: 4, subresource: 2 }], + texture_transitions: vec![super::super::title_textures::Transition { + res: 0x5600, + generation: 4, + subresource: 2, + after: D3D12_RESOURCE_STATE_COPY_SOURCE, + }], cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x6000, vec![4])], ..Default::default() }; @@ -5816,6 +5851,12 @@ mod tests { state.write64_signals = vec![(0x4000, 9)]; state.sparse_writes = vec![(0x7000, 16)]; state.texture_writes = vec![super::super::title_textures::GpuWrite { res: 0x7500, generation: 9, subresource: 3 }]; + state.texture_transitions = vec![super::super::title_textures::Transition { + res: 0x7600, + generation: 9, + subresource: 3, + after: D3D12_RESOURCE_STATE_RENDER_TARGET, + }]; state.cpu_writes = vec![super::super::cpu_writes::Write::Immediate(0x8000, vec![9])]; state.written_ranges.clear(); state.segment_write_producers.clear(); @@ -5827,6 +5868,12 @@ mod tests { assert_eq!(effects.write64_signals, vec![(0x4000, 4)]); assert_eq!(effects.sparse_writes, vec![(0x5000, 8)]); assert_eq!(effects.texture_writes, vec![super::super::title_textures::GpuWrite { res: 0x5500, generation: 4, subresource: 2 }]); + assert_eq!(effects.texture_transitions, vec![super::super::title_textures::Transition { + res: 0x5600, + generation: 4, + subresource: 2, + after: D3D12_RESOURCE_STATE_COPY_SOURCE, + }]); assert!(effects.producer_overlaps(WriteProducer::InSegmentGpu, 0x4100, 8)); assert!(effects.producer_overlaps(WriteProducer::CpuAfterSegment, 0x4200, 8)); assert!(!effects.producer_overlaps(WriteProducer::CpuAfterSegment, 0x4300, 8)); @@ -5904,6 +5951,12 @@ mod tests { let m = g.get_or_insert_with(HashMap::new); let mut first = ListState::default(); first.note_write(WriteProducer::CpuAfterSegment, va, 8); + first.texture_transitions.push(super::super::title_textures::Transition { + res: 0x8100, + generation: 1, + subresource: 0, + after: D3D12_RESOURCE_STATE_COPY_SOURCE, + }); m.insert(producer as usize, first); m.insert( continuation as usize, @@ -5916,6 +5969,12 @@ mod tests { mask: u64::MAX, after_write64: false, }], + texture_transitions: vec![super::super::title_textures::Transition { + res: 0x8200, + generation: 1, + subresource: 0, + after: D3D12_RESOURCE_STATE_COPY_DEST, + }], ..Default::default() }, ); @@ -5943,10 +6002,12 @@ mod tests { let completed = Arc::new(AtomicBool::new(false)); let mut chunks = Vec::new(); + let mut transition_chunks = Vec::new(); unsafe { let leftovers = execute_submission_plan_with_completions(std::ptr::null_mut(), &plan, &[], |chunk| { let lists = chunk.lists().to_vec(); chunks.push(lists.clone()); + transition_chunks.push(chunk.effects.iter().flat_map(|e| &e.texture_transitions).map(|t| t.res).collect::>()); if lists == vec![producer] { assert!(chunk.needs_cpu_completion()); let (receipt, done) = super::super::cpu_writes::completion_pair_for_test(); @@ -5966,6 +6027,7 @@ mod tests { assert!(leftovers.is_empty()); } assert_eq!(chunks, vec![vec![producer], vec![continuation]]); + assert_eq!(transition_chunks, vec![vec![0x8100], vec![0x8200]], "wait splitting keeps transition effects with their physical segment"); let mut callbacks = 0; let completed_all = unsafe { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 96870e0f30..f3af596c36 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8104,11 +8104,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis chunks += 1; submitted.extend_from_slice(lists); super::list_x::copy_scratch_submitted(this, lists); - let completion = chunk.submit_effects(this); - // State and last-writer publication belong to the same queue turn as execution; - // a following Signal must not observe only half of this submission. - super::title_textures::submitted(lists); - (true, completion) + (true, chunk.submit_effects(this)) }) }); super::alloc_pool::note_execute_call(chunks); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 697ef0de08..43e8956d8f 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -16,9 +16,8 @@ //! address) are not seen; the title's own GPU work on the texture goes to the PC texture. //! //! A copy starts and ends in the state the title's submitted work left the texture in: its -//! transitions of these textures are noted per PC command list as they are recorded -//! (`note_transitions`) and applied, in submission order, when the list is submitted -//! (`submitted`) – per subresource once a transition names one. +//! transitions of these textures are captured in each physical command-list segment's immutable +//! submission effects and applied in submission order – per subresource once one is named. use std::collections::BTreeMap; use std::ffi::c_void; @@ -616,27 +615,46 @@ pub(super) fn capture_gpu_write(res: usize, subresource: u32) -> Option, writes: &[GpuWrite], transitions: &[Transition]) { + if writes.is_empty() && transitions.is_empty() { return; } let mut newly_written = Vec::new(); { let mut t = TEXTURES.lock().unwrap(); - for &write in writes { - let Some(e) = t.get_mut(write.res).filter(|e| e.generation == write.generation) else { continue }; + if let Some(queue) = queue { + for &write in writes { + let Some(e) = t.get_mut(write.res).filter(|e| e.generation == write.generation) else { continue }; + let n = subresource_count(&e.tex); + if write.subresource != D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES && !(n <= 1 && write.subresource == 0) && write.subresource as usize >= n { + continue; + } + let epoch = NEXT_GPU_EPOCH.fetch_add(1, Ordering::Relaxed) + 1; + let writer = GpuWriter { epoch, queue }; + apply_gpu_writer(&mut e.gpu_writers, n, write.subresource, writer); + if !e.gpu_written { + e.gpu_written = true; + GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); + newly_written.push(write.res); + } + } + } + for &transition in transitions { + let Some(e) = t.get_mut(transition.res).filter(|e| e.generation == transition.generation) else { continue }; let n = subresource_count(&e.tex); - if write.subresource != D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES && !(n <= 1 && write.subresource == 0) && write.subresource as usize >= n { + if transition.subresource != D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES + && !(n <= 1 && transition.subresource == 0) + && transition.subresource as usize >= n + { continue; } - let epoch = NEXT_GPU_EPOCH.fetch_add(1, Ordering::Relaxed) + 1; - let writer = GpuWriter { epoch, queue }; - apply_gpu_writer(&mut e.gpu_writers, n, write.subresource, writer); - if !e.gpu_written { - e.gpu_written = true; - GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); - newly_written.push(write.res); - } + apply_transition(&mut e.states, n, transition.subresource, transition.after); } } if !newly_written.is_empty() { @@ -725,62 +743,34 @@ pub fn address(res: usize) -> Option { t.by_res.get(&res).or_else(|| t.shadowed.get(&res)).map(|e| e.va) } -/// (texture, subresource or ALL_SUBRESOURCES, state after) of a transition the title recorded -type Transition = (usize, u32, D3D12_RESOURCE_STATES); - -/// PC command list → the transitions of textures kept in step it recorded since it was made or -/// last reset, in order. They apply when the list is submitted – each time: a closed list may -/// run again. -static LIST_NOTES: Mutex>> = Mutex::new(BTreeMap::new()); +/// A recorded transition of a tracked texture. The registration generation keeps a captured +/// command-list effect from applying to a new resource at a reused COM address. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Transition { + pub(super) res: usize, + pub(super) generation: u64, + pub(super) subresource: u32, + pub(super) after: D3D12_RESOURCE_STATES, +} /// Whether any texture is kept in step (callers skip collecting transitions otherwise). pub fn any() -> bool { TEXTURES_LEN.load(Ordering::Relaxed) != 0 } -/// The title recorded `transitions` on PC list `list`: those of textures kept in step are noted -/// for when the list is submitted. -pub fn note_transitions(list: usize, transitions: &[Transition]) { +/// Capture the transitions of textures currently kept in step while a physical segment records. +pub(super) fn capture_transitions(transitions: &[(usize, u32, D3D12_RESOURCE_STATES)]) -> Vec { if !any() || transitions.is_empty() { - return; - } - let kept: Vec = { - let t = TEXTURES.lock().unwrap(); - transitions.iter().filter(|(r, _, _)| t.by_res.contains_key(r) || t.shadowed.contains_key(r)).copied().collect() - }; - if !kept.is_empty() { - LIST_NOTES.lock().unwrap().entry(list).or_default().extend(kept); - } -} - -/// PC list `list` starts a new recording (made, reset, released): its noted transitions go. -pub fn list_reset(list: usize) { - let mut g = LIST_NOTES.lock().unwrap(); - if !g.is_empty() { - g.remove(&list); - } -} - -/// The PC lists `lists` were submitted, in this order: the textures kept in step are in the -/// states their transitions leave them in. -pub fn submitted(lists: &[*mut c_void]) { - let notes: Vec = { - let g = LIST_NOTES.lock().unwrap(); - if g.is_empty() { - return; - } - lists.iter().filter_map(|&l| g.get(&(l as usize))).flatten().copied().collect() - }; - if notes.is_empty() { - return; - } - let mut t = TEXTURES.lock().unwrap(); - for (res, sub, after) in notes { - if let Some(e) = t.get_mut(res) { - let n = subresource_count(&e.tex); - apply_transition(&mut e.states, n, sub, after); - } + return Vec::new(); } + let t = TEXTURES.lock().unwrap(); + transitions + .iter() + .filter_map(|&(res, subresource, after)| { + let e = t.by_res.get(&res).or_else(|| t.shadowed.get(&res))?; + Some(Transition { res, generation: e.generation, subresource, after }) + }) + .collect() } /// Subresources of a texture kept in step (as `subresources` makes them). @@ -2746,37 +2736,31 @@ mod tests { let tex = Arc::new(xg::Texture::new(&d).unwrap()); assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it - let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); + let (res, other) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize); TEXTURES.lock().unwrap().insert(res, Entry { device: 0, committed_bytes: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().by_res.get(&res).unwrap().states.clone(); - let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); - - note_transitions(l1, &[(res, ALL, SRV), (other, ALL, D3D12_RESOURCE_STATE_RENDER_TARGET), (res, 4, D3D12_RESOURCE_STATE_COPY_SOURCE)]); - assert_eq!(LIST_NOTES.lock().unwrap().get(&l1).map(|v| v.len()), Some(2), "only the texture kept in step is noted"); + let e1 = capture_transitions(&[(res, ALL, SRV), (other, ALL, D3D12_RESOURCE_STATE_RENDER_TARGET), (res, 4, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + assert_eq!(e1.len(), 2, "only the texture kept in step is captured"); assert_eq!(states(), vec![D3D12_RESOURCE_STATE_COMMON], "recorded, not run yet"); - note_transitions(l2, &[(res, 4, SRV), (res, 0, D3D12_RESOURCE_STATE_COPY_DEST)]); - submitted(&[p1]); + let e2 = capture_transitions(&[(res, 4, SRV), (res, 0, D3D12_RESOURCE_STATE_COPY_DEST)]); + publish_submission_effects(None, &[], &e1); let mut want = vec![SRV; 6]; want[4] = D3D12_RESOURCE_STATE_COPY_SOURCE; assert_eq!(states(), want); - submitted(&[p2]); + publish_submission_effects(None, &[], &e2); want[4] = SRV; want[0] = D3D12_RESOURCE_STATE_COPY_DEST; assert_eq!(states(), want); // l1 runs again (a closed list may): its transitions again, after l2's - submitted(&[p2, p1]); + publish_submission_effects(None, &[], &e2); + publish_submission_effects(None, &[], &e1); assert_eq!(states(), { let mut w = vec![SRV; 6]; w[4] = D3D12_RESOURCE_STATE_COPY_SOURCE; w }); - list_reset(l1); - list_reset(l2); - submitted(&[p1, p2]); - assert_eq!(states()[4], D3D12_RESOURCE_STATE_COPY_SOURCE, "a reset list has nothing to apply"); forget(res); - assert!(LIST_NOTES.lock().unwrap().get(&l1).is_none()); } /// The title's bytes are used where they are when all of them are readable, and read with the From e0038f6c60e3d080971f5806e1ac2c59fc335632 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:21:15 -0800 Subject: [PATCH 108/265] XAudio2: remove locks and copies from source submission Mirror patched vtable originals in a fixed atomic fast table, bypass silent and decoded voice maps when they are empty, and submit decoder-owned PCM16 storage without allocating a second byte buffer. Make shared silence allocation retryable and keep decoded-error fallback storage bounded when it is unavailable.\n\nAssisted-by: Google Antigravity (Gemini 4 Neon)\nAssisted-by: Codex (GPT-5.6-sol)\nCo-authored-by: Decodere <98278826+Decodere@users.noreply.github.com> --- crates/xcl/src/hle/xaudio2.rs | 246 +++++++++++++++++++++++++++++----- 1 file changed, 214 insertions(+), 32 deletions(-) diff --git a/crates/xcl/src/hle/xaudio2.rs b/crates/xcl/src/hle/xaudio2.rs index fae020df15..6474efde5e 100644 --- a/crates/xcl/src/hle/xaudio2.rs +++ b/crates/xcl/src/hle/xaudio2.rs @@ -505,11 +505,56 @@ pub fn silent_buffer(i: &XmaInfo, b: &XAudio2Buffer, silence: *const u8, max_byt // Decoded voice state (Opus & XMA1/XMA2) & IXAudio2VoiceCallback wrapper // --------------------------------------------------------------------------------------- +const _: () = assert!(cfg!(target_endian = "little")); + /// Owned decoded PCM16 buffer kept alive at a stable heap address until `OnBufferEnd` -/// or `DestroyVoice`. +/// or `DestroyVoice`. Empty when backed by the shared read-only `silence()` mapping. struct DecodedBuffer { orig_context: usize, - _pcm: Box<[u8]>, + _pcm: Vec, +} + +/// Prepare decoded little-endian PCM16 samples for zero-copy XAudio2 submission. +/// Returns `None` when fewer than one complete frame was decoded so the caller falls back +/// to shared silence. +fn prepare_decoded_pcm(mut samples: Vec, channels: u16, orig_buf: &XAudio2Buffer) -> Option<(XAudio2Buffer, Vec)> { + let ch = channels.max(1) as usize; + let max_frames = (XAUDIO2_MAX_BUFFER_BYTES as usize) / (ch * 2); + let total_frames = (samples.len() / ch).min(max_frames); + if total_frames == 0 { + return None; + } + samples.truncate(total_frames * ch); + let mut nb = *orig_buf; + clamp_regions(&mut nb, total_frames as u32); + nb.audio_bytes = (samples.len() * 2) as u32; + Some((nb, samples)) +} + +const OWNED_SILENCE_BYTES: usize = 64 * 1024; + +fn prepare_fallback_silence( + info: &XmaInfo, + orig_buf: &XAudio2Buffer, + shared: *const u8, +) -> Option<(XAudio2Buffer, Vec)> { + if !shared.is_null() { + return Some((silent_buffer(info, orig_buf, shared, SILENCE_BYTES), Vec::new())); + } + + // Keep decoding failures recoverable when the large shared mapping cannot be allocated. + // This is deliberately bounded: a missing 32 MiB mapping must not turn one submission into + // a comparably large per-buffer allocation. + let mut nb = silent_buffer(info, orig_buf, std::ptr::null(), OWNED_SILENCE_BYTES); + let samples = nb.audio_bytes as usize / std::mem::size_of::(); + if samples == 0 { + return None; + } + let mut pcm = Vec::new(); + pcm.try_reserve_exact(samples).ok()?; + pcm.resize(samples, 0); + nb.audio_data = pcm.as_ptr() as *const u8; + Some((nb, pcm)) } enum VoiceDecoder { @@ -664,10 +709,50 @@ static DECODED_CALLBACK_VTBL: VoiceCallbackVtbl = VoiceCallbackVtbl { // the system engine and in-place vtable patches // --------------------------------------------------------------------------------------- +const FAST_ORIG_CAP: usize = 32; + +struct FastOriginals { + len: AtomicUsize, + entries: [(AtomicUsize, AtomicUsize, AtomicUsize); FAST_ORIG_CAP], +} + +impl FastOriginals { + const fn new() -> Self { + Self { + len: AtomicUsize::new(0), + entries: [const { (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)) }; FAST_ORIG_CAP], + } + } + + fn push(&self, idx: usize, vt: usize, slot: usize, orig: usize) { + if idx < FAST_ORIG_CAP { + let (ev, es, ef) = &self.entries[idx]; + ev.store(vt, Ordering::Relaxed); + es.store(slot, Ordering::Relaxed); + ef.store(orig, Ordering::Relaxed); + self.len.store(idx + 1, Ordering::Release); + } + } + + fn lookup(&self, vt: usize, slot: usize) -> Result, ()> { + let n = self.len.load(Ordering::Acquire); + for (ev, es, ef) in &self.entries[..n] { + if ev.load(Ordering::Relaxed) == vt && es.load(Ordering::Relaxed) == slot { + return Ok(Some(ef.load(Ordering::Relaxed))); + } + } + if n < FAST_ORIG_CAP { Ok(None) } else { Err(()) } + } +} + /// Originals of patched slots: (vtable address, slot) → function. static ORIGINALS: Mutex> = Mutex::new(Vec::new()); +/// Lock-free mirror of the first `FAST_ORIG_CAP` entries of `ORIGINALS`. +static FAST_ORIGINALS: FastOriginals = FastOriginals::new(); /// Live silent voices (voice pointer → info). static XMA: Mutex>> = Mutex::new(None); +/// Count of live silent voices (fast path for plain PCM and decoded voices). +static SILENT_LIVE_COUNT: AtomicUsize = AtomicUsize::new(0); /// Live decoded voices (Opus & XMA1/XMA2: voice pointer → handle). static DECODED_VOICES: Mutex>> = Mutex::new(None); /// Count of live decoded voices (fast path for plain PCM voices). @@ -695,7 +780,9 @@ unsafe fn patch(obj: *mut c_void, slot: usize, hook: usize) { crate::xlog_error!("XAudio2: cannot make vtable {vt:p} writable (slot {slot})"); return; } + let idx = g.len(); g.push((vt as usize, slot, cur)); + FAST_ORIGINALS.push(idx, vt as usize, slot, cur); p.write(hook); VirtualProtect(p as *const c_void, 8, old, &mut old); } @@ -703,7 +790,19 @@ unsafe fn patch(obj: *mut c_void, slot: usize, hook: usize) { /// The original implementation of `slot` for `obj`'s class. unsafe fn original(obj: *mut c_void, slot: usize) -> Option { let vt = vtable(obj) as usize; - ORIGINALS.lock().unwrap().iter().find(|&&(v, s, _)| v == vt && s == slot).map(|&(_, _, f)| f) + lookup_original(&FAST_ORIGINALS, &ORIGINALS, vt, slot) +} + +fn lookup_original( + fast: &FastOriginals, + slow: &Mutex>, + vt: usize, + slot: usize, +) -> Option { + match fast.lookup(vt, slot) { + Ok(hit) => hit, + Err(()) => slow.lock().unwrap().iter().find(|&&(v, s, _)| v == vt && s == slot).map(|&(_, _, f)| f), + } } fn system_create() -> Option<(Option, Option)> { @@ -931,7 +1030,12 @@ unsafe extern "system" fn create_source_voice( patch_source_voice(voice); SOURCE_VOICES.fetch_add(1, Ordering::Relaxed); if let Some(i) = silent { - XMA.lock().unwrap().get_or_insert_with(HashMap::new).insert(voice as usize, i); + { + let mut g = XMA.lock().unwrap(); + if g.get_or_insert_with(HashMap::new).insert(voice as usize, i).is_none() { + SILENT_LIVE_COUNT.fetch_add(1, Ordering::Release); + } + } SILENT_VOICES.fetch_add(1, Ordering::Relaxed); if is_xma(tag) && XMA_VOICES.fetch_add(1, Ordering::Relaxed) == 0 { crate::xlog_warn!( @@ -997,9 +1101,23 @@ unsafe extern "system" fn create_mastering_voice( } fn silence() -> *const u8 { - use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READONLY}; - static P: OnceLock = OnceLock::new(); - *P.get_or_init(|| unsafe { VirtualAlloc(std::ptr::null(), SILENCE_BYTES, MEM_COMMIT | MEM_RESERVE, PAGE_READONLY) as usize }) as *const u8 + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READONLY}; + static P: AtomicUsize = AtomicUsize::new(0); + let cached = P.load(Ordering::Acquire); + if cached != 0 { + return cached as *const u8; + } + let allocated = unsafe { VirtualAlloc(std::ptr::null(), SILENCE_BYTES, MEM_COMMIT | MEM_RESERVE, PAGE_READONLY) as usize }; + if allocated == 0 { + return std::ptr::null(); + } + match P.compare_exchange(0, allocated, Ordering::Release, Ordering::Acquire) { + Ok(_) => allocated as *const u8, + Err(winner) => { + unsafe { VirtualFree(allocated as *mut c_void, 0, MEM_RELEASE) }; + winner as *const u8 + } + } } unsafe fn submit_decoded_buffer( @@ -1040,47 +1158,48 @@ unsafe fn submit_decoded_buffer( } }; - let mut nb = orig_buf; - let pcm_bytes: Box<[u8]> = match decoded_pcm { - Ok(samples) if !samples.is_empty() => { - let total_frames = (samples.len() / state.channels.max(1) as usize) as u32; - clamp_regions(&mut nb, total_frames); - let mut bytes = Vec::with_capacity(samples.len() * 2); - for s in samples { - bytes.extend_from_slice(&s.to_le_bytes()); - } + let prepared = match decoded_pcm { + Ok(samples) => match prepare_decoded_pcm(samples, state.channels, &orig_buf) { + Some(p) => Ok(p), + None => Err(None), + }, + Err(e) => Err(Some(e)), + }; + let (mut nb, pcm) = match prepared { + Ok(p) => { if is_xma_voice { XMA_BUFFERS_DECODED.fetch_add(1, Ordering::Relaxed); } else { OPUS_BUFFERS_DECODED.fetch_add(1, Ordering::Relaxed); } - bytes.into_boxed_slice() + p } - res => { + Err(err) => { let err_counter = if is_xma_voice { &XMA_DECODE_ERRORS } else { &OPUS_DECODE_ERRORS }; let codec_name = if is_xma_voice { "XMA" } else { "Opus" }; let prev = err_counter.fetch_add(1, Ordering::Relaxed); if prev == 0 { - match res { - Err(e) => crate::xlog_warn!("XAudio2: {codec_name} decode error ({e}) – substituting silence"), - Ok(_) => crate::xlog_warn!("XAudio2: {codec_name} buffer decoded 0 samples – substituting silence"), + match err { + Some(e) => crate::xlog_warn!("XAudio2: {codec_name} decode error ({e}) – substituting silence"), + None => crate::xlog_warn!("XAudio2: {codec_name} buffer decoded 0 complete frames – substituting silence"), } } - let sb = silent_buffer(&fallback_info, &orig_buf, std::ptr::null(), SILENCE_BYTES); - nb = sb; + let Some(fallback) = prepare_fallback_silence(&fallback_info, &orig_buf, silence()) else { + return E_FAIL; + }; SILENCED.fetch_add(1, Ordering::Relaxed); - vec![0u8; sb.audio_bytes as usize].into_boxed_slice() + fallback } }; - let pcm_ptr = pcm_bytes.as_ptr(); - let pcm_len = pcm_bytes.len() as u32; - let boxed = Box::new(DecodedBuffer { orig_context: orig_buf.context as usize, _pcm: pcm_bytes }); + let boxed = Box::new(DecodedBuffer { orig_context: orig_buf.context as usize, _pcm: pcm }); + if !boxed._pcm.is_empty() { + nb.audio_data = boxed._pcm.as_ptr() as *const u8; + nb.audio_bytes = (boxed._pcm.len() * 2) as u32; + } let token = &*boxed as *const DecodedBuffer as usize; state.live_buffers.lock().unwrap().insert(token, boxed); - nb.audio_data = pcm_ptr; - nb.audio_bytes = pcm_len; nb.context = token as *mut c_void; let hr = orig(this, &nb, std::ptr::null()); @@ -1103,7 +1222,11 @@ unsafe extern "system" fn submit_source_buffer(this: *mut c_void, buf: *const XA return submit_decoded_buffer(this, orig, &state, buf.read_unaligned()); } } - let info = XMA.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied()); + let info = if SILENT_LIVE_COUNT.load(Ordering::Acquire) != 0 { + XMA.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied()) + } else { + None + }; match info { Some(i) if !buf.is_null() => { let s = silence(); @@ -1159,8 +1282,11 @@ unsafe extern "system" fn get_state(this: *mut c_void, state_out: *mut XAudio2Vo unsafe extern "system" fn destroy_voice(this: *mut c_void) { let Some(orig) = original(this, VOICE_DESTROY) else { return }; let orig: DestroyVoiceFn = std::mem::transmute(orig); - if let Some(m) = XMA.lock().unwrap().as_mut() { - m.remove(&(this as usize)); + if SILENT_LIVE_COUNT.load(Ordering::Acquire) != 0 { + let mut g = XMA.lock().unwrap(); + if g.as_mut().and_then(|m| m.remove(&(this as usize))).is_some() { + SILENT_LIVE_COUNT.fetch_sub(1, Ordering::Release); + } } let decoded_handle = if DECODED_LIVE_COUNT.load(Ordering::Acquire) != 0 { DECODED_VOICES.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))) @@ -1786,4 +1912,60 @@ mod tests { assert_eq!(flush(guard.voice), S_OK); } } + + #[test] + fn prepare_decoded_pcm_is_zero_copy_and_whole_frame_clamped() { + let orig = buffer(16, 0, 10, 0, 0, 0); + // Empty and < 1 full frame return None so caller falls back to shared silence. + assert!(prepare_decoded_pcm(Vec::new(), 2, &orig).is_none()); + assert!(prepare_decoded_pcm(vec![0x1234i16], 2, &orig).is_none()); + + // 5 samples for 2 channels -> 2 complete frames (4 samples, 8 bytes), zero copy. + let samples = vec![0x1234i16, -1i16, 0x0055i16, 0x7FFFi16, 0x1111i16]; + let orig_ptr = samples.as_ptr(); + let (nb, out) = prepare_decoded_pcm(samples, 2, &orig).expect("2 whole frames"); + assert_eq!(out.as_ptr(), orig_ptr, "PCM Vec must not reallocate or copy"); + assert_eq!((out.len(), { nb.audio_bytes }, { nb.play_length }), (4, 8, 2)); + let bytes = unsafe { std::slice::from_raw_parts(out.as_ptr() as *const u8, out.len() * 2) }; + assert_eq!(&bytes[..4], &[0x34, 0x12, 0xFF, 0xFF]); + } + + #[test] + fn fast_originals_serves_entries_lock_free_and_respects_overflow() { + let fast = FastOriginals::new(); + let slow = Mutex::new(Vec::new()); + assert_eq!(fast.lookup(0x1000, 1), Ok(None)); + for i in 0..FAST_ORIG_CAP { + let entry = (0x1000 + i * 8, i % 4, 0x9000 + i); + slow.lock().unwrap().push(entry); + fast.push(i, entry.0, entry.1, entry.2); + } + assert_eq!(fast.lookup(0x1000, 0), Ok(Some(0x9000))); + assert_eq!(fast.lookup(0x1000 + (FAST_ORIG_CAP - 1) * 8, (FAST_ORIG_CAP - 1) % 4), Ok(Some(0x9000 + FAST_ORIG_CAP - 1))); + assert_eq!(fast.lookup(0xDEAD, 0), Err(())); + + // The 33rd entry cannot be mirrored. Exercise the exact production helper and + // verify it consults the isolated slow registry only after fast-table saturation. + let overflow = (0xDEAD, 7, 0xBEEF); + slow.lock().unwrap().push(overflow); + assert_eq!(lookup_original(&fast, &slow, overflow.0, overflow.1), Some(overflow.2)); + assert_eq!(lookup_original(&fast, &slow, 0xBAD, 7), None); + } + + #[test] + fn decode_fallback_uses_shared_or_bounded_owned_silence() { + let info = XmaInfo { channels: 2, rate: 48_000, samples_encoded: 48_000, bytes_per_block: 0x1000, block_count: 1, ..Default::default() }; + let orig = buffer(0x1000, 0, 480, 0, 0, 0); + let shared = 0x4000 as *const u8; + let (nb, pcm) = prepare_fallback_silence(&info, &orig, shared).expect("shared silence"); + assert!(pcm.is_empty() && pcm.capacity() == 0); + assert_eq!(({ nb.audio_data }, { nb.audio_bytes }), (shared, 480 * 4)); + + let huge = buffer(0x1000, 0, u32::MAX, 0, 0, 0); + let (nb, pcm) = prepare_fallback_silence(&info, &huge, std::ptr::null()).expect("owned silence"); + assert_eq!(nb.audio_bytes as usize, OWNED_SILENCE_BYTES); + assert_eq!(pcm.len() * std::mem::size_of::(), OWNED_SILENCE_BYTES); + assert_eq!({ nb.audio_data }, pcm.as_ptr() as *const u8); + assert!(pcm.iter().all(|&sample| sample == 0)); + } } From 9fdfe6c99526e0caad17b6de74e20c432cd2188d Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:23:06 -0800 Subject: [PATCH 109/265] DirectStorage: precompute BCPack bit packing Replace per-block bit-spread, residual-mask, and anchor scans with compile-time lookup tables and fixed masks while preserving every existing BCPack output. Add exhaustive helper equivalence checks and baseline hashes for the shipped fixtures and all BC6H/BC7 modes.\n\nAssisted-by: Google Antigravity (Gemini 4 Neon)\nAssisted-by: Codex (GPT-5.6-sol)\nCo-authored-by: Decodere <98278826+Decodere@users.noreply.github.com> --- crates/xcl/src/hle/bcpack/victory.rs | 375 ++++++++++++++++++++++----- 1 file changed, 316 insertions(+), 59 deletions(-) diff --git a/crates/xcl/src/hle/bcpack/victory.rs b/crates/xcl/src/hle/bcpack/victory.rs index 20b8fa5129..9886e914d9 100644 --- a/crates/xcl/src/hle/bcpack/victory.rs +++ b/crates/xcl/src/hle/bcpack/victory.rs @@ -331,10 +331,39 @@ fn references(s: &[u8], paired: bool) -> (usize, usize) { (usize::from(ix.wrapping_add(delta)), usize::from(ix)) } +/// Spreads a 4-bit symbol onto even bit positions `0, 2, 4, 6`. +const SPREAD4: [u8; 16] = [ + 0x00, 0x01, 0x04, 0x05, 0x10, 0x11, 0x14, 0x15, + 0x40, 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55, +]; + +/// Spreads an 8-bit symbol onto even bit positions `0, 2, ..., 14`. +const SPREAD8: [u16; 256] = { + let mut t = [0u16; 256]; + let mut v = 0usize; + while v < 256 { + let mut out = 0u16; + let mut k = 0; + while k < 8 { + out |= (((v >> k) & 1) as u16) << (2 * k); + k += 1; + } + t[v] = out; + v += 1; + } + t +}; + /// Two 4-bit symbols, the first on the even bits. +#[inline(always)] fn interleave(a: u8, b: u8) -> u8 { - let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k)); - spread(a) | spread(b) << 1 + SPREAD4[usize::from(a & 15)] | (SPREAD4[usize::from(b & 15)] << 1) +} + +/// Two 8-bit symbols, the first on the even bits. +#[inline(always)] +fn wide_interleave(a: u8, b: u8) -> u16 { + SPREAD8[usize::from(a)] | (SPREAD8[usize::from(b)] << 1) } /// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first @@ -348,26 +377,40 @@ fn pick<'a, T>(i: usize, r: usize, history: &'a [T], dictionary: &'a [T], zero: } /// Zigzag residual (0, -1, 1, -2, ...) modulo 2^bits. +#[inline(always)] fn zz(v: u8, bits: u32) -> u8 { let mask = ((1u32 << bits) - 1) as u8; ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask } -/// Element widths of the plain formats' endpoints and indices. +/// Element masks and active counts of the plain formats' endpoints and indices. struct Widths { - ep: [u8; 8], - ix: [u8; 32], + ep_mask: [u8; 8], + ep_len: usize, + ix_mask: [u8; 32], + ix_len: usize, paired: bool, } const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths { - let mut ix = [0; 32]; + let mut ep_mask = [0u8; 8]; + let mut ep_len = 0; let mut k = 0; - while k < ix3 + ix2 { - ix[k] = if k < ix3 { 3 } else { 2 }; + while k < 8 { + if ep[k] != 0 { + ep_mask[k] = ((1u16 << ep[k]) - 1) as u8; + ep_len = k + 1; + } k += 1; } - Widths { ep, ix, paired } + let mut ix_mask = [0u8; 32]; + let ix_len = ix3 + ix2; + let mut k = 0; + while k < ix_len { + ix_mask[k] = if k < ix3 { 7 } else { 3 }; + k += 1; + } + Widths { ep_mask, ep_len, ix_mask, ix_len, paired } } const BC1: Widths = widths([5, 6, 5, 5, 6, 5, 0, 0], 0, 16, false); @@ -390,11 +433,17 @@ fn plain<'a>( let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; let mut v = residual(s); - for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { - *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; + for ((v, &r), &mask) in v.ep[..w.ep_len].iter_mut().zip(ep_ref).zip(&w.ep_mask) { + *v = v.wrapping_add(r) & mask; } - for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { - *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); + if w.ix_len == 16 { + for ((v, &r), &mask) in v.ix[..16].iter_mut().zip(&ix_ref[..16]).zip(&w.ix_mask[..16]) { + *v = v.wrapping_add(r) & mask; + } + } else { + for ((v, &r), &mask) in v.ix[..w.ix_len].iter_mut().zip(ix_ref).zip(&w.ix_mask) { + *v = v.wrapping_add(r) & mask; + } } history[i % HISTORY] = v; pack(&v, block); @@ -403,22 +452,26 @@ fn plain<'a>( } /// 2-bit index residuals: one symbol per 2x2 quad. -fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) { +#[inline(always)] +fn quads(rank: &[u8; 256], s: &[u8; 4], ix: &mut [u8; 16]) { for (q, &sym) in s.iter().enumerate() { let v = rank[usize::from(sym)]; let base = (q >> 1) * 8 + (q & 1) * 2; - for (k, p) in [0, 1, 4, 5].into_iter().enumerate() { - ix[base + p] = v >> (2 * k) & 3; - } + ix[base] = v & 3; + ix[base + 1] = (v >> 2) & 3; + ix[base + 4] = (v >> 4) & 3; + ix[base + 5] = (v >> 6) & 3; } } /// 3-bit index residuals: one symbol per two pixels in raster order. +#[inline(always)] fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { - for (k, &sym) in s.iter().enumerate() { + let (chunks, _) = ix.as_chunks_mut::<2>(); + for (&sym, dst) in s.iter().zip(chunks) { let v = rank[usize::from(sym & 63)]; - ix[2 * k] = v & 7; - ix[2 * k + 1] = v >> 4 & 7; + dst[0] = v & 7; + dst[1] = (v >> 4) & 7; } } @@ -427,7 +480,7 @@ fn bc1_residual(t: &Tables, s: &[u8]) -> Plain { for (k, bits) in [5, 6, 5, 5, 6, 5].into_iter().enumerate() { v.ep[k] = zz(s[2 + k], bits); } - quads(&t.rank1, &s[8..12], &mut v.ix); + quads(t.rank1, s[8..12].try_into().unwrap(), (&mut v.ix[..16]).try_into().unwrap()); v } @@ -447,7 +500,7 @@ fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { ..Default::default() }; pairs(&t.rank3a, &s[6..14], &mut v.ix[..16]); - quads(&t.rank3c, &s[20..24], &mut v.ix[16..]); + quads(t.rank3c, s[20..24].try_into().unwrap(), (&mut v.ix[16..]).try_into().unwrap()); v } @@ -471,54 +524,88 @@ fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { const BC1_CODE: [u32; 4] = [0, 2, 3, 1]; const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1]; -fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { +#[inline(always)] +fn bc1_color(ep: &[u8; 6], ix: &[u8; 16], out: &mut [u8; 8]) { let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]); let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]); - let bits = (0..16).fold(0, |acc, p| { - acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p) - }); - out[..2].copy_from_slice(&c0.to_le_bytes()); - out[2..4].copy_from_slice(&c1.to_le_bytes()); - out[4..8].copy_from_slice(&bits.to_le_bytes()); + let mut bits = 0u32; + for (p, &val) in ix.iter().enumerate() { + bits |= BC1_CODE[usize::from(val & 3)] << (2 * p); + } + let word = u64::from(c0) | (u64::from(c1) << 16) | (u64::from(bits) << 32); + *out = word.to_le_bytes(); } /// BC4 half: endpoints are kept 128 below their stored value. -fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) { - let bits = (0..16).fold(0u64, |acc, p| { - acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p) - }); +#[inline(always)] +fn bc4_alpha(e0: u8, e1: u8, ix: &[u8; 16], out: &mut [u8; 8]) { + let mut bits = 0u64; + for (p, &val) in ix.iter().enumerate() { + bits |= BC4_CODE[usize::from(val & 7)] << (16 + 3 * p); + } let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits; - out[..8].copy_from_slice(&v.to_le_bytes()); + *out = v.to_le_bytes(); } fn bc1_pack(v: &Plain, out: &mut [u8]) { - bc1_color(&v.ep, &v.ix, out); + bc1_color( + v.ep[..6].try_into().unwrap(), + v.ix[..16].try_into().unwrap(), + (&mut out[..8]).try_into().unwrap(), + ); } fn bc3_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[6], v.ep[7], &v.ix[..16], &mut out[..8]); - bc1_color(&v.ep, &v.ix[16..], &mut out[8..]); + let (a, c) = out.split_at_mut(8); + bc4_alpha(v.ep[6], v.ep[7], v.ix[..16].try_into().unwrap(), a.try_into().unwrap()); + bc1_color( + v.ep[..6].try_into().unwrap(), + v.ix[16..].try_into().unwrap(), + (&mut c[..8]).try_into().unwrap(), + ); } fn bc4_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[0], v.ep[1], &v.ix, out); + bc4_alpha(v.ep[0], v.ep[1], v.ix[..16].try_into().unwrap(), (&mut out[..8]).try_into().unwrap()); } fn bc5_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], &mut out[..8]); - bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]); + let (a, b) = out.split_at_mut(8); + bc4_alpha(v.ep[0], v.ep[1], v.ix[..16].try_into().unwrap(), a.try_into().unwrap()); + bc4_alpha(v.ep[2], v.ep[3], v.ix[16..].try_into().unwrap(), (&mut b[..8]).try_into().unwrap()); } +/// Even and odd bit nibbles of every byte, zigzag-decoded to signed 4-bit residuals. +const NIBBLES: [[i16; 2]; 256] = { + let mut t = [[0i16; 2]; 256]; + let mut b = 0usize; + while b < 256 { + let mut even = 0u8; + let mut odd = 0u8; + let mut k = 0; + while k < 4 { + even |= (((b as u8) >> (2 * k)) & 1) << k; + odd |= (((b as u8) >> (2 * k + 1)) & 1) << k; + k += 1; + } + let ze = (even >> 1) as i16 ^ -((even & 1) as i16); + let zo = (odd >> 1) as i16 ^ -((odd & 1) as i16); + t[b] = [ze, zo]; + b += 1; + } + t +}; + /// A byte's even and odd bits as two zigzag-coded 4-bit residuals. +#[inline(always)] fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { - let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); - let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); - let (even, odd) = (z(half(b)), z(half(b >> 1))); + let [even, odd] = NIBBLES[usize::from(b)]; if odd_first { [odd, even] } else { [even, odd] } } /// Index residual plus reference, both left-aligned to 16 bits at their own /// widths, back to `bits` bits (signed). +#[inline(always)] fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { let up = |v: i16, b: u8| { if b == 0 || b > 16 { @@ -539,9 +626,11 @@ struct Bits { } impl Bits { + #[inline(always)] fn put(&mut self, value: u64, n: u32) { if n > 0 && self.at < 128 { - self.v |= (u128::from(value) & ((1u128 << n) - 1)) << self.at; + let masked = if n < 64 { value & ((1u64 << n) - 1) } else { value }; + self.v |= u128::from(masked) << self.at; } self.at += n; } @@ -735,15 +824,15 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), _ => {} } - let anchors: &[u8] = match subsets { - 2 => &[0, ANCHOR2[part]], - 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], - _ => &[0], + let anchor_mask: u16 = match subsets { + 2 => 1 | (1 << ANCHOR2[part]), + 3 => 1 | (1 << ANCHOR3A[part]) | (1 << ANCHOR3B[part]), + _ => 1, }; let mut indices = |set: usize| { - let bits = ix.bits[set]; + let bits = u32::from(ix.bits[set]); for (p, &v) in ix.ix[set].iter().enumerate() { - let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); + let n = bits - u32::from((anchor_mask >> p) & 1); w.put(u64::from(v as u16), n); } }; @@ -920,11 +1009,7 @@ fn bc6<'a>( }, ); let z = |v: u16| (v >> 1) ^ (v & 1).wrapping_neg(); - let wide = |a: u8, b: u8| { - (0..8).fold(0u16, |acc, k| { - acc | u16::from(a >> k & 1) << (2 * k) | u16::from(b >> k & 1) << (2 * k + 1) - }) - }; + let wide = wide_interleave; for (i, (s, block)) in records.zip(out).enumerate() { let (ep_ref, ix_ref) = references(s, true); let mode = s[30].wrapping_add(1); @@ -999,14 +1084,186 @@ fn bc6<'a>( ); } } - let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; + let anchor_mask: u16 = if two { 1 | (1 << ANCHOR2[usize::from(part)]) } else { 1 }; + let bias = 1u16 << (bits - 1); for (p, &v) in ix.ix.iter().enumerate() { - let short = p == 0 || p == usize::from(anchor); - let v = (v as u16).wrapping_add(1 << (bits - 1)); - w.put(v.into(), u32::from(bits) - u32::from(short)); + let v = (v as u16).wrapping_add(bias); + w.put(v.into(), u32::from(bits) - u32::from((anchor_mask >> p) & 1)); } block.copy_from_slice(&w.v.to_le_bytes()); } Ok(()) } +#[cfg(test)] +mod tests { + use super::*; + + fn fnv1a(bytes: &[u8]) -> u64 { + let mut h = 0xcbf29ce484222325u64; + for &b in bytes { + h ^= u64::from(b); + h = h.wrapping_mul(0x100000001b3); + } + h + } + + #[test] + fn lut_helpers_match_scalar_reference_exhaustively() { + let spread4 = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> k) & 1) << (2 * k)); + let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> (2 * k)) & 1) << k); + let z4 = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); + for a in 0..=255u8 { + let (even, odd) = (z4(half(a)), z4(half(a >> 1))); + assert_eq!(nibbles(a, false), [even, odd]); + assert_eq!(nibbles(a, true), [odd, even]); + for b in 0..=255u8 { + assert_eq!(interleave(a, b), spread4(a) | (spread4(b) << 1)); + let wide_ref = (0..8).fold(0u16, |acc, k| { + acc | (u16::from((a >> k) & 1) << (2 * k)) | (u16::from((b >> k) & 1) << (2 * k + 1)) + }); + assert_eq!(wide_interleave(a, b), wide_ref); + } + } + + // Precomputed Widths masks and active lengths for BC1/BC3/BC4/BC5. + for (w, ep_bits, ix3, ix2) in [ + (&BC1, [5u8, 6, 5, 5, 6, 5, 0, 0], 0usize, 16usize), + (&BC3, [5, 6, 5, 5, 6, 5, 8, 8], 16, 16), + (&BC4, [8, 8, 0, 0, 0, 0, 0, 0], 16, 0), + (&BC5, [8, 8, 8, 8, 0, 0, 0, 0], 32, 0), + ] { + let want_ep_len = ep_bits.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1); + assert_eq!(w.ep_len, want_ep_len); + assert_eq!(w.ix_len, ix3 + ix2); + for (k, &bits) in ep_bits.iter().enumerate() { + assert_eq!(w.ep_mask[k], ((1u16 << bits) - 1) as u8); + } + for (k, &mask) in w.ix_mask.iter().enumerate() { + let bits = if k < ix3 { 3 } else if k < ix3 + ix2 { 2 } else { 0 }; + assert_eq!(mask, (1u8 << bits) - 1); + } + } + + // BC7 and BC6H u16 anchor bitmasks match slice/branch anchor predicates. + for part in 0..64usize { + for subsets in [1usize, 2, 3] { + let anchors: &[u8] = match subsets { + 2 => &[0, ANCHOR2[part]], + 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], + _ => &[0], + }; + let mask: u16 = match subsets { + 2 => 1 | (1 << ANCHOR2[part]), + 3 => 1 | (1 << ANCHOR3A[part]) | (1 << ANCHOR3B[part]), + _ => 1, + }; + for p in 0..16usize { + assert_eq!(((mask >> p) & 1) != 0, anchors.contains(&(p as u8))); + } + } + if part < 32 { + for two in [false, true] { + let anchor = if two { ANCHOR2[part] } else { 0 }; + let mask: u16 = if two { 1 | (1 << ANCHOR2[part]) } else { 1 }; + for p in 0..16usize { + assert_eq!(((mask >> p) & 1) != 0, p == 0 || p == usize::from(anchor)); + } + } + } + } + + // Bits::put matches u128 reference across n = 0, small widths, 64, and overflow past 128. + let mut got = Bits::default(); + let mut ref_v = 0u128; + let mut ref_at = 0u32; + for (val, n) in [(0xFFFFu64, 0u32), (0x55, 5), (0xDEAD_BEEF_CAFE_BABE, 64), (0x3FF, 10), (0xFFFF, 60)] { + got.put(val, n); + if n > 0 && ref_at < 128 { + ref_v |= (u128::from(val) & ((1u128 << n) - 1)) << ref_at; + } + ref_at += n; + assert_eq!((got.v, got.at), (ref_v, ref_at)); + } + } + + #[test] + fn all_bc_fixtures_and_packers_match_baseline() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data/bcpack"); + let tables = Tables::builtin(); + let cases: [(&str, u8, usize, u64); 12] = [ + ("bc1-2-0", 1, 2 * 8, 0x00241ed045f935b7), + ("bc1-16-1", 1, 16 * 8, 0xaa27d5c23c617a11), + ("bc1-16-9", 1, 16 * 8, 0x5af81e16cde0f88b), + ("bc1-700-2", 1, 700 * 8, 0x6c1294776a5e0f7f), + ("bc1-8192-3", 1, 8192 * 8, 0xa0d8a27ea25cb660), + ("bc3-16-1", 3, 16 * 8, 0xc9b128a6e1beda7b), + ("bc4-16-1", 4, 16 * 8, 0x80173d43d3e12784), + ("bc5-16-1", 5, 16 * 8, 0x4338d58b289e83fc), + ("bc6-16-1", 6, 16 * 8, 0x4312c31241f68f5f), + ("bc7-2-0", 7, 2 * 8, 0xb3e3f4cd147b0999), + ("bc7-16-1", 7, 16 * 8, 0x013a7ec1ceec8b71), + ("bc7-8192-3", 7, 8192 * 8, 0x0b54870998ec2325), + ]; + for (stem, mode, out_len, want_hash) in cases { + let src = std::fs::read(dir.join(format!("{stem}.bin"))).unwrap(); + let mut dst = vec![0u8; out_len]; + decode(mode, &src, &mut dst, tables).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(fnv1a(&dst), want_hash, "{stem} output diverged from baseline"); + } + let bad_src = std::fs::read(dir.join("bc7-700-2.bin")).unwrap(); + let mut bad_dst = vec![0u8; 700 * 8]; + assert_eq!(decode(7, &bad_src, &mut bad_dst, tables), Err(Error("unused BC7 control code"))); + + // Verify fixed-size bc1_color/bc4_alpha and every BC6H mode 1..=14 / BC7 mode 0..=7. + let ep6 = [19u8, 45, 7, 29, 12, 31]; + let ix16: [u8; 16] = std::array::from_fn(|p| ((p * 5 + 3) & 7) as u8); + let (mut got1, mut got4) = ([0u8; 8], [0u8; 8]); + bc1_color(&ep6, &ix16, &mut got1); + let c0 = u16::from(ep6[0]) << 11 | u16::from(ep6[1]) << 5 | u16::from(ep6[2]); + let c1 = u16::from(ep6[3]) << 11 | u16::from(ep6[4]) << 5 | u16::from(ep6[5]); + let ref_bits1 = (0..16).fold(0u32, |acc, p| acc | (BC1_CODE[usize::from(ix16[p] & 3)] << (2 * p))); + assert_eq!(&got1[..2], &c0.to_le_bytes()); + assert_eq!(&got1[2..4], &c1.to_le_bytes()); + assert_eq!(&got1[4..8], &ref_bits1.to_le_bytes()); + bc4_alpha(0x2A, 0xD5, &ix16, &mut got4); + let ref_v4 = u64::from(0x2Au8 ^ 0x80) + | (u64::from(0xD5u8 ^ 0x80) << 8) + | (0..16).fold(0u64, |acc, p| acc | (BC4_CODE[usize::from(ix16[p] & 7)] << (16 + 3 * p))); + assert_eq!(got4, ref_v4.to_le_bytes()); + + // Exercise all 14 BC6H modes (1..=14) and all 8 BC7 modes (0..=7) end-to-end. + let bc6_recs: Vec<[u8; 32]> = (1u8..=14) + .map(|m| { + let mut r = [0u8; 32]; + for (k, slot) in r.iter_mut().enumerate().take(30) { + *slot = (m.wrapping_mul(17).wrapping_add((k as u8).wrapping_mul(11))) & 0x7F; + } + r[30] = m - 1; + r[31] = (m * 3) & 31; + r + }) + .collect(); + let mut bc6_out = [[0u8; 16]; 14]; + bc6(bc6_recs.iter().map(|r| &r[..]), bc6_out.iter_mut().map(|b| &mut b[..]), tables.bc6).unwrap(); + assert!(bc6_out.iter().all(|b| b.iter().any(|&x| x != 0))); + + let mut bc7_recs = Vec::new(); + for mode in 0u16..8 { + let idx = tables.ctrl7.iter().position(|&c| c != 0 && (c & 7) == mode).unwrap(); + let mut r = [0u8; 32]; + for (k, slot) in r.iter_mut().enumerate().take(30) { + *slot = ((mode as u8 + 1).wrapping_mul(13).wrapping_add((k as u8).wrapping_mul(7))) & 0x3F; + } + r[30] = (idx & 31) as u8; + r[31] = ((idx >> 5) & 15) as u8; + bc7_recs.push(r); + } + let mut bc7_out = [[0u8; 16]; 8]; + bc7(bc7_recs.iter().map(|r| &r[..]), bc7_out.iter_mut().map(|b| &mut b[..]), tables).unwrap(); + for (mode, block) in bc7_out.iter().enumerate() { + assert_eq!(block[0].trailing_zeros() as usize, mode, "BC7 mode {mode} header bit"); + } + } +} + From 5a5b6504bb48a3b55476a2ebe95941676fdc70b9 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:25:16 -0800 Subject: [PATCH 110/265] XAudio2: reuse validated Opus multistream scratch Reuse self-delimited packet and per-stream PCM buffers, precompute defensive channel mappings, and reject cross-stream duration mismatches before any decoder state advances. Keep bulk output copying and broad output preallocation out of this logical change.\n\nAssisted-by: Google Antigravity (Gemini 4 Neon)\nAssisted-by: Codex (GPT-5.6-sol)\nCo-authored-by: Decodere <98278826+Decodere@users.noreply.github.com> --- crates/xcl/src/hle/opus.rs | 334 ++++++++++++++++++++++++++++++++----- 1 file changed, 293 insertions(+), 41 deletions(-) diff --git a/crates/xcl/src/hle/opus.rs b/crates/xcl/src/hle/opus.rs index ac9c01313f..70d49e338a 100644 --- a/crates/xcl/src/hle/opus.rs +++ b/crates/xcl/src/hle/opus.rs @@ -266,8 +266,9 @@ pub fn parse_packet(packet: &[u8], multistream: bool) -> Option { } /// Parse one RFC 6716 Appendix B self-delimited Opus packet starting at `data[*pos..]` and -/// convert it into a standard (non-self-delimited) RFC 6716 Opus packet. -fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option> { +/// convert it into a standard (non-self-delimited) RFC 6716 Opus packet, reusing `out`. +fn split_self_delimited_into(data: &[u8], pos: &mut usize, out: &mut Vec) -> Option<()> { + out.clear(); let toc = *data.get(*pos)?; *pos += 1; let code = toc & 0x03; @@ -279,10 +280,10 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option> { let end = pos.checked_add(len)?; let payload = data.get(*pos..end)?; *pos = end; - let mut out = Vec::with_capacity(1 + len); + out.reserve(1 + len); out.push(toc); out.extend_from_slice(payload); - Some(out) + Some(()) } 1 => { let len = read_frame_len(data, pos)?; @@ -290,10 +291,10 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option> { let end = pos.checked_add(total)?; let payload = data.get(*pos..end)?; *pos = end; - let mut out = Vec::with_capacity(1 + total); + out.reserve(1 + total); out.push(toc); out.extend_from_slice(payload); - Some(out) + Some(()) } 2 => { let len1 = read_frame_len(data, pos)?; @@ -302,11 +303,11 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option> { let end = pos.checked_add(total)?; let payload = data.get(*pos..end)?; *pos = end; - let mut out = Vec::with_capacity(3 + total); + out.reserve(3 + total); out.push(toc); - write_frame_len(len1, &mut out)?; + write_frame_len(len1, out)?; out.extend_from_slice(payload); - Some(out) + Some(()) } 3 => { let fcb = *data.get(*pos)?; @@ -332,7 +333,6 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option> { } } let pad_hdr = &data[pad_hdr_start..*pos]; - let mut out = Vec::new(); out.push(toc); out.push(fcb); out.extend_from_slice(pad_hdr); @@ -342,7 +342,7 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option> { for i in 0..count { let flen = read_frame_len(data, pos)?; if i + 1 < count { - write_frame_len(flen, &mut out)?; + write_frame_len(flen, out)?; } sum = sum.checked_add(flen)?; } @@ -355,12 +355,52 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option> { let body = data.get(*pos..end)?; *pos = end; out.extend_from_slice(body); - Some(out) + Some(()) } _ => unreachable!(), } } +/// Parse one RFC 6716 Appendix B self-delimited Opus packet starting at `data[*pos..]` and +/// convert it into a standard (non-self-delimited) RFC 6716 Opus packet. +fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option> { + let mut out = Vec::new(); + split_self_delimited_into(data, pos, &mut out)?; + Some(out) +} + +/// Split an RFC 7845 multistream packet into `sub_pkts` (length `stream_count - 1`, reused in place) +/// and return the trailing standard sub-packet slice. Validates all `stream_count` sub-packets +/// before returning `Some` so decoders never consume a partially valid packet. +fn split_multistream_into<'a>( + packet: &'a [u8], + stream_count: usize, + sub_pkts: &mut [Vec], +) -> Option<&'a [u8]> { + if stream_count == 0 || sub_pkts.len() != stream_count - 1 { + return None; + } + if packet.len() < stream_count.checked_mul(2)? - 1 { + return None; + } + let mut pos = 0usize; + let mut duration_48k = None; + for sub in sub_pkts.iter_mut() { + split_self_delimited_into(packet, &mut pos, sub)?; + let info = parse_packet(sub, false)?; + if duration_48k.is_some_and(|duration| duration != info.total_samples_48k) { + return None; + } + duration_48k = Some(info.total_samples_48k); + } + let last = packet.get(pos..)?; + let info = parse_packet(last, false)?; + if duration_48k.is_some_and(|duration| duration != info.total_samples_48k) { + return None; + } + Some(last) +} + /// Split an RFC 7845 multistream packet into `stream_count` standard single-stream packets. pub fn split_multistream_packet<'a>(packet: &'a [u8], stream_count: usize) -> Option>> { if stream_count == 0 { @@ -1311,6 +1351,78 @@ impl MftDecoder { } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ChannelSrc { + Silence, + Mono(usize), + Coupled { stream: usize, chan: usize }, +} + +/// Precompute RFC 7845 channel sources defensively; `255` and out-of-range entries map to silence. +fn build_channel_map(mapping: &[u8], stream_count: usize, coupled_count: usize) -> Vec { + let coupled = coupled_count.min(stream_count); + let coupled_channels = coupled.saturating_mul(2); + mapping + .iter() + .map(|&idx| { + if idx == 255 { + return ChannelSrc::Silence; + } + let idx = usize::from(idx); + if idx < coupled_channels { + ChannelSrc::Coupled { stream: idx / 2, chan: idx % 2 } + } else { + let stream = coupled + (idx - coupled_channels); + if stream < stream_count { + ChannelSrc::Mono(stream) + } else { + ChannelSrc::Silence + } + } + }) + .collect() +} + +/// Interleave per-stream decoded PCM into `out`, clamping `max_frames` to the shortest referenced stream. +fn interleave_streams( + sub_pcm: &[Vec], + channel_map: &[ChannelSrc], + max_frames: usize, + out: &mut Vec, +) -> usize { + if channel_map.is_empty() || max_frames == 0 { + return 0; + } + let mut frames = max_frames; + for &src in channel_map { + match src { + ChannelSrc::Silence => {} + ChannelSrc::Mono(s) => { + frames = frames.min(sub_pcm.get(s).map_or(0, Vec::len)); + } + ChannelSrc::Coupled { stream, chan } => { + let avail = if chan < 2 { sub_pcm.get(stream).map_or(0, |b| b.len() / 2) } else { 0 }; + frames = frames.min(avail); + } + } + } + if frames == 0 { + return 0; + } + out.reserve(frames.saturating_mul(channel_map.len())); + for f in 0..frames { + for &src in channel_map { + let sample = match src { + ChannelSrc::Silence => 0i16, + ChannelSrc::Mono(s) => sub_pcm[s][f], + ChannelSrc::Coupled { stream, chan } => sub_pcm[stream][f * 2 + chan], + }; + out.push(sample); + } + } + frames +} + /// Stateful RFC 6716 / RFC 7845 Opus decoder (1–8 channels) backed by `MSOpusDecoder.dll`. /// /// `MSOpusDecoder.dll` registers `ThreadingModel = Both` (free-threaded); access is serialized @@ -1325,6 +1437,9 @@ pub struct Decoder { pre_skip: u16, pre_skip_left: usize, output_gain_scale: f32, + channel_map: Vec, + sub_pkts: Vec>, + sub_pcm: Vec>, } // SAFETY: MSOpusDecoder.dll is ThreadingModel=Both (MTA-safe) and Decoder requires &mut self. @@ -1360,6 +1475,16 @@ impl Decoder { let output_rate = streams[0].output_rate(); let pre_skip_scaled = ((head.pre_skip as u64 * output_rate as u64) / 48_000) as usize; let output_gain_scale = gain_scale(head.output_gain); + let (channel_map, sub_pkts, sub_pcm) = if multistream { + let sc = streams.len(); + ( + build_channel_map(&head.mapping, sc, usize::from(head.coupled_count)), + vec![Vec::new(); sc.saturating_sub(1)], + vec![Vec::new(); sc], + ) + } else { + (Vec::new(), Vec::new(), Vec::new()) + }; Ok(Self { streams, @@ -1371,6 +1496,9 @@ impl Decoder { pre_skip: head.pre_skip, pre_skip_left: pre_skip_scaled, output_gain_scale, + channel_map, + sub_pkts, + sub_pcm, }) } @@ -1405,45 +1533,27 @@ impl Decoder { fn decode_packet_pcm(&mut self, packet: &[u8], out: &mut Vec) -> Result<(), String> { let start = out.len(); - let ch = self.channels as usize; if !self.multistream { self.streams[0].decode_packet(packet, out)?; } else { - let subs = split_multistream_packet(packet, self.streams.len()) + let stream_count = self.streams.len(); + let last = split_multistream_into(packet, stream_count, &mut self.sub_pkts) .ok_or_else(|| "invalid RFC 7845 multistream Opus packet".to_string())?; - let mut decoded: Vec> = Vec::with_capacity(self.streams.len()); + let coupled = usize::from(self.coupled_count); let mut frames = usize::MAX; - for (i, sub) in subs.iter().enumerate() { - let mut buf = Vec::new(); - let n = self.streams[i].decode_packet(sub, &mut buf)?; - frames = frames.min(n); - decoded.push(buf); + for i in 0..stream_count { + let sub: &[u8] = if i + 1 < stream_count { &self.sub_pkts[i] } else { last }; + let pcm = &mut self.sub_pcm[i]; + pcm.clear(); + let n = self.streams[i].decode_packet(sub, pcm)?; + let expected_ch = if i < coupled { 2 } else { 1 }; + frames = frames.min(n).min(pcm.len() / expected_ch); } if frames == usize::MAX { frames = 0; } - // Map decoded stream channels to output channels per RFC 7845 mapping table. - let coupled = self.coupled_count as usize; - out.reserve(frames * ch); - for f in 0..frames { - for &idx in &self.mapping { - let sample = if idx == 255 { - 0i16 - } else { - let idx = idx as usize; - if idx < coupled * 2 { - let s = idx / 2; - let c = idx % 2; - decoded[s][f * 2 + c] - } else { - let s = coupled + (idx - coupled * 2); - decoded[s][f] - } - }; - out.push(sample); - } - } + interleave_streams(&self.sub_pcm, &self.channel_map, frames, out); } // Apply RFC 7845 output gain if non-zero. @@ -2046,4 +2156,146 @@ pub(crate) mod tests { assert!(d24.decode_packet(&[0xFB, 0], &mut out24).is_err()); assert_eq!(d24.decode_packet(MONO_HYBRID_20MS[1], &mut out24).unwrap(), 480); } + + #[test] + fn split_self_delimited_into_reuses_buffer_and_matches_owned_split() { + // 6-stream packet exercising self-delimited codes 0, 1, 2, 3-VBR-padded, 3-CBR + standard tail. + let synthetic: &[u8] = &[ + 0xFC, 0x02, 0x11, 0x22, // code 0 + 0xF1, 0x02, 0x11, 0x22, 0x33, 0x44, // code 1: two 10 ms frames + 0xF2, 0x02, 0x03, 0x11, 0x22, 0x33, 0x44, 0x55, // code 2: two 10 ms frames + 0xF3, 0xC2, 0x02, 0x01, 0x02, 0xAA, 0xBB, 0xCC, 0x00, 0x00, // code 3 VBR + pad + 0xF3, 0x02, 0x02, 0x11, 0x22, 0x33, 0x44, // code 3 CBR + 0xF8, 0x99, 0x88, // standard tail + ]; + let owned = split_multistream_packet(synthetic, 6).unwrap(); + let mut sub_pkts = vec![Vec::new(); 5]; + let last = split_multistream_into(synthetic, 6, &mut sub_pkts).unwrap(); + for i in 0..5 { + assert_eq!(sub_pkts[i].as_slice(), owned[i].as_ref()); + } + assert_eq!(last, owned[5].as_ref()); + + // Real 5.1 packets: warm up on the larger packet [0], then verify zero reallocation on [1]. + let mut sub51 = vec![Vec::new(); 3]; + let last0 = split_multistream_into(SURROUND51_20MS[0], 4, &mut sub51).unwrap(); + let owned0 = split_multistream_packet(SURROUND51_20MS[0], 4).unwrap(); + for i in 0..3 { + assert_eq!(sub51[i].as_slice(), owned0[i].as_ref()); + } + assert_eq!(last0, owned0[3].as_ref()); + let before: Vec<(usize, usize)> = sub51.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect(); + + let last1 = split_multistream_into(SURROUND51_20MS[1], 4, &mut sub51).unwrap(); + let owned1 = split_multistream_packet(SURROUND51_20MS[1], 4).unwrap(); + for i in 0..3 { + assert_eq!(sub51[i].as_slice(), owned1[i].as_ref()); + } + assert_eq!(last1, owned1[3].as_ref()); + let after: Vec<(usize, usize)> = sub51.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect(); + assert_eq!(before, after, "reused sub_pkts buffers must not reallocate"); + + // Edge cases: 1-stream, 0-stream, wrong scratch len, short packet, invalid tail. + let mut empty_subs: Vec> = Vec::new(); + assert_eq!(split_multistream_into(MONO_HYBRID_20MS[0], 1, &mut empty_subs), Some(MONO_HYBRID_20MS[0])); + assert!(split_multistream_into(MONO_HYBRID_20MS[0], 0, &mut empty_subs).is_none()); + assert!(split_multistream_into(SURROUND51_20MS[0], 4, &mut empty_subs).is_none()); + assert!(split_multistream_into(&[0xFC, 0x00, 0xFC], 4, &mut sub51).is_none()); + let bad_tail = [0xFC, 0x02, 0xFF, 0xFE, 0xFC, 0x02, 0xFF, 0xFE, 0x78, 0x02, 0xFF, 0xFE, 0xFB, 0x00]; + assert!(split_multistream_into(&bad_tail, 4, &mut sub51).is_none()); + let mismatched_duration = [0xFD, 0x01, 0xAA, 0xBB, 0xFC, 0xCC]; + let mut one_sub = vec![Vec::new()]; + assert!(split_multistream_packet(&mismatched_duration, 2).is_some(), "each sub-packet is valid by itself"); + assert!(split_multistream_into(&mismatched_duration, 2, &mut one_sub).is_none(), "all sub-streams must describe the same duration"); + } + + #[test] + fn interleave_channel_map_clamps_short_stream_without_panic() { + let map = build_channel_map(&[0, 4, 1, 2, 3, 5, 255, 99], 4, 2); + assert_eq!( + map, + vec![ + ChannelSrc::Coupled { stream: 0, chan: 0 }, + ChannelSrc::Mono(2), + ChannelSrc::Coupled { stream: 0, chan: 1 }, + ChannelSrc::Coupled { stream: 1, chan: 0 }, + ChannelSrc::Coupled { stream: 1, chan: 1 }, + ChannelSrc::Mono(3), + ChannelSrc::Silence, + ChannelSrc::Silence, + ], + ); + // Defensive clamp if coupled_count exceeds stream_count. + assert_eq!( + build_channel_map(&[0, 1, 2], 1, 3), + vec![ + ChannelSrc::Coupled { stream: 0, chan: 0 }, + ChannelSrc::Coupled { stream: 0, chan: 1 }, + ChannelSrc::Silence, + ], + ); + + let full = vec![ + vec![10, 20, 11, 21], + vec![30, 40, 31, 41], + vec![50, 51], + vec![60, 61], + ]; + let map51 = build_channel_map(&[0, 4, 1, 2, 3, 5, 255], 4, 2); + let mut out = Vec::new(); + assert_eq!(interleave_streams(&full, &map51, 2, &mut out), 2); + assert_eq!(out, vec![10, 50, 20, 30, 40, 60, 0, 11, 51, 21, 31, 41, 61, 0]); + + // Short coupled stream (3 samples -> 1 complete stereo frame) clamps instead of panicking. + let short_coupled = vec![vec![10, 20, 99], vec![30, 40, 31, 41], vec![50, 51], vec![60, 61]]; + out.clear(); + assert_eq!(interleave_streams(&short_coupled, &map51, 4, &mut out), 1); + assert_eq!(out, vec![10, 50, 20, 30, 40, 60, 0]); + + // Out-of-bounds stream or channel entries yield 0 frames without panicking. + out.clear(); + assert_eq!(interleave_streams(&full, &[ChannelSrc::Mono(99)], 2, &mut out), 0); + assert_eq!(interleave_streams(&full, &[ChannelSrc::Coupled { stream: 0, chan: 2 }], 2, &mut out), 0); + assert!(out.is_empty()); + } + + #[test] + fn multistream_scratch_reuse_and_atomic_validation() { + if !is_available() { + eprintln!("skipping: MSOpusDecoder.dll not available"); + return; + } + // Atomic validation: valid streams 0..2 + invalid stream 3 must fail without advancing any stream. + let mut dec51 = Decoder::new(6, 48_000, SURROUND51_20MS_HEAD).unwrap(); + let bad_tail = [0xFC, 0x02, 0xFF, 0xFE, 0xFC, 0x02, 0xFF, 0xFE, 0x78, 0x02, 0xFF, 0xFE, 0xFB, 0x00]; + let mut pcm51 = Vec::new(); + assert!(dec51.decode_packet(&bad_tail, &mut pcm51).is_err()); + assert!(pcm51.is_empty()); + assert!(dec51.streams.iter().all(|s| s.timestamp_100ns() == 0)); + + let mut dec3 = Decoder::new(3, 48_000, &build_opus_head(3, 48_000, 0, 0)).unwrap(); + let mismatched_duration = [0xFD, 0x01, 0xAA, 0xBB, 0xFC, 0xCC]; + let mut pcm3 = Vec::new(); + assert!(dec3.decode_packet(&mismatched_duration, &mut pcm3).is_err()); + assert!(pcm3.is_empty()); + assert!(dec3.streams.iter().all(|s| s.timestamp_100ns() == 0), "duration mismatch is rejected before any sub-decoder advances"); + + // Scratch reuse across multistream packets: zero reallocations on packet 1 after packet 0 warm-up. + assert_eq!(dec51.decode_packet(SURROUND51_20MS[0], &mut pcm51).unwrap(), 960 - 312); + let pkt_ptrs: Vec<(usize, usize)> = dec51.sub_pkts.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect(); + let pcm_ptrs: Vec<(usize, usize)> = dec51.sub_pcm.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect(); + assert!(pkt_ptrs.iter().all(|&(_, c)| c > 0) && pcm_ptrs.iter().all(|&(_, c)| c > 0)); + assert_eq!(dec51.decode_packet(SURROUND51_20MS[1], &mut pcm51).unwrap(), 960); + assert_eq!(pkt_ptrs, dec51.sub_pkts.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect::>()); + assert_eq!(pcm_ptrs, dec51.sub_pcm.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect::>()); + + // Defensive OOB clamp if a coupled sub-stream outputs mono (half the expected samples). + let mut dec_short = Decoder::new(6, 48_000, SURROUND51_20MS_HEAD).unwrap(); + let ud = build_opus_head(1, 48_000, 0, 0); + dec_short.streams[0] = SingleStreamDecoder::new(1, 48_000, Some(&ud)).unwrap(); + let mut short_out = Vec::new(); + assert_eq!(dec_short.decode_packet(SURROUND51_20MS[0], &mut short_out).unwrap(), 480 - 312); + assert_eq!(short_out.len(), (480 - 312) * 6); + + } } From fb81098850ed01c7dfc9b91986c1f9565d827a3d Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:26:21 -0800 Subject: [PATCH 111/265] D3D12.X: detach heap state before final Release Take descriptor-heap and unified-memory bookkeeping while a temporary native reference still pins the old object, then free captured backing only after the driver actually reaches zero. Preserve a documented post-free fallback for missed simultaneous-release probes without changing queue or allocator retirement protocols.\n\nAssisted-by: Claude Code (Claude Opus 5.5)\nAssisted-by: Codex (GPT-5.6-sol)\nCo-authored-by: Sage <108908666+sage-sage@users.noreply.github.com> --- crates/xcl/src/hle/d3d12x/console_heap.rs | 50 ++++--- crates/xcl/src/hle/d3d12x/real.rs | 170 ++++++++++++++++++++-- 2 files changed, 185 insertions(+), 35 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index cd78056644..2a8c7e1f1e 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -397,29 +397,39 @@ pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32, sampler: /// The heap object was released for good: its slots go back to unified memory. pub fn unregister(obj: usize) { - let gone = { - let mut heaps = HEAPS.lock().unwrap(); - heaps.iter().position(|h| h.obj == obj).map(|i| heaps.swap_remove(i)) - }; - if let Some(h) = gone { - for (p, &f) in h.pages.iter().enumerate().filter(|&(_, &f)| f != UNMAPPED) { - if h.sampler { - release_global_sampler(f, sampler_page_descriptors(h.n, p as u32)); - } else { - release_global(f, page_descriptors(h.n, p as u32)); - } + if let Some(h) = take(obj) { + free(h); + } +} + +/// A heap removed by `take`; its backing storage remains live until `free`. +pub struct Taken(Heap); + +/// Stop finding a heap by object address without freeing memory the object may still use. +pub fn take(obj: usize) -> Option { + let mut heaps = HEAPS.lock().unwrap(); + heaps.iter().position(|h| h.obj == obj).map(|i| Taken(heaps.swap_remove(i))) +} + +/// Return a taken heap's slots and shadow memory after its native object is gone. +pub fn free(Taken(h): Taken) { + for (p, &f) in h.pages.iter().enumerate().filter(|&(_, &f)| f != UNMAPPED) { + if h.sampler { + release_global_sampler(f, sampler_page_descriptors(h.n, p as u32)); + } else { + release_global(f, page_descriptors(h.n, p as u32)); } - match h.memory { - Memory::Sparse => { - unsafe { super::sparse::free(h.shadow) }; - } - Memory::Uma => { - if let Some(u) = crate::gpu::uma::get() { - u.free(h.shadow); - } + } + match h.memory { + Memory::Sparse => { + unsafe { super::sparse::free(h.shadow) }; + } + Memory::Uma => { + if let Some(u) = crate::gpu::uma::get() { + u.free(h.shadow); } - Memory::Title => unsafe { crate::hle::kernelx::runtime_free(h.shadow, crate::hle::kernelx::D3D_DESCRIPTOR_HEAP) }, } + Memory::Title => unsafe { crate::hle::kernelx::runtime_free(h.shadow, crate::hle::kernelx::D3D_DESCRIPTOR_HEAP) }, } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9d9f3ffcb7..2515ae6ed0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2088,16 +2088,31 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst } } -/// descriptor heap Release (every caller): a console heap's slots go with it -unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 { +/// Remove address-keyed state before a last native Release can expose that address for reuse. +/// A simultaneous Release can make the probe miss the last reference; the post-free `take` +/// prevents stale state from leaking but cannot protect a replacement already at the address. +unsafe fn release_taking_first(this: *mut c_void, mut take: impl FnMut() -> T, after: impl FnOnce(T)) -> u32 { + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let take_first = add_ref(this) == 2; + let taken = take_first.then(&mut take); + // Drop the temporary probe reference, then the caller's reference. + f(this); let n = f(this); if n == 0 { - super::console_heap::unregister(this as usize); + after(match taken { + Some(taken) => taken, + None => take(), + }); } n } +/// descriptor heap Release (every caller): a console heap's slots go with it +unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 { + release_taking_first(this, || super::console_heap::take(this as usize), |h| h.into_iter().for_each(super::console_heap::free)) +} + /// Default UAV dimension for a texture resource when `CreateUnorderedAccessView` receives a NULL desc. fn default_uav_dimension(rd: &D3D12_RESOURCE_DESC) -> D3D12_UAV_DIMENSION { match rd.Dimension { @@ -3639,19 +3654,19 @@ fn heap_block(heap: usize) -> Option<(usize, bool)> { /// ID3D12Heap::Release: its block of unified memory goes with it. unsafe extern "system" fn mem_heap_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); - if n == 0 { - let gone = HEAP_UMA.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block); - if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { - if u.is_sparse(p) { - super::sparse::free(p); - } else { - u.free(p); + release_taking_first( + this, + || HEAP_UMA.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block), + |gone| { + if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { + if u.is_sparse(p) { + super::sparse::free(p); + } else { + u.free(p); + } } - } - } - n + }, + ) } creator!(dev_create_fence_pc, "CreateFence", Kind::Fence, [a1, a2]); @@ -10328,3 +10343,128 @@ mod list_release_tests { } } +#[cfg(test)] +mod heap_release_order_tests { + use super::*; + + #[repr(C)] + struct FakeHeap { + vtable: *const usize, + refs: u32, + scripted: bool, + releases: u32, + freed: fn(usize), + ext_vtable: [usize; 4], + orig_vtable: [usize; 3], + } + + std::thread_local! { + static EVENTS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + fn event(name: &'static str) { + EVENTS.with(|events| events.borrow_mut().push(name)); + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let heap = &mut *(this as *mut FakeHeap); + if heap.scripted { + 3 // Make the helper take its compatibility path deterministically. + } else { + heap.refs += 1; + heap.refs + } + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let heap = &mut *(this as *mut FakeHeap); + if heap.scripted { + heap.releases += 1; + if heap.releases == 2 { + (heap.freed)(this as usize); + 0 + } else { + 2 + } + } else { + heap.refs -= 1; + if heap.refs == 0 { + (heap.freed)(this as usize); + } + heap.refs + } + } + + fn fake(refs: u32, scripted: bool, freed: fn(usize)) -> *mut FakeHeap { + let heap = Box::into_raw(Box::new(FakeHeap { + vtable: std::ptr::null(), + refs, + scripted, + releases: 0, + freed, + ext_vtable: [0; 4], + orig_vtable: [0; 3], + })); + unsafe { + (*heap).orig_vtable[1] = add_ref as usize; + (*heap).orig_vtable[2] = release as usize; + (*heap).ext_vtable[0] = (*heap).orig_vtable.as_ptr() as usize; + (*heap).ext_vtable[2] = add_ref as usize; + (*heap).ext_vtable[3] = release as usize; + (*heap).vtable = (*heap).ext_vtable.as_ptr().add(1); + } + heap + } + + fn note_freed(_: usize) { + event("freed"); + } + + #[test] + fn last_release_takes_before_free_and_frees_afterward() { + EVENTS.with(|events| events.borrow_mut().clear()); + let heap = fake(2, false, note_freed); + unsafe { + assert_eq!(release_taking_first(heap.cast(), || event("take"), |()| event("after")), 1); + assert!(EVENTS.with(|events| events.borrow().is_empty()), "a non-final release keeps the state"); + assert_eq!(release_taking_first(heap.cast(), || event("take"), |()| event("after")), 0); + drop(Box::from_raw(heap)); + } + assert_eq!(EVENTS.with(|events| events.borrow().clone()), ["take", "freed", "after"]); + } + + #[test] + fn missed_probe_takes_once_after_final_release() { + EVENTS.with(|events| events.borrow_mut().clear()); + let heap = fake(0, true, note_freed); + unsafe { + assert_eq!(release_taking_first(heap.cast(), || event("take"), |()| event("after")), 0); + drop(Box::from_raw(heap)); + } + assert_eq!( + EVENTS.with(|events| events.borrow().clone()), + ["freed", "take", "after"], + "the compatibility fallback cannot close the post-free address-reuse window" + ); + } + + #[test] + fn memory_heap_release_keeps_replacement_at_reused_address() { + fn replace(addr: usize) { + let replacement = HeapUma { size: 0x2_0000, align: 0x1_0000, prefer_coherent: false, cpu_readback: false, block: None }; + HEAP_UMA.lock().unwrap().get_or_insert_with(HashMap::new).insert(addr, replacement); + } + + let heap = fake(1, false, replace); + let addr = heap as usize; + let old = HeapUma { size: 0x1_0000, align: 0x1_0000, prefer_coherent: false, cpu_readback: false, block: None }; + HEAP_UMA.lock().unwrap().get_or_insert_with(HashMap::new).insert(addr, old); + unsafe { + assert_eq!(mem_heap_release(heap.cast()), 0); + drop(Box::from_raw(heap)); + } + let kept = HEAP_UMA.lock().unwrap().as_mut().and_then(|heaps| heaps.remove(&addr)); + assert_eq!(kept.map(|heap| heap.size), Some(0x2_0000), "the final Release must not remove replacement bookkeeping"); + } +} + From 9061f0aad0c90dab8f1ea713e5c035f4337d53be Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 17:37:09 -0500 Subject: [PATCH 112/265] D3D12.X: count driver pipeline builds in the window title The title counted only DXC work, so multi-second cold driver pipeline builds could make it report zero active work while the title stalled. Count uncached CreatePipelineState calls, builds waiting for the large compile slot, and completed builds. Keep cached driver-blob loads out of the build count, including the two-pass compute path, and restore the thread-local cache marker during unwinding. Log slow driver builds even when they fall below the large-pipeline threshold. Assisted-by: Claude Code (Claude Opus 5.5) Assisted-by: Codex (GPT-5.6-sol) Co-authored-by: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/present.rs | 39 ++++--- crates/xcl/src/hle/d3d12x/real.rs | 150 ++++++++++++++++++++++++--- 2 files changed, 162 insertions(+), 27 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 54d02f5fad..1bcc1d6368 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -764,10 +764,19 @@ impl FrameRate { /// While XCL compiles shaders (DXC, programs the disk cache did not have – the title draws /// nothing with those pipelines meanwhile: after an XCL update the screen stays black while -/// thousands recompile), the window's title says so: -/// "XCL – | N FPS | compiling shaders: N running, M done[, Q pipelines queued][, F failed]". -/// It stays 2 s after the last compile (compiles in the title's own calls come one by one), -/// then only the game name and presented frame rate remain. +/// thousands recompile) or the driver builds pipelines, the window's title says so +/// (`compiling_text`). It stays 2 s after the last compile (compiles in the title's own calls +/// come one by one), then only the game name and presented frame rate remain. +/// " | compiling shaders: DXC N running, M done | driver N building[ (W waiting for a +/// slot)], D done[, Q pipelines queued][, F failed]": `dxc` (running, done), `driver` builds +/// (running, waiting for a huge-compile slot, done; `real::driver_build_counts`). +fn compiling_text(title: &str, (running, done): (usize, usize), (building, waiting, built): (usize, usize, usize), queued: usize, failed: usize) -> String { + let waiting = if waiting > 0 { format!(" ({waiting} waiting for a slot)") } else { String::new() }; + let queued = if queued > 0 { format!(", {queued} pipelines queued") } else { String::new() }; + let failed = if failed > 0 { format!(", {failed} failed") } else { String::new() }; + format!("{title} | compiling shaders: DXC {running} running, {done} done | driver {building} building{waiting}, {built} done{queued}{failed}") +} + unsafe fn show_compiling(hwnd: HWND) { static SHOWN: Mutex<Option<String>> = Mutex::new(None); static LAST_ACTIVE: Mutex<Option<Instant>> = Mutex::new(None); @@ -780,8 +789,9 @@ unsafe fn show_compiling(hwnd: HWND) { .get_or_insert_with(|| FrameRate::new(now, presented)) .sample(now, presented); let (_, failed, queued) = super::pso_async::counts(); - let (running, done) = crate::gpu::recomp::dxc::compile_counts(); - let active = running > 0 || queued > 0; + let dxc = crate::gpu::recomp::dxc::compile_counts(); + let driver = super::real::driver_build_counts(); + let active = dxc.0 > 0 || driver.0 > 0 || driver.1 > 0 || queued > 0; let recent = { let mut last = LAST_ACTIVE.lock().unwrap(); if active { @@ -790,13 +800,7 @@ unsafe fn show_compiling(hwnd: HWND) { last.is_some_and(|t| t.elapsed() < Duration::from_secs(2)) }; let title = format!("XCL – {} | {fps:.1} FPS", window_name()); - let text = if recent { - let queued = if queued > 0 { format!(", {queued} pipelines queued") } else { String::new() }; - let failed = if failed > 0 { format!(", {failed} failed") } else { String::new() }; - format!("{title} | compiling shaders: {running} running, {done} done{queued}{failed}") - } else { - title - }; + let text = if recent { compiling_text(&title, dxc, driver, queued, failed) } else { title }; let mut shown = SHOWN.lock().unwrap(); if shown.as_deref() != Some(text.as_str()) { let _ = SetWindowTextW(hwnd, &HSTRING::from(text.as_str())); @@ -1919,6 +1923,15 @@ mod tests { drop(token); } + #[test] + fn the_title_counts_dxc_compiles_and_driver_builds() { + assert_eq!( + compiling_text("XCL – t | 30.0 FPS", (0, 12), (2, 1, 40), 5, 0), + "XCL – t | 30.0 FPS | compiling shaders: DXC 0 running, 12 done | driver 2 building (1 waiting for a slot), 40 done, 5 pipelines queued" + ); + assert_eq!(compiling_text("t", (3, 4), (0, 0, 0), 0, 1), "t | compiling shaders: DXC 3 running, 4 done | driver 0 building, 0 done, 1 failed"); + } + #[test] fn present_ring_overlaps_previous_frame_and_drains_cleanly() { let mut ring = PresentRing::new(PRESENT_SLOTS); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 2515ae6ed0..ee20d58685 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3911,9 +3911,79 @@ pub fn switch_form_retries() -> u64 { SWITCH_FORM_RETRIES.load(Ordering::Relaxed) } +/// Driver pipeline builds for the window title: every `Create*PipelineState` call XCL makes +/// (`driver_pso`, on a worker or on a title thread) while it runs and once done, and the huge ones +/// waiting for their slot (`driver_compile_identified`). A call given a driver blob of an earlier +/// build (`BLOB_SUPPLIED`) is a load, not a build, and is not counted. +struct DriverBuilds { + building: AtomicUsize, + waiting: AtomicUsize, + done: AtomicUsize, +} + +static DRIVER_BUILDS: DriverBuilds = DriverBuilds::new(); + +thread_local! { + /// this thread's driver call is given a driver blob (`driver_compile_identified`) + static BLOB_SUPPLIED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +struct BlobSupplied(bool); + +impl BlobSupplied { + fn set(supplied: bool) -> Self { + Self(BLOB_SUPPLIED.with(|b| b.replace(supplied))) + } +} + +impl Drop for BlobSupplied { + fn drop(&mut self) { + BLOB_SUPPLIED.with(|b| b.set(self.0)); + } +} + +/// One counted build or wait: undone when dropped (a build also counts as done then). +struct Counted<'a>(&'a AtomicUsize, Option<&'a AtomicUsize>); + +impl Drop for Counted<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::Relaxed); + if let Some(done) = self.1 { + done.fetch_add(1, Ordering::Relaxed); + } + } +} + +impl DriverBuilds { + const fn new() -> Self { + Self { building: AtomicUsize::new(0), waiting: AtomicUsize::new(0), done: AtomicUsize::new(0) } + } + + fn building(&self) -> Counted<'_> { + self.building.fetch_add(1, Ordering::Relaxed); + Counted(&self.building, Some(&self.done)) + } + + fn waiting(&self) -> Counted<'_> { + self.waiting.fetch_add(1, Ordering::Relaxed); + Counted(&self.waiting, None) + } + + fn counts(&self) -> (usize, usize, usize) { + (self.building.load(Ordering::Relaxed), self.waiting.load(Ordering::Relaxed), self.done.load(Ordering::Relaxed)) + } +} + +/// Driver pipeline builds (running now, waiting for a huge-compile slot, done so far), for the +/// window title. +pub fn driver_build_counts() -> (usize, usize, usize) { + DRIVER_BUILDS.counts() +} + /// A driver pipeline call; E_OUTOFMEMORY while this thread translates with heap windows is /// noted for `with_switch_fallback`. unsafe fn driver_pso(f: PsoFn, this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _build = (!BLOB_SUPPLIED.with(|b| b.get())).then(|| DRIVER_BUILDS.building()); let heap = crate::gpu::recomp::pso::mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0; let injected = heap && INJECTED_OOM.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)).is_ok(); let hr = if injected { @@ -4181,7 +4251,7 @@ fn compile_slots(bytes: usize) -> &'static Slots { /// waits for its slot first (`big_compile_turn`; not a title thread's, nor one the title waits /// for). Logs its time, size and whether it was gated. fn driver_compile<R>(kind: &str, bytes: usize, gate: bool, build: impl FnOnce() -> R) -> R { - driver_compile_identified(kind, bytes, gate, None, build).0 + driver_compile_identified(kind, bytes, gate, None, false, build).0 } /// `XCL_PSO_TRACE=1`: every driver compile is logged, not only huge ones. @@ -4190,30 +4260,44 @@ fn pso_trace() -> bool { *V.get_or_init(|| std::env::var("XCL_PSO_TRACE").is_ok_and(|v| v.trim() == "1")) } -/// `driver_compile`, with the console record's hash (`fnv64` of the shader container, as in -/// `[SHADER]` lines and `xcl shaders --measure-pso`) and whether a driver blob was supplied. +/// `driver_compile`, with the optional console record hash (`fnv64` of the shader container, +/// as in `[SHADER]` lines and `xcl shaders --measure-pso`) and whether a driver blob was supplied. /// Also returns the time spent in the driver alone (not waiting for a slot). -fn driver_compile_identified<R>(kind: &str, bytes: usize, gate: bool, record: Option<(u64, bool)>, build: impl FnOnce() -> R) -> (R, std::time::Duration) { +fn driver_compile_identified<R>(kind: &str, bytes: usize, gate: bool, record: Option<u64>, cached: bool, build: impl FnOnce() -> R) -> (R, std::time::Duration) { let huge = gate && bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); let gate_stall = huge.then(|| crate::stall::span(crate::stall::StallKind::DriverCompileGate)).flatten(); - let _slot = huge.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + let _slot = huge.then(|| { + let _waiting = DRIVER_BUILDS.waiting(); + big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted) + }); drop(gate_stall); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; let log = pso_trace() || bytes >= huge_pso_bytes(); if log { - let record = record.map_or_else(String::new, |(hash, cached)| { - format!(", record {hash:016x}, driver blob {}", if cached { "supplied" } else { "absent" }) - }); + let record = record.map_or_else( + || if cached { ", driver blob supplied".to_string() } else { String::new() }, + |hash| format!(", record {hash:016x}, driver blob {}", if cached { "supplied" } else { "absent" }), + ); crate::xlog_info!("D3D12.X: driver compile start #{sequence}: {kind} PSO, {bytes} B DXIL{record}"); } let started = std::time::Instant::now(); + let _blob = BlobSupplied::set(cached); let r = build(); let took = started.elapsed(); if log { crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_pso_bytes(), huge, waited)); + } else if took >= std::time::Duration::from_secs(1) { + // a slow one below the huge size, logged without XCL_PSO_TRACE too (a title thread's + // graphics pipelines took 2 - 5 s each, unlogged) + let record = record.map_or_else( + || if cached { ", driver blob supplied".to_string() } else { String::new() }, + |hash| format!(", record {hash:016x}, driver blob {}", if cached { "supplied" } else { "absent" }), + ); + let thread = std::thread::current().name().unwrap_or("title").to_string(); + crate::xlog_info!("D3D12.X: slow driver compile #{sequence}: {kind} PSO, {bytes} B DXIL{record}, {} ms on {thread}", took.as_millis()); } (r, took) } @@ -4379,6 +4463,42 @@ mod big_compile_tests { assert!(gate_note(true, false, ms).contains("ungated here")); } + #[test] + fn driver_builds_count_while_running_and_once_done() { + let b = DriverBuilds::new(); + { + let _one = b.building(); + let _two = b.building(); + let _wait = b.waiting(); + assert_eq!(b.counts(), (2, 1, 0)); + } + assert_eq!(b.counts(), (0, 0, 2), "a wait is not a build"); + } + + unsafe extern "system" fn counting_driver(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { + // the global counter: other tests' builds can run too, so at least this one + if DRIVER_BUILDS.counts().0 >= 1 { S_OK } else { S_FALSE } + } + + unsafe extern "system" fn blob_driver(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { + if BLOB_SUPPLIED.with(|b| b.get()) { S_OK } else { S_FALSE } + } + + #[test] + fn every_driver_call_is_counted_and_a_blob_load_is_not() { + let done = DRIVER_BUILDS.counts().2; + let call = |f: PsoFn| unsafe { driver_pso(f, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), std::ptr::null_mut()) }; + assert_eq!(call(counting_driver), S_OK, "counted while in the driver"); + assert!(DRIVER_BUILDS.counts().2 > done); + // a compile given a driver blob reaches the driver as a load; a cold one does not + assert_eq!(driver_compile_identified("test", 1, false, Some(1), true, || call(blob_driver)).0, S_OK); + assert_eq!(driver_compile_identified("test", 1, false, Some(1), false, || call(blob_driver)).0, S_FALSE); + assert_eq!(driver_compile_identified("two-pass test", 1, false, None, true, || call(blob_driver)).0, S_OK, + "a cache hit without a console record is still a driver-blob load"); + let _ = std::panic::catch_unwind(|| driver_compile_identified("panic test", 1, false, None, true, || panic!("driver panic"))); + assert!(!BLOB_SUPPLIED.with(|b| b.get()), "reset after the call"); + } + #[test] fn giant_driver_compiles_have_their_own_lane() { assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE - 1), &BIG_COMPILES)); @@ -4671,7 +4791,8 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL "compute", dxil.len(), gate_compute_driver_compile(cached.is_some()), - Some((record, cached.is_some())), + Some(record), + cached.is_some(), || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), ); let mut persist_took = in_driver; @@ -4689,7 +4810,8 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL "compute retry", dxil.len(), gate_compute_driver_compile(false), - Some((record, false)), + Some(record), + false, || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), ); hr = retried; @@ -5993,7 +6115,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const driver_cache::note(false, loaded.take()); } }, - |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some((ps_hash, has_cached)), f), + |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some(ps_hash), has_cached, f), |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), ); let hr = build.hr; @@ -6779,7 +6901,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: } let iid = pc_iid(Kind::PipelineState); let mut compute: *mut c_void = std::ptr::null_mut(); - let (mut hc, mut cin_driver) = driver_compile_identified("compute pass", tp.cs.len(), false, None, || { + let (mut hc, mut cin_driver) = driver_compile_identified("compute pass", tp.cs.len(), false, None, ccached.is_some(), || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); let mut cpersist_took = cin_driver; @@ -6790,7 +6912,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: } cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); compute = std::ptr::null_mut(); - let (retried, took) = driver_compile_identified("compute pass retry", tp.cs.len(), false, None, || { + let (retried, took) = driver_compile_identified("compute pass retry", tp.cs.len(), false, None, false, || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); hc = retried; @@ -7754,7 +7876,7 @@ unsafe fn translated_graphics_stream_once(this: *mut c_void, desc: *const c_void } let submit = |label: &str, has_cached: bool, out: &StreamOut| { let d = [out.0.len(), out.0.as_ptr() as usize]; - driver_compile_identified(label, out.shader_bytes(), gate_compute_driver_compile(has_cached), Some((ps_hash, has_cached)), + driver_compile_identified(label, out.shader_bytes(), gate_compute_driver_compile(has_cached), Some(ps_hash), has_cached, || finish_pso(this, fs, d.as_ptr() as *const c_void, riid, ppv)) }; let rejected_generation = cached.clone(); From 70683257e861ab76af6ace9b293345e0a43ec189 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:31:08 -0800 Subject: [PATCH 113/265] D3D12.X: poll allocator fences outside global state GetCompletedValue can enter the driver and block or call back into XCL. Snapshot strong fence references and list generations under the allocator state lock, poll them unlocked, then revalidate the exact submission before recording diagnostics or declaring storage reusable. This removes driver polling from note_resubmits and in_flight without allowing an address-reuse generation or a newly reserved submission to be mistaken for completed work. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 166 ++++++++++++++++++++---- 1 file changed, 140 insertions(+), 26 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 0c39bca2ee..a0f0c73f61 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -69,6 +69,7 @@ struct State { submit_pins: HashMap<(usize, u64), usize>, } +#[derive(Clone)] struct LastSubmit { queue: usize, fence: ID3D12Fence, @@ -76,6 +77,13 @@ struct LastSubmit { recording: u64, } +fn same_submit(a: &LastSubmit, b: &LastSubmit) -> bool { + a.queue == b.queue + && a.fence.as_raw() == b.fence.as_raw() + && a.value == b.value + && a.recording == b.recording +} + unsafe impl Send for State {} static STATE: Mutex<Option<State>> = Mutex::new(None); @@ -556,27 +564,54 @@ pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize if !enabled() { return 0; } - let mut g = lock_for_submit(); - let Some(s) = g.as_mut() else { return 0 }; - let mut found = 0; - for &l in lists { - let l = l as usize; - let Some(last) = s.last_submit.get(&l) else { continue }; - if last.fence.GetCompletedValue() >= last.value { - continue; + // A driver query may block or call back into XCL. Keep strong fence snapshots alive, but + // never make GetCompletedValue while the allocator pool's global state is locked. + let mut probes = Vec::with_capacity(lists.len()); + { + let g = lock_for_submit(); + let Some(s) = g.as_ref() else { return 0 }; + for &list in lists { + let list = list as usize; + if let (Some(&lifetime), Some(last)) = (s.list_lifetimes.get(&list), s.last_submit.get(&list)) { + probes.push((list, lifetime, last.clone())); + } } - let same_recording = s.recordings.get(&l).copied().unwrap_or(0) == last.recording; - let same_queue = last.queue == queue as usize; - found += 1; - s.resubmits += 1; - let n = s.resubmits; - if n <= 8 || n.is_power_of_two() { - crate::xlog_warn!( - "D3D12.X: a command list is submitted while its previous submit is still on the GPU ({}, {}; #{n} so far) – the PC does not allow it (debug layer id 553)", - if same_recording { "the same recording" } else { "a new recording" }, - if same_queue { "the same queue" } else { "another queue" }, - ); + } + let incomplete: Vec<_> = probes + .into_iter() + .filter(|(_, _, last)| last.fence.GetCompletedValue() < last.value) + .collect(); + if incomplete.is_empty() { + return 0; + } + let mut warnings = Vec::with_capacity(incomplete.len()); + let found = { + let mut g = lock_for_submit(); + let Some(s) = g.as_mut() else { return 0 }; + let mut found = 0; + for (list, lifetime, observed) in incomplete { + if s.list_lifetimes.get(&list) != Some(&lifetime) + || s.last_submit.get(&list).is_none_or(|current| !same_submit(current, &observed)) + { + continue; + } + let same_recording = s.recordings.get(&list).copied().unwrap_or(0) == observed.recording; + let same_queue = observed.queue == queue as usize; + found += 1; + s.resubmits += 1; + let n = s.resubmits; + if n <= 8 || n.is_power_of_two() { + warnings.push((same_recording, same_queue, n)); + } } + found + }; + for (same_recording, same_queue, n) in warnings { + crate::xlog_warn!( + "D3D12.X: a command list is submitted while its previous submit is still on the GPU ({}, {}; #{n} so far) – the PC does not allow it (debug layer id 553)", + if same_recording { "the same recording" } else { "a new recording" }, + if same_queue { "the same queue" } else { "another queue" }, + ); } found } @@ -584,15 +619,27 @@ pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize /// Whether the GPU has not finished the last submit of the PC list `list` (#1452: it must not be /// submitted again before that; `title_list` records the title's next recording elsewhere). pub fn in_flight(list: usize) -> bool { + let (lifetime, last) = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return false }; + let Some(&lifetime) = s.list_lifetimes.get(&list) else { return false }; + if s.submit_pins.get(&(list, lifetime)).copied().unwrap_or(0) != 0 { + return true; + } + let Some(last) = s.last_submit.get(&list).cloned() else { return false }; + (lifetime, last) + }; + if unsafe { last.fence.GetCompletedValue() } < last.value { + return true; + } + // If the address changed generation, or another submit was reserved/published while the + // driver call ran, fail closed. The caller may spend another list/allocator but cannot reset + // storage that newly became busy. let g = STATE.lock().unwrap(); let Some(s) = g.as_ref() else { return false }; - s.list_lifetimes - .get(&list) - .and_then(|&lifetime| s.submit_pins.get(&(list, lifetime))) - .copied() - .unwrap_or(0) - != 0 - || s.last_submit.get(&list).is_some_and(|l| unsafe { l.fence.GetCompletedValue() } < l.value) + s.list_lifetimes.get(&list) != Some(&lifetime) + || s.submit_pins.get(&(list, lifetime)).copied().unwrap_or(0) != 0 + || s.last_submit.get(&list).is_none_or(|current| !same_submit(current, &last)) } /// Compatibility helper for tests that submit directly instead of using `SubmissionGate`. @@ -773,6 +820,73 @@ mod tests { assert_eq!((remaining, transferred, refs.get(), retained.get()), (1, false, 1, 0)); } + #[test] + fn list_completion_queries_run_outside_allocator_state() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + use std::sync::atomic::{AtomicBool, Ordering}; + + static OUTSIDE: AtomicBool = AtomicBool::new(false); + #[repr(C)] + struct Fence { + vtable: *const usize, + value: Cell<u64>, + refs: Cell<u32>, + } + unsafe extern "system" fn completed(this: *mut c_void) -> u64 { + OUTSIDE.store(STATE.try_lock().is_ok(), Ordering::Relaxed); + (*this.cast::<Fence>()).value.get() + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let f = &*this.cast::<Fence>(); + f.refs.set(f.refs.get() + 1); + f.refs.get() + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let f = &*this.cast::<Fence>(); + f.refs.set(f.refs.get() - 1); + f.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + + const SLOT: usize = size_of::<usize>(); + let mut vtable = [unexpected_call as usize; size_of::<ID3D12Fence_Vtbl>() / SLOT]; + vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + let mut object = Fence { vtable: vtable.as_ptr(), value: Cell::new(0), refs: Cell::new(1) }; + let fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut object).cast()) }; + let (list, lifetime) = (0x7ffe_6a01usize, 17u64); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.list_lifetimes.insert(list, lifetime); + s.recordings.insert(list, 3); + s.last_submit.insert(list, LastSubmit { queue: 0x81, fence: fence.clone(), value: 1, recording: 3 }); + } + + OUTSIDE.store(false, Ordering::Relaxed); + assert_eq!(unsafe { note_resubmits(0x81usize as *mut c_void, &[list as *mut c_void]) }, 1); + assert!(OUTSIDE.load(Ordering::Relaxed), "resubmit polling must not hold STATE"); + OUTSIDE.store(false, Ordering::Relaxed); + assert!(in_flight(list)); + assert!(OUTSIDE.load(Ordering::Relaxed), "in-flight polling must not hold STATE"); + object.value.set(1); + OUTSIDE.store(false, Ordering::Relaxed); + assert!(!in_flight(list)); + assert!(OUTSIDE.load(Ordering::Relaxed), "completed polling must not hold STATE"); + + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.last_submit.remove(&list); + s.recordings.remove(&list); + s.list_lifetimes.remove(&list); + } + drop(fence); + assert_eq!(object.refs.get(), 0); + } + #[test] fn released_namespace_keeps_busy_made_backing_until_retirement() { let (alloc, made) = (0x7ffe_6100usize, 0x7ffe_6200usize); From 0ea9a959b0e100962cab86f1f3430311c7df3006 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:32:31 -0800 Subject: [PATCH 114/265] D3D12.X: retain submitted texture staging after wait failure Texture submission can succeed even when the retirement-fence creation or Signal used to track its lifetime fails. If the fallback queue wait also fails, releasing the command objects and staging resource can free memory that submitted GPU work still references. Drop those objects only after a successful fallback wait; otherwise retain them deliberately. Apply the same rule to synchronous uploads whose native tracking Signal fails. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/texture.rs | 31 ++++++++++++++++++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 6 ++-- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index b68e3d5a6c..944457a32b 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -310,7 +310,11 @@ pub(crate) unsafe fn upload_batch_with_zero_mips( crate::hle::d3d12x::real::native_queue_execute(queue, &list); up.value += 1; let copy_error = |e| format!("texture copy: {e}"); - crate::hle::d3d12x::real::native_queue_signal(queue, &up.fence, up.value).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?; + if let Err(e) = crate::hle::d3d12x::real::native_queue_signal(queue, &up.fence, up.value) { + let signal = copy_error(fence::api_error(dev, "Signal", e)); + drop_after_wait(up, wait(dev, queue))?; + return Err(signal); + } if let Err(e) = fence::wait(&up.fence, up.value, dev, None, 10_000) { // the GPU may still read the upload buffer and run the list: they stay alive (a fresh // uploader next time) – freeing them under the GPU removed the device @@ -599,6 +603,15 @@ pub unsafe fn wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue) -> Result<(), fence::wait(&fence, 1, dev, None, 10_000).map_err(copy_error) } +/// Release GPU submission objects only once a fallback queue wait made that safe. If the wait +/// itself fails, deliberately retain them: submitted work may still reference their resources. +pub(crate) fn drop_after_wait<T>(objects: T, waited: Result<(), String>) -> Result<(), String> { + if waited.is_err() { + std::mem::forget(objects); + } + waited +} + unsafe fn buffer(dev: &ID3D12Device, size: u64) -> Result<ID3D12Resource, String> { let rd = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, @@ -641,6 +654,22 @@ mod tests { use std::collections::HashMap; use windows::Win32::Graphics::Dxgi::Common::*; + #[test] + fn submitted_objects_are_retained_when_the_fallback_wait_fails() { + struct CountDrop<'a>(&'a std::sync::atomic::AtomicUsize); + impl Drop for CountDrop<'_> { + fn drop(&mut self) { + self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + + let drops = std::sync::atomic::AtomicUsize::new(0); + assert!(drop_after_wait(CountDrop(&drops), Ok(())).is_ok()); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 1); + assert_eq!(drop_after_wait(CountDrop(&drops), Err("wait failed".into())).unwrap_err(), "wait failed"); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 1); + } + #[test] fn shared_zero_mip_staging_compacts_and_clears_the_full_span() { // A 1024² R8 texture with five mips, including the driver's row and placement alignment. diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index c082f1acf2..a58fd54201 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1334,8 +1334,7 @@ unsafe fn submit_on_title_queue( g.insert(key, QueueUploads { fence, value: 0, in_flight: std::collections::VecDeque::new(), bytes: 0 }); } Err(e) => { - texture::wait(dev, queue)?; - drop(f); + texture::drop_after_wait(f, texture::wait(dev, queue))?; return Err(e.to_string()); } } @@ -1344,8 +1343,7 @@ unsafe fn submit_on_title_queue( q.value += 1; if let Err(e) = super::real::native_queue_signal(queue, &q.fence, q.value) { q.value -= 1; - texture::wait(dev, queue)?; - drop(f); + texture::drop_after_wait(f, texture::wait(dev, queue))?; return Err(e.to_string()); } q.bytes += f.bytes; From e10df30daf014c0c7ac966ca03bd2d65ca236f5c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 09:54:27 +0300 Subject: [PATCH 115/265] D3D12.X: bypass title hooks for internal queue execution Internal XCL submissions may execute while sparse or VRAM locks are held. If such an ExecuteCommandLists call reaches the title path, its accounting and late-release hooks can re-enter those locks and deadlock. Forward own_work submissions directly through the original native slot inside the queue's ordered lease. This keeps internal queues out of title presentation accounting while preserving queue ordering. Assisted-by: Antigravity (Google Gemini frontier model; exact model unknown) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 80 ++++++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ee20d58685..300cdfd1e0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8450,7 +8450,12 @@ unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lists: *const *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteCommandLists"))); - if n == 0 || lists.is_null() { + // Internal XCL submits (`sparse` uploads/readbacks, `title_textures` uploads, tile zeroing) + // run inside `own_work()` — sometimes while holding internal locks (`sparse::STATE`, + // `vram::PAGES`). Forwarding them through the native slot, in the queue's ordered turn, skips + // `present::note_execute` -> `late_release::drain_known` -> `vram::recycle_ready`, preventing + // re-entrant lock self-deadlocks and keeping internal queues out of `present::QUEUES`. + if n == 0 || lists.is_null() || super::title_textures::is_own_work() { super::queue_submit::with(this as usize, || f(this, n, lists)); stop_if_device_removed(); return; @@ -9166,6 +9171,79 @@ mod queue_tests { assert!(NEWER_LIST_SLOTS.contains(&(129, 127)), "DispatchMesh must map to newer slot #129"); assert!(!NEWER_LIST_SLOTS.iter().any(|&(newer, _)| newer == 128), "newer slot #128 must not map to DispatchMesh"); } + + #[test] + fn own_work_execute_command_lists_bypasses_note_execute_and_drain() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + static CALLED: AtomicUsize = AtomicUsize::new(0); + unsafe extern "system" fn fake_qi(_this: *mut c_void, _iid: *const GUID, out: *mut *mut c_void) -> HRESULT { + if !out.is_null() { + *out = std::ptr::null_mut(); + } + -2147467262 // E_NOINTERFACE + } + unsafe extern "system" fn fake_ref(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn fake_noop(_this: *mut c_void) {} + unsafe extern "system" fn fake_execute(_this: *mut c_void, n: u32, _lists: *const *mut c_void) { + CALLED.fetch_add(n as usize, Ordering::SeqCst); + } + + let iface = layout::find("ID3D12CommandQueue").expect("ID3D12CommandQueue layout"); + let exec_slot = layout::slot(iface, "ExecuteCommandLists").expect("ExecuteCommandLists slot"); + let n = iface.methods.len(); + let mut fake_vtbl = vec![fake_noop as usize; n + 1]; + fake_vtbl[0] = fake_qi as usize; + fake_vtbl[1] = fake_ref as usize; + fake_vtbl[2] = fake_ref as usize; + fake_vtbl[exec_slot] = fake_execute as usize; + fake_vtbl[n] = 0; + let orig = fake_vtbl.as_ptr() as usize; + + struct ClassCleanup(usize); + impl Drop for ClassCleanup { + fn drop(&mut self) { + let mut exts = Vec::new(); + CLASSES.lock().unwrap().retain(|c| { + if c.orig == self.0 { + exts.push(c.ext); + false + } else { + true + } + }); + if let Some(set) = EXTS.lock().unwrap().as_mut() { + for e in exts { + set.remove(&e); + } + } + } + } + let _cleanup = ClassCleanup(orig); + + let mut obj = orig; + let obj_ptr = &mut obj as *mut usize as *mut c_void; + struct LeaseCleanup(usize); + impl Drop for LeaseCleanup { + fn drop(&mut self) { + crate::hle::d3d12x::queue_submit::release(self.0, || 0); + } + } + let _lease_cleanup = LeaseCleanup(obj_ptr as usize); + let ext = unsafe { class_for(obj_ptr, orig, Kind::CommandQueue) }; + unsafe { *(obj_ptr as *mut usize) = ext; } + + let mut dummy_list = std::ptr::null_mut::<c_void>(); + let activity_before = crate::hle::d3d12x::present::activity(); + let before_called = CALLED.load(Ordering::SeqCst); + unsafe { + crate::hle::d3d12x::title_textures::own_work(|| { + q_execute_command_lists(obj_ptr, 1, &mut dummy_list as *mut *mut c_void); + }); + } + assert_eq!(CALLED.load(Ordering::SeqCst), before_called + 1, "original ExecuteCommandLists must still run"); + assert_eq!(crate::hle::d3d12x::present::activity(), activity_before, "own_work submit must bypass present::note_execute"); + } } #[cfg(test)] From fee5d1b6cefa6a4e31e3592b57ec7fcbb9aa5755 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:38:26 -0800 Subject: [PATCH 116/265] Recompiler: fold unobserved EXEC selects in direct DXIL Guest VGPR writes preserve inactive lanes as select(exec, new, old). Lane-local operations whose values are ultimately observed only under the same condition cannot observe the preserved arm, so read through it and let DCE remove the resulting dead selects. Use a conservative observation lattice: phis, memory, atomics, integer division, wave/quad operations, derivatives, and unknown calls observe all lanes. Keep an opt-out and before/after GPU parity coverage for wave32, split wave64, inactive lanes, and cross-lane barriers. Assisted-by: Claude Code (Claude Opus 5.5) Assisted-by: Codex (GPT-5.6-sol) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- crates/xcl/src/gpu/dxil/kernel.rs | 8 +- crates/xcl/src/gpu/dxil/mod.rs | 2 + crates/xcl/src/gpu/dxil/module.rs | 2 + crates/xcl/src/gpu/dxil/module/opt.rs | 168 +++++++++++++++++++++++- crates/xcl/src/gpu/dxil/select_tests.rs | 95 ++++++++++++++ 5 files changed, 273 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/gpu/dxil/select_tests.rs diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index c97248189a..f05561086b 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -159,10 +159,16 @@ fn translate_entry( // SSA construction recurses along the CFG (one level per guarded memory access between // a register's definition and its use): a thread with a large stack for big programs let code = code.to_vec(); + #[cfg(test)] + let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get()); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) - .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables)) + .spawn(move || { + #[cfg(test)] + super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold)); + translate_on_this_thread(&code, o, entry, compact, nest, tables) + }) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index a0ec94583f..9540026ed1 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -57,3 +57,5 @@ mod msaa_tests; mod round_tests; #[cfg(test)] mod geometry_tests; +#[cfg(test)] +mod select_tests; diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 23345b83a1..b9712d4b57 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -16,6 +16,8 @@ use std::collections::HashMap; use super::bitstream::{signed, BitWriter}; mod opt; +#[cfg(test)] +pub(crate) use opt::NO_SELECT_FOLD; pub(super) mod split; // ---------------------------------------------------------------- types diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 0210f5e74a..ebe4338a6d 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -68,6 +68,12 @@ impl Op { } } +#[cfg(test)] +thread_local! { + /// Tests can compare emitted code with the guarded-select fold disabled. + pub(crate) static NO_SELECT_FOLD: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + /// How an instruction may be merged with an identical one. #[derive(PartialEq)] enum Cse { @@ -610,7 +616,7 @@ impl Module { /// Cleans up the entry function (see the module docs of `opt`). Values /// keep their identities; replaced ones simply lose their uses. /// - /// `XCL_DXIL_NO_OPT=phi,cse,dce,merge` (any subset, or `all`) skips passes, for bisecting. + /// `XCL_DXIL_NO_OPT=phi,cse,select,dce,merge` (any subset, or `all`) skips passes, for bisecting. pub fn optimize(&mut self) { let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); @@ -788,6 +794,14 @@ impl Module { } } + #[cfg(test)] + let skip_select = NO_SELECT_FOLD.with(|c| c.get()); + #[cfg(not(test))] + let skip_select = false; + if !skip("select") && !skip_select { + self.fold_guarded_selects(&order, &repl); + } + // dead instructions: live = side effects, terminators and their operands, transitively let (i64t, f64t) = self.existing_i64_f64(); let wide: Vec<Ty> = i64t.into_iter().chain(f64t).collect(); @@ -890,6 +904,115 @@ impl Module { } } + /// Whether `op` computes each lane from only that lane's operands. Operations whose + /// evaluation observes other lanes, memory, or undefined integer division operands are + /// deliberately excluded. + fn lane_local(&self, op: &Op, ty: Ty) -> bool { + match op { + Op::Bin(BinOp::UDiv | BinOp::URem, ..) => false, + Op::Bin(BinOp::SDiv | BinOp::SRem, ..) => self.is_float(ty), + Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) => true, + Op::Call(f, args) => { + let d = &self.funcs[*f as usize]; + d.attrs == FnAttrs::ReadNone + && d.name.starts_with("dx.op.") + && args.first().and_then(|&a| self.const_u64(a)).is_some_and(|id| matches!(id, 6..=56 | 101 | 102 | 124..=132)) + } + _ => false, + } + } + + /// Reads through `select(c, current, old)` only where the value is ultimately observed + /// under the same `c`. This removes guest-EXEC preservation arms from chains of lane-local + /// operations without changing inactive lanes. Phis and non-lane-local operations observe + /// all lanes and stop the fold. + fn fold_guarded_selects(&mut self, order: &[u32], repl: &[Option<Value>]) { + #[derive(Clone, Copy, PartialEq)] + enum Seen { + Unused, + Where(Value), + All, + } + fn meet(s: &mut Seen, by: Seen) { + *s = match (*s, by) { + (x, Seen::Unused) => x, + (Seen::Unused, y) => y, + (Seen::Where(a), Seen::Where(b)) if a == b => Seen::Where(a), + _ => Seen::All, + } + } + + let live = |i: u32| repl[i as usize].is_none(); + let mut seen = vec![Seen::Unused; self.insts.len()]; + for &b in order { + for &i in &self.blocks[b as usize] { + if let (true, Op::Phi(inc)) = (live(i), &self.insts[i as usize].op) { + for &(v, _) in inc { + if let Value::Inst(j) = v { + seen[j as usize] = Seen::All; + } + } + } + } + } + for &b in order.iter().rev() { + for &i in self.blocks[b as usize].iter().rev() { + if !live(i) { + continue; + } + let (op, ty) = (&self.insts[i as usize].op, self.insts[i as usize].ty); + if matches!(op, Op::Phi(_)) { + continue; + } + let me = if self.lane_local(op, ty) { seen[i as usize] } else { Seen::All }; + if me == Seen::Unused { + continue; + } + let mut by = |v: Value, s: Seen| { + if let Value::Inst(j) = v { + meet(&mut seen[j as usize], s); + } + }; + match *op { + Op::Select(c, a, b) => { + by(c, me); + by(a, Seen::Where(c)); + by(b, me); + } + _ => op.for_each_operand(|v| by(v, me)), + } + } + } + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k]; + let (op, ty) = (&self.insts[i as usize].op, self.insts[i as usize].ty); + if !live(i) || seen[i as usize] == Seen::Unused || !self.lane_local(op, ty) { + continue; + } + let me = seen[i as usize]; + let outer_condition = if let Op::Select(c, ..) = *op { Some(c) } else { None }; + let mut op = op.clone(); + let mut pos = 0; + op.map_operands(|mut v| { + let at = pos; + pos += 1; + while let Value::Inst(j) = v { + let Op::Select(c, t, f) = self.insts[j as usize].op else { break }; + v = match (outer_condition, at) { + (Some(outer), 1) if outer == c => t, + (Some(outer), 2) if outer == c => f, + _ if me == Seen::Where(c) => t, + _ => break, + }; + } + v + }); + self.insts[i as usize].op = op; + } + } + } + /// Simplifies the CFG to a fixed point: /// 1. Collapses degenerate `CondBr(_, t, t)` and `Switch` cases matching the default target. /// 2. Bypasses empty trampoline blocks (`[Br(t)]`) whenever `t`'s phis allow it. @@ -1584,6 +1707,48 @@ mod tests { let order: Vec<u32> = m.block_layout().0.into_iter().map(|b| b as u32).collect(); assert!(m.uses_well_formed(&order)); } + #[test] + fn guarded_selects_fold_only_for_same_condition_lane_local_uses() { + let mut m = Module::new(); + m.define_entry("main"); + let entry = m.entry_block(); + m.set_block(entry); + + let void = m.void(); + let i32t = m.i32(); + let src_ty = m.func_ty(i32t, &[]); + let src = m.declare("dx.op.waveGetLaneIndex", src_ty, FnAttrs::ReadNone); + let sink_ty = m.func_ty(void, &[i32t]); + let sink = m.declare("dx.op.storeOutput.i32", sink_ty, FnAttrs::NoUnwind); + + let x = m.call(src, &[]); + let (one, three, five, sentinel) = (m.i32c(1), m.i32c(3), m.i32c(5), m.i32c(0xA5A5_5A5A)); + let exec = m.cmp(Pred::ULt, x, five); + let old = m.bin(BinOp::Xor, x, sentinel); + let current = m.bin(BinOp::Add, x, one); + let saved = m.select(exec, current, old); + let product = m.bin(BinOp::Mul, saved, three); + let guarded = m.select(exec, product, saved); + + // A second preserved value is read by an all-lane observer and must remain intact. + let must_stay = m.select(exec, current, x); + let all_lane_use = m.bin(BinOp::Sub, must_stay, one); + m.call(sink, &[guarded]); + m.call(sink, &[all_lane_use]); + m.ret(); + m.optimize(); + + let Value::Inst(guarded_i) = guarded else { panic!() }; + let Value::Inst(product_i) = product else { panic!() }; + assert!(matches!(m.insts[guarded_i as usize].op, Op::Select(c, t, f) if c == exec && t == product && f == old)); + assert!(matches!(m.insts[product_i as usize].op, Op::Bin(BinOp::Mul, a, b, 0) if (a, b) == (current, three) || (a, b) == (three, current))); + let body = &m.blocks[entry.0 as usize]; + let present = |v: Value| matches!(v, Value::Inst(i) if body.contains(&i)); + assert!(!present(saved), "the EXEC-preservation select should have no uses"); + assert!(present(must_stay), "an all-lane use must retain its preservation select"); + let order: Vec<u32> = m.block_layout().0.into_iter().map(|b| b as u32).collect(); + assert!(m.uses_well_formed(&order)); + } } #[cfg(test)] @@ -1755,4 +1920,5 @@ mod int_minmax_tests { assert_eq!(r.vgpr[l][5], a.min(b), "med3_u32(v0, 0, v1) lane {l}"); } } + } diff --git a/crates/xcl/src/gpu/dxil/select_tests.rs b/crates/xcl/src/gpu/dxil/select_tests.rs new file mode 100644 index 0000000000..2d9c1d3663 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/select_tests.rs @@ -0,0 +1,95 @@ +//! GPU equivalence for the guarded-select fold, including inactive lanes. + +use super::kernel::{translate, KernelOptions}; +use super::module::NO_SELECT_FOLD; +use crate::gpu::rdna2::encode; +use crate::gpu::recomp::runner::{self, KernelState}; + +const V: u64 = 256; + +fn program(list: &[(&str, &str, &[(&str, u64)])]) -> Vec<u8> { + let mut code = Vec::new(); + for (name, encoding, fields) in list { + code.extend(encode(name, encoding, fields, None).unwrap_or_else(|e| panic!("{name}: {e}"))); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + code +} + +fn translate_with_fold(code: &[u8], options: KernelOptions, enabled: bool) -> Vec<u8> { + NO_SELECT_FOLD.with(|c| c.set(!enabled)); + let result = translate(code, options); + NO_SELECT_FOLD.with(|c| c.set(false)); + result.unwrap_or_else(|e| panic!("translate (select fold {enabled}): {e}")) +} + +#[test] +fn gpu_guarded_select_fold_preserves_inactive_lanes() { + match (runner::adapter(), runner::wave64_programs_supported()) { + (Ok(_), Ok(true)) => {} + (adapter, _) => return runner::skip_test(if adapter.is_err() { "no GPU" } else { "no wave64" }), + } + let code = program(&[ + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 0)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V), ("VSRC1", 1)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 2)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 4), ("SRC1", V + 3), ("SRC2", V + 4)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 5), ("VSRC1", 4)]), + ("V_CMP_GT_F32", "ENC_VOPC", &[("SRC0", V + 4), ("VSRC1", 5)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 4), ("VSRC1", 5)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 131)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 6), ("SRC1", 137)]), + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 2)]), + ("V_SUB_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 6)]), + ("V_MAX_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 4)]), + ("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 9), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 4), ("SRC1", 133)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 6), ("VSRC1", 6)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 4), ("VSRC1", 6)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 7), ("VSRC1", 8)]), + ]); + const EDGE: [u32; 12] = [0x7FC0_1234, 0, 0x8000_0000, 0x7F80_0000, 0xFF80_0000, 1, 0x807F_FFFF, 0x3FC0_0000, 0xC000_0000, 0x3F80_0000, 0x4120_0000, 0xBE80_0000]; + let mut state = KernelState::default(); + let mut random = 0x9E37_79B9_7F4A_7C15u64; + for (lane, regs) in state.vgpr.iter_mut().enumerate() { + for word in regs.iter_mut().take(4) { + random ^= random << 13; + random ^= random >> 7; + random ^= random << 17; + *word = if random % 3 == 0 { random as u32 } else { EDGE[(random >> 8) as usize % EDGE.len()] }; + } + for (reg, word) in regs.iter_mut().enumerate().skip(4).take(8) { + *word = 0xA000_0000 | (lane as u32) << 8 | reg as u32; + } + } + (state.sgpr[0], state.sgpr[1]) = (0xF0F0_5A3C, 0x0FF0_C3A5); + (state.sgpr[2], state.sgpr[3]) = (0x3333_FF0F, 0xFFFF_3333); + + let mut ran = 0; + for (wave64, split) in [(false, false), (true, true), (true, false)] { + if wave64 && !split && runner::wave64_supported() != Ok(true) { + continue; + } + let options = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let (before, after) = (translate_with_fold(&code, options, false), translate_with_fold(&code, options, true)); + assert!(after.len() < before.len(), "wave64 {wave64} split {split}: nothing folded ({} -> {} B)", before.len(), after.len()); + let a = runner::run(&before, &state, &[]).expect("GPU run before fold"); + let b = runner::run(&after, &state, &[]).expect("GPU run after fold"); + let lanes = if wave64 { 64 } else { 32 }; + for lane in 0..lanes { + assert_eq!(a.vgpr[lane][..12], b.vgpr[lane][..12], "wave64 {wave64} split {split}: lane {lane}"); + let active = (state.sgpr[lane / 32] >> (lane % 32)) & 1 != 0; + if !active { + for reg in [4, 5, 7, 8] { + assert_eq!(b.vgpr[lane][reg], state.vgpr[lane][reg], "wave64 {wave64} split {split}: inactive lane {lane} v{reg}"); + } + } + } + assert_eq!(a.sgpr, b.sgpr, "wave64 {wave64} split {split}: SGPRs"); + assert_eq!(a.scc, b.scc, "wave64 {wave64} split {split}: SCC"); + ran += 1; + } + assert!(ran >= 2); +} From 0d4d445ef6245fdeddd6f3c1b0ded90446c61787 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:39:45 -0800 Subject: [PATCH 117/265] D3D12.X: signal allocator retirement fences outside global state Pending submit completion created fences and entered the queue driver while holding the allocator pool's global lock. That serialized unrelated queues and made driver callbacks capable of deadlocking allocator operations. Use an Arc-owned per-queue marker with monotonic reentrant value reservations. Create and Signal outside global state, then publish marks only after exact marker revalidation. Failed signals and replaced queue generations retain their submit pins fail-closed. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 246 +++++++++++++++++++++--- 1 file changed, 220 insertions(+), 26 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index a0f0c73f61..67a1f448fe 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -13,11 +13,11 @@ //! put aside earlier whose lists have all been reset since and whose submits are done, or a new //! one. A list reset on the title's allocator records on the PC allocator in use. A list holds //! one recording, so no more allocators are put aside than there are lists. -use std::collections::{HashMap, HashSet}; +use std::collections::{hash_map::Entry, HashMap, HashSet}; use std::ffi::c_void; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -54,7 +54,7 @@ struct State { of_list: HashMap<usize, usize>, /// title allocator → the type of the lists on it types: HashMap<usize, i32>, - fences: HashMap<usize, (ID3D12Fence, u64)>, + fences: HashMap<usize, Arc<QueueFence>>, made: u64, swaps: u64, /// PC list → its last submit (queue, fence, value after it, recording number then) @@ -77,6 +77,17 @@ struct LastSubmit { recording: u64, } +struct QueueFence { + fence: ID3D12Fence, + next_value: AtomicU64, +} + +impl QueueFence { + fn new(fence: ID3D12Fence) -> Self { + Self { fence, next_value: AtomicU64::new(0) } + } +} + fn same_submit(a: &LastSubmit, b: &LastSubmit) -> bool { a.queue == b.queue && a.fence.as_raw() == b.fence.as_raw() @@ -92,13 +103,11 @@ static STATE: Mutex<Option<State>> = Mutex::new(None); /// called only after its retirement mark completes; every removed COM fence drops unlocked. pub(super) fn forget_queue(id: super::present::QueueId) { let queue = id.raw(); - let gone = { + let (marker, gone) = { let mut state = STATE.lock().unwrap(); let Some(state) = state.as_mut() else { return }; let mut gone = Vec::new(); - if let Some((fence, _)) = state.fences.remove(&queue) { - gone.push(fence); - } + let marker = state.fences.remove(&queue); for backing in state.backings.values_mut() { if let Some((fence, _)) = backing.marks.remove(&queue) { gone.push(fence); @@ -110,8 +119,9 @@ pub(super) fn forget_queue(id: super::present::QueueId) { gone.push(submit.fence); } } - gone + (marker, gone) }; + drop(marker); drop(gone); } @@ -380,31 +390,75 @@ impl Drop for BeginSubmit { impl PendingSubmit { /// Associate the captured submit with the queue's existing retirement fence. `false` leaves /// all reservations permanently pinned: execution may have happened but cannot be retired. - pub(super) unsafe fn finish(mut self, queue: *mut c_void) -> bool { + pub(super) unsafe fn finish(self, queue: *mut c_void) -> bool { if self.entries.is_empty() { return true; } - let mut g = lock_for_submit(); - let Some(s) = g.as_mut() else { return false }; let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return false }; let key = queue as usize; - if !s.fences.contains_key(&key) { - let mut dev: Option<ID3D12Device> = None; - let Some(fence) = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok()) else { - return false; - }; - s.fences.insert(key, (fence, 0)); - } - let (fence, value) = { - let (fence, value) = s.fences.get_mut(&key).unwrap(); - SUBMIT.signal_attempts.fetch_add(1, Ordering::Relaxed); - if super::real::native_queue_signal(q, &*fence, *value + 1).is_err() { - SUBMIT.signal_failures.fetch_add(1, Ordering::Relaxed); - return false; + super::queue_submit::with(key, || self.finish_with_queue_ops( + key, + || { + let mut dev: Option<ID3D12Device> = None; + q.GetDevice(&mut dev).ok()?; + dev?.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok() + }, + |fence, value| super::real::native_queue_signal(q, fence, value).is_ok(), + )) + } + + /// The queue turn excludes another thread while the state lock is released around driver + /// calls. An `Arc` keeps the exact marker alive; replacement means the queue generation was + /// invalidated, so the submitted work deliberately remains pinned. + fn finish_with_queue_ops( + mut self, + key: usize, + create: impl FnOnce() -> Option<ID3D12Fence>, + signal: impl FnOnce(&ID3D12Fence, u64) -> bool, + ) -> bool { + let marker = { + let g = lock_for_submit(); + let Some(s) = g.as_ref() else { return false }; + s.fences.get(&key).cloned() + }; + let marker = match marker { + Some(marker) => marker, + None => { + let Some(fence) = create() else { return false }; + let made = Arc::new(QueueFence::new(fence)); + let mut g = lock_for_submit(); + let Some(s) = g.as_mut() else { return false }; + let (marker, unused) = match s.fences.entry(key) { + Entry::Occupied(entry) => (Arc::clone(entry.get()), Some(made)), + Entry::Vacant(entry) => { + let marker = Arc::clone(&made); + entry.insert(made); + (marker, None) + } + }; + drop(g); + drop(unused); + marker } - *value += 1; - (fence.clone(), *value) }; + // Reserve before entering the driver. The queue lease excludes another thread, while an + // atomic reservation lets intentional same-thread re-entry take a distinct later value. + // A failed Signal burns its value; its submit remains pinned and a gap is harmless. + let Ok(value) = marker.next_value.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| v.checked_add(1)) else { + return false; + }; + let value = value + 1; + SUBMIT.signal_attempts.fetch_add(1, Ordering::Relaxed); + if !signal(&marker.fence, value) { + SUBMIT.signal_failures.fetch_add(1, Ordering::Relaxed); + return false; + } + let fence = marker.fence.clone(); + let mut g = lock_for_submit(); + let Some(s) = g.as_mut() else { return false }; + if s.fences.get(&key).is_none_or(|current| !Arc::ptr_eq(current, &marker)) { + return false; + } let backing_mark_writes = record_submit(s, &self.entries, key, &fence, value); SUBMIT.lists_marked.fetch_add(self.entries.len() as u64, Ordering::Relaxed); SUBMIT.backing_mark_writes.fetch_add(backing_mark_writes, Ordering::Relaxed); @@ -887,6 +941,146 @@ mod tests { assert_eq!(object.refs.get(), 0); } + #[test] + fn submit_marking_calls_out_unlocked_and_revalidates_the_queue_marker() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + + #[repr(C)] + struct Fence { + vtable: *const usize, + refs: Cell<u32>, + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let f = &*this.cast::<Fence>(); + f.refs.set(f.refs.get() + 1); + f.refs.get() + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let f = &*this.cast::<Fence>(); + f.refs.set(f.refs.get() - 1); + f.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + + const SLOT: usize = size_of::<usize>(); + let mut vtable = [unexpected_call as usize; size_of::<ID3D12Fence_Vtbl>() / SLOT]; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + let mut first_object = Fence { vtable: vtable.as_ptr(), refs: Cell::new(1) }; + let mut old_object = Fence { vtable: vtable.as_ptr(), refs: Cell::new(1) }; + let mut new_object = Fence { vtable: vtable.as_ptr(), refs: Cell::new(1) }; + let first_fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut first_object).cast()) }; + let old_fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut old_object).cast()) }; + let new_fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut new_object).cast()) }; + + let (first_list, first_queue) = (0x7ffe_6b01usize, 0x7ffe_6b02usize); + let pending = begin_submit(&[first_list as *mut c_void]).unwrap().execution_possible(); + assert!(pending.finish_with_queue_ops( + first_queue, + || { + assert!(STATE.try_lock().is_ok(), "fence creation must run outside STATE"); + Some(first_fence.clone()) + }, + |_, value| { + assert!(STATE.try_lock().is_ok(), "queue Signal must run outside STATE"); + assert_eq!(value, 1); + true + }, + )); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.last_submit[&first_list].value, 1); + assert!(!s.submit_pins.contains_key(&(first_list, s.list_lifetimes[&first_list]))); + } + + let failed_list = 0x7ffe_6b05usize; + let failed = begin_submit(&[failed_list as *mut c_void]).unwrap().execution_possible(); + assert!(!failed.finish_with_queue_ops(first_queue, || unreachable!(), |_, value| { + assert_eq!(value, 2); + false + })); + let retried = begin_submit(&[failed_list as *mut c_void]).unwrap().execution_possible(); + assert!(retried.finish_with_queue_ops(first_queue, || unreachable!(), |_, value| { + assert_eq!(value, 3, "a failed Signal leaves a gap instead of colliding with a retry"); + true + })); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + let lifetime = s.list_lifetimes[&failed_list]; + assert_eq!(s.submit_pins.get(&(failed_list, lifetime)), Some(&1), "the failed submit stays pinned"); + assert_eq!(s.last_submit[&failed_list].value, 3); + } + + let (outer_list, inner_list) = (0x7ffe_6b06usize, 0x7ffe_6b07usize); + let outer = begin_submit(&[outer_list as *mut c_void]).unwrap().execution_possible(); + let inner = begin_submit(&[inner_list as *mut c_void]).unwrap().execution_possible(); + assert!(super::super::queue_submit::with(first_queue, || { + outer.finish_with_queue_ops(first_queue, || unreachable!(), |_, outer_value| { + assert_eq!(outer_value, 4); + assert!(super::super::queue_submit::with(first_queue, || { + inner.finish_with_queue_ops(first_queue, || unreachable!(), |_, inner_value| { + assert_eq!(inner_value, 5, "same-thread re-entry reserves a distinct value"); + true + }) + })); + true + }) + })); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!((s.last_submit[&outer_list].value, s.last_submit[&inner_list].value), (4, 5)); + } + + let (reused_list, reused_queue) = (0x7ffe_6b03usize, 0x7ffe_6b04usize); + let pending = begin_submit(&[reused_list as *mut c_void]).unwrap().execution_possible(); + assert!(!pending.finish_with_queue_ops( + reused_queue, + || Some(old_fence.clone()), + |_, value| { + assert!(STATE.try_lock().is_ok(), "queue invalidation can run while Signal is outside STATE"); + assert_eq!(value, 1); + STATE.lock().unwrap().as_mut().unwrap().fences.insert( + reused_queue, + Arc::new(QueueFence::new(new_fence.clone())), + ); + true + }, + ), "a replacement raw-address generation must not receive the old submit's mark"); + let (markers, submits) = { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(!s.last_submit.contains_key(&reused_list)); + let lifetime = s.list_lifetimes[&reused_list]; + assert_eq!(s.submit_pins.get(&(reused_list, lifetime)), Some(&1)); + assert_eq!(s.fences[&reused_queue].fence.as_raw(), new_fence.as_raw()); + s.submit_pins.remove(&(reused_list, lifetime)); + s.list_lifetimes.remove(&reused_list); + let markers = [s.fences.remove(&first_queue), s.fences.remove(&reused_queue)]; + let submits = [ + s.last_submit.remove(&first_list), + s.last_submit.remove(&failed_list), + s.last_submit.remove(&outer_list), + s.last_submit.remove(&inner_list), + ]; + let failed_lifetime = s.list_lifetimes.remove(&failed_list).unwrap(); + s.submit_pins.remove(&(failed_list, failed_lifetime)); + s.list_lifetimes.remove(&first_list); + s.list_lifetimes.remove(&outer_list); + s.list_lifetimes.remove(&inner_list); + (markers, submits) + }; + drop(markers); + drop(submits); + drop(first_fence); + drop(old_fence); + drop(new_fence); + assert_eq!((first_object.refs.get(), old_object.refs.get(), new_object.refs.get()), (0, 0, 0)); + } + #[test] fn released_namespace_keeps_busy_made_backing_until_retirement() { let (alloc, made) = (0x7ffe_6100usize, 0x7ffe_6200usize); From 4cc28d403d517ea6a1f8b70d05adbd02abe44842 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:43:47 -0800 Subject: [PATCH 118/265] D3D12.X: publish GPU texture writes at title fence completion GPU-written title textures previously remained detached from their CPU memory view. Before a title signals the exact queue that wrote supported subresources, build immutable readback plans, validate and reserve their writer epochs in that queue turn, and enqueue the readbacks ahead of the native title-fence signal. Fence completion stays hidden until completed tickets are reverse-tiled into committed writable title pages. Replaced epochs, resource generations, partial submission failures, and queue reuse are discarded or retained fail-closed. Cross-queue writes remain pending for their own synchronized writer queue. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 2 +- crates/xcl/src/hle/d3d12x/fence_x.rs | 9 +- crates/xcl/src/hle/d3d12x/list_x.rs | 2 +- crates/xcl/src/hle/d3d12x/real.rs | 74 ++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 312 +++++++++++++++++++- 5 files changed, 377 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index e28d3ea86c..78c357ed09 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif | **Pipelines** | ✅ | PSOs from console shaders: VS+PS, CS, MS+PS, VS+GS+PS; root signature with the shaders' static samplers; non-blocking creation – a pipeline whose shaders are not compiled yet gets a stand-in at once and is built in the background | GPU tests drawing the game's own VS / PS pairs, also built in the background | | **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies) | the game's BVH builder and FSR 4 record and run through XCL | | **D3D12.X graphics** | ✅ | device, resources and heaps (also placed in title memory), pipelines; the title's graphics command lists – draws, indirect draws, graphics root arguments, barriers, copies, clears – and command lists recorded by console code, replayed; `PresentX` and frame pacing into an XCL window | Minecraft Preview plays its worlds (millions of draws, none skipped); Fortnite and XDefiant draw their screens | -| **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures | 909 / 912 retail textures exact (the 3 volume LUTs decode smooth); GPU upload bit exact | +| **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures; supported GPU-written title subresources copy back before their writer queue's title fence becomes visible | 909 / 912 retail textures exact (the 3 volume LUTs decode smooth); GPU upload bit exact | | **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders | GPU traversal = brute force reference; the game's builder output checked on the GPU | | **Upscaling** | ✅ | the game's AMD FSR 4 console DLL (`amd_fidelityfx_upscaler_xbox.dll`): context, the 29 pipelines in the console driver's own container (FSPX) translated, a frame's 20 passes recorded and run on the GPU | end-to-end with the real DLL: a 1280×720 → 1920×1080 frame on an RX 9070, the input's gradient in the output | diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs index f6ca932d71..babd5744fb 100644 --- a/crates/xcl/src/hle/d3d12x/fence_x.rs +++ b/crates/xcl/src/hle/d3d12x/fence_x.rs @@ -56,7 +56,9 @@ impl FenceTable { return; } if let Some(v) = unsafe { borrowed(fence, |f| f.GetCompletedValue()) } { - mirror.cell.0.store(v, Ordering::Release); + if super::title_textures::complete_fence_downloads(fence, v) { + mirror.cell.0.store(v, Ordering::Release); + } } } @@ -153,6 +155,7 @@ fn event() -> usize { let e = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) as usize; let spawned = std::thread::Builder::new().name("xcl-fences".into()).spawn(move || loop { th::WaitForSingleObject(e as _, th::INFINITE); + super::title_textures::poll_fence_downloads(); table().refresh(); }); if let Err(err) = spawned { @@ -162,6 +165,10 @@ fn event() -> usize { }) } +pub(super) fn wake_event() -> HANDLE { + HANDLE(event() as *mut c_void) +} + unsafe fn borrowed<R>(fence: usize, f: impl FnOnce(&ID3D12Fence) -> R) -> Option<R> { let p = fence as *mut c_void; ID3D12Fence::from_raw_borrowed(&p).map(f) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 8836772dd4..99c4f240ff 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1141,7 +1141,7 @@ fn new_queue_id(raw: usize) -> super::title_textures::WriterQueueId { super::title_textures::WriterQueueId { raw, generation } } -fn queue_identity(raw: usize) -> Option<super::title_textures::WriterQueueId> { +pub(super) fn queue_identity(raw: usize) -> Option<super::title_textures::WriterQueueId> { LIVE_QUEUES.lock().unwrap().iter().find(|q| q.queue == raw).map(|q| q.id) } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9d9f3ffcb7..7a4f959bc9 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -680,6 +680,14 @@ pub(crate) unsafe fn native_queue_wait(queue: &ID3D12CommandQueue, fence: &ID3D1 }) } +pub(crate) unsafe fn native_fence_completed(fence: &ID3D12Fence) -> u64 { + let raw = fence.as_raw(); + let slot = std::mem::offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / std::mem::size_of::<usize>(); + type F = unsafe extern "system" fn(*mut c_void) -> u64; + let f: F = std::mem::transmute(if is_ext(vt(raw) as usize) { orig_fn(raw, slot) } else { *vt(raw).add(slot) }); + f(raw) +} + #[cfg(test)] pub(super) fn register_test_queue_vtable(ext: usize, add: bool) { let mut tables = EXTS.lock().unwrap(); @@ -3009,7 +3017,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { Kind::PipelineState => v.push(("Release", pso_release as usize)), Kind::DescriptorHeap => v.push(("Release", heap_release as usize)), Kind::Heap => v.push(("Release", mem_heap_release as usize)), - Kind::Fence => v.push(("Signal", fence_signal as usize)), + Kind::Fence => v.extend_from_slice(&[("GetCompletedValue", fence_completed as usize), ("Signal", fence_signal as usize)]), _ => {} } v @@ -8190,21 +8198,40 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a let older = if shifted && slot >= 16 { slot - 2 } else if shifted { usize::MAX } else { slot }; let pc = |s: usize| orig_fn(this, s); match older { - // Signal / Wait take a fence: anything else is not one of them - 14 | 15 if is_fence(a1) => super::queue_submit::with(this as usize, || { - if older == 14 { + // Signal takes a fence: prepare outside the turn, then validate/insert atomically with it. + 14 if is_fence(a1) => loop { + let prepared = super::title_textures::prepare_downloads(this); + let attempt = super::queue_submit::with(this as usize, || { + let downloads = match super::title_textures::submit_prepared_downloads(this, prepared) { + Ok(downloads) => downloads, + Err(super::title_textures::SubmitDownloadsError::Stale) => return Err(None), + Err(super::title_textures::SubmitDownloadsError::Failed(error)) => return Err(Some(error)), + }; super::list_x::break_cycles_before_title_signal(this as usize, a1, a2 as u64); - } - let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(if older == 14 { PC_SIGNAL } else { PC_WAIT })); - let hr = f(this, a1, a2); - if hr >= 0 { - if older == 14 { + super::title_textures::tie_downloads(a1 as *mut c_void, a2 as u64, downloads); + let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(PC_SIGNAL)); + let hr = f(this, a1, a2); + if hr >= 0 { super::fence_x::note_queue_signal(a1, a2 as u64); super::list_x::note_title_queue_signal(this as usize, a1, a2 as u64); - } else { - super::fence_x::note_queue_wait(a1, a2 as u64); - super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); } + Ok(hr as u32 as usize) + }); + match attempt { + Ok(hr) => break hr, + Err(None) => continue, + Err(Some(error)) => { + crate::xlog_warn!("D3D12.X: {error}; title queue Signal not submitted"); + break crate::util::E_FAIL as u32 as usize; + } + } + }, + 15 if is_fence(a1) => super::queue_submit::with(this as usize, || { + let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(PC_WAIT)); + let hr = f(this, a1, a2); + if hr >= 0 { + super::fence_x::note_queue_wait(a1, a2 as u64); + super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); } hr as u32 as usize }), @@ -8287,22 +8314,39 @@ queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, /// nothing left Fortnite's render fences pending: its render thread waited, textures were /// never released, and the garbage collector ended the game after 10 s.) unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, value: u64, _flags: u32) -> HRESULT { - super::queue_submit::with(this as usize, || q_signal_x_serialized(this, fence, value)) + loop { + let prepared = super::title_textures::prepare_downloads(this); + match super::queue_submit::with(this as usize, || q_signal_x_serialized(this, fence, value, prepared)) { + Ok(hr) => return hr, + Err(super::title_textures::SubmitDownloadsError::Stale) => continue, + Err(super::title_textures::SubmitDownloadsError::Failed(error)) => { + crate::xlog_warn!("D3D12.X: {error}; title queue SignalX not submitted"); + return crate::util::E_FAIL; + } + } + } } -unsafe fn q_signal_x_serialized(this: *mut c_void, fence: *mut c_void, value: u64) -> HRESULT { +unsafe fn q_signal_x_serialized(this: *mut c_void, fence: *mut c_void, value: u64, prepared: super::title_textures::PreparedDownloads) -> Result<HRESULT, super::title_textures::SubmitDownloadsError> { const PC_SIGNAL: usize = 14; + let downloads = super::title_textures::submit_prepared_downloads(this, prepared)?; super::list_x::break_cycles_before_title_signal(this as usize, fence as usize, value); + super::title_textures::tie_downloads(fence, value, downloads); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, PC_SIGNAL)); let hr = f(this, fence, value); if hr >= 0 { super::fence_x::note_queue_signal(fence as usize, value); super::list_x::note_title_queue_signal(this as usize, fence as usize, value); } - hr + Ok(hr) } /// Fence::Signal (CPU) +unsafe extern "system" fn fence_completed(this: *mut c_void) -> u64 { + let f: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(orig_fn(this, slot_of(this, "GetCompletedValue"))); + super::title_textures::safe_fence_value(this as usize, f(this)) +} + unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT { let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Signal"))); let hr = f(this, value); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index c082f1acf2..73d10a3a73 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -19,9 +19,9 @@ //! transitions of these textures are captured in each physical command-list segment's immutable //! submission effects and applied in submission order – per subresource once one is named. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::ffi::c_void; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use windows::core::Interface; @@ -2031,7 +2031,7 @@ pub(super) struct PendingDownload { impl Drop for PendingDownload { fn drop(&mut self) { let done = self.fence_value.is_some_and(|v| { - let got = unsafe { self.fence.GetCompletedValue() }; + let got = unsafe { super::real::native_fence_completed(&self.fence) }; got != u64::MAX && got >= v }); if !done { @@ -2046,7 +2046,7 @@ impl Drop for PendingDownload { impl PendingDownload { pub fn is_complete(&self) -> bool { self.fence_value.is_some_and(|v| { - let got = unsafe { self.fence.GetCompletedValue() }; + let got = unsafe { super::real::native_fence_completed(&self.fence) }; got != u64::MAX && got >= v }) } @@ -2075,6 +2075,10 @@ impl PendingDownload { pub fn footprints(&self) -> &[DownloadSubresource] { &self.footprints } pub fn layout(&self) -> &xg::Texture { &self.tex } + + fn arm(&self, event: windows::Win32::Foundation::HANDLE) { + if let Some(value) = self.fence_value { unsafe { let _ = self.fence.SetEventOnCompletion(value, event); } } + } } #[allow(dead_code)] @@ -2114,6 +2118,273 @@ impl TextureDownloadPlan { } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DownloadWrite { subresource: u32, state: D3D12_RESOURCE_STATES, writer: GpuWriter } + +pub(super) struct ReadyDownload { res: usize, generation: u64, target: usize, format: u32, writes: Vec<DownloadWrite>, ticket: PendingDownload } + +struct FenceDownloads { fence: ID3D12Fence, value: u64, downloads: Vec<Option<ReadyDownload>> } + +static FENCE_DOWNLOADS: Mutex<Vec<FenceDownloads>> = Mutex::new(Vec::new()); +static DOWNLOADS_PENDING: AtomicBool = AtomicBool::new(false); +static SCHEDULED_DOWNLOADS: Mutex<BTreeSet<(usize, u64, u64, u32, u64)>> = Mutex::new(BTreeSet::new()); +static SAFE_FENCE_VALUES: Mutex<BTreeMap<usize, u64>> = Mutex::new(BTreeMap::new()); + +fn writer_at(entry: &Entry, subresource: usize) -> Option<GpuWriter> { + match entry.gpu_writers.as_slice() { + [] => None, [writer] => *writer, writers => writers.get(subresource).copied().flatten(), + } +} + +fn download_writes(res: usize, entry: &Entry, queue: WriterQueueId) -> Vec<DownloadWrite> { + let n = subresource_count(&entry.tex); + let scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + (0..n).filter_map(|subresource| { + let writer = writer_at(entry, subresource)?; + (writer.queue == queue && !scheduled.contains(&(res, entry.generation, writer.queue.generation, subresource as u32, writer.epoch))) + .then(|| DownloadWrite { subresource: subresource as u32, state: if entry.states.len() == n { entry.states[subresource] } else { entry.states[0] }, writer }) + }).collect() +} + +struct DownloadSnapshot { res: usize, generation: u64, target: usize, format: u32, tex: Arc<xg::Texture>, device: ID3D12Device, source: ID3D12Resource, writes: Vec<DownloadWrite>, plan: Option<TextureDownloadPlan> } + +pub(super) struct PreparedDownloads { id: WriterQueueId, snapshots: Vec<DownloadSnapshot> } + +pub(super) enum SubmitDownloadsError { Stale, Failed(String) } + +fn download_current(entry: &Entry, generation: u64, target: usize, writes: &[DownloadWrite]) -> bool { + entry.generation == generation && entry.src == target && writes.iter().all(|w| writer_at(entry, w.subresource as usize) == Some(w.writer)) +} + +/// Build readback lists outside the queue turn. The state is validated again at insertion. +/// Writes owned by another queue are left for a signal on that exact queue. +pub(super) unsafe fn prepare_downloads(queue: *mut c_void) -> PreparedDownloads { + let id = super::list_x::queue_identity(queue as usize).unwrap_or(WriterQueueId { raw: queue as usize, generation: 0 }); + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return PreparedDownloads { id, snapshots: Vec::new() } }; + let queue_type = q.GetDesc().Type; + if !download_queue_type_supported(queue_type) { return PreparedDownloads { id, snapshots: Vec::new() } } + let candidates: Vec<DownloadSnapshot> = { + let table = TEXTURES.lock().unwrap(); + table.by_res.iter().filter_map(|(&res, entry)| { + let writes = download_writes(res, entry, id); + if writes.is_empty() { return None } + let source = ID3D12Resource::from_raw_borrowed(&(res as *mut c_void))?.clone(); + let device = ID3D12Device::from_raw_borrowed(&(entry.device as *mut c_void))?.clone(); + Some(DownloadSnapshot { res, generation: entry.generation, target: entry.src, format: source.GetDesc().Format.0 as u32, + tex: Arc::clone(&entry.tex), device, source, writes, plan: None }) + }).collect() + }; + let mut snapshots = Vec::new(); + for mut snapshot in candidates { + let selected: Vec<_> = snapshot.writes.iter().map(|w| (w.subresource, w.state)).collect(); + let Ok(plan) = prepare_texture_download(&snapshot.device, &snapshot.source, queue_type, Arc::clone(&snapshot.tex), snapshot.format, &selected) else { continue }; + snapshot.plan = Some(plan); + snapshots.push(snapshot); + } + PreparedDownloads { id, snapshots } +} + +/// Validate and insert prepared lists while the caller owns `queue`'s turn. A stale snapshot +/// submits nothing, so the caller can rebuild outside the turn and retry. +pub(super) unsafe fn submit_prepared_downloads(queue: *mut c_void, prepared: PreparedDownloads) -> Result<Vec<ReadyDownload>, SubmitDownloadsError> { + if prepared.snapshots.is_empty() { return Ok(Vec::new()) } + if super::list_x::queue_identity(queue as usize) != Some(prepared.id) { return Err(SubmitDownloadsError::Stale) } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return Ok(Vec::new()) }; + let table = TEXTURES.lock().unwrap(); + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + let valid = prepared.snapshots.iter().all(|snapshot| { + table.by_res.get(&snapshot.res).is_some_and(|entry| { + entry.generation == snapshot.generation + && entry.src == snapshot.target + && snapshot.writes.iter().all(|w| { + !scheduled.contains(&(snapshot.res, snapshot.generation, w.writer.queue.generation, w.subresource, w.writer.epoch)) + && + writer_at(entry, w.subresource as usize) == Some(w.writer) + && (if entry.states.len() == subresource_count(&entry.tex) { + entry.states[w.subresource as usize] + } else { + entry.states[0] + }) == w.state + }) + }) + }); + if !valid { return Err(SubmitDownloadsError::Stale) } + let keys: Vec<_> = prepared.snapshots.iter().flat_map(|snapshot| snapshot.writes.iter().map(|write| { + (snapshot.res, snapshot.generation, write.writer.queue.generation, write.subresource, write.writer.epoch) + })).collect(); + for &key in &keys { scheduled.insert(key); } + drop(scheduled); + drop(table); + let mut ready = Vec::new(); + for snapshot in prepared.snapshots { + let submitted = match snapshot.plan.unwrap().submit(q) { + Ok(submitted) => submitted, + Err(error) => { rollback_reservations(&keys); return Err(SubmitDownloadsError::Failed(error)) } + }; + if let Some(error) = submitted.signal_error { rollback_reservations(&keys); return Err(SubmitDownloadsError::Failed(format!("texture download completion signal failed: {error}"))) } + ready.push(ReadyDownload { res: snapshot.res, generation: snapshot.generation, target: snapshot.target, format: snapshot.format, writes: snapshot.writes, ticket: submitted.ticket }); + } + Ok(ready) +} + +fn rollback_reservations(keys: &[(usize, u64, u64, u32, u64)]) { + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + for key in keys { scheduled.remove(key); } +} + +/// Tie already-submitted readbacks to the title fence queued immediately after them. +pub(super) unsafe fn tie_downloads(fence: *mut c_void, value: u64, downloads: Vec<ReadyDownload>) { + if downloads.is_empty() { return } + let Some(fence) = ID3D12Fence::from_raw_borrowed(&fence).cloned() else { return }; + SAFE_FENCE_VALUES.lock().unwrap().insert(fence.as_raw() as usize, super::real::native_fence_completed(&fence)); + let event = super::fence_x::wake_event(); + for download in &downloads { download.ticket.arm(event); } + { + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + for download in &downloads { for write in &download.writes { + scheduled.insert((download.res, download.generation, write.writer.queue.generation, write.subresource, write.writer.epoch)); + } } + } + FENCE_DOWNLOADS.lock().unwrap().push(FenceDownloads { fence: fence.clone(), value, downloads: downloads.into_iter().map(Some).collect() }); + DOWNLOADS_PENDING.store(true, Ordering::Release); + let _ = fence.SetEventOnCompletion(value, event); +} + +fn publish_download(download: &ReadyDownload) -> Result<bool, String> { + let Some(readback) = (unsafe { download.ticket.readback_bytes()? }) else { return Ok(false) }; + let size = usize::try_from(download.ticket.layout().size()).map_err(|_| "texture download destination is too large")?; + let current = unsafe { title_bytes(download.target, size) }; + let mut console = Vec::new(); + console.try_reserve_exact(size).map_err(|_| "cannot allocate texture download destination")?; + console.extend_from_slice(¤t); + for (write, footprint) in download.writes.iter().zip(download.ticket.footprints()) { + reverse_layout_subresource(download.ticket.layout(), download.format, write.subresource, footprint.footprint, &readback, &mut console) + .map_err(|e| format!("cannot reverse texture download layout: {e:?}"))?; + } + let mut table = TEXTURES.lock().unwrap(); + let Some(entry) = table.by_res.get_mut(&download.res) else { return Ok(true) }; + if !download_current(entry, download.generation, download.target, &download.writes) { return Ok(true) } + if !unsafe { write_changed_pages(download.target, ¤t, &console) } { return Ok(false) } + let n = subresource_count(&entry.tex); + if entry.gpu_writers.len() != n { + entry.gpu_writers = vec![entry.gpu_writers.first().copied().flatten(); n]; + } + for write in &download.writes { + let slot = &mut entry.gpu_writers[write.subresource as usize]; + if *slot == Some(write.writer) { *slot = None; } + } + if entry.gpu_writers.iter().all(Option::is_none) { + entry.gpu_writers.clear(); + entry.gpu_written = false; + } + Ok(true) +} + +/// Write changed 4 KiB pages without faulting if the title concurrently unmaps one. Every +/// changed page must be committed and writable; otherwise its fence remains hidden and retries. +unsafe fn write_changed_pages(at: usize, old: &[u8], new: &[u8]) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_GUARD}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if old.len() != new.len() { return false } + let mut offset = 0; + while offset < new.len() { + let end = (((at + offset) & !4095) + 4096).saturating_sub(at).min(new.len()); + if old[offset..end] == new[offset..end] { offset = end; continue } + let address = at + offset; + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(address as *const c_void, &mut info, std::mem::size_of_val(&info)) == 0 + || info.State != MEM_COMMIT + || info.Protect & 0xCC == 0 + || info.Protect & PAGE_GUARD != 0 + || (info.BaseAddress as usize).saturating_add(info.RegionSize) < at + end + { + return false; + } + let mut written = 0; + if WriteProcessMemory(GetCurrentProcess(), address as *const c_void, new[offset..end].as_ptr() as *const c_void, end - offset, &mut written) == 0 + || written != end - offset { + return false; + } + offset = end; + } + true +} + +fn unschedule(download: &ReadyDownload) { + unschedule_writes(download.res, download.generation, &download.writes); +} + +fn unschedule_writes(res: usize, generation: u64, writes: &[DownloadWrite]) { + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + for write in writes { scheduled.remove(&(res, generation, write.writer.queue.generation, write.subresource, write.writer.epoch)); } +} + +fn batch_ready(blocked: &mut bool, target: u64, completed: u64) -> bool { + if *blocked || target > completed { *blocked = true; false } else { true } +} + +/// Apply every completed download through `value`. False withholds the title's mirrored fence +/// value until a transiently unavailable readback or destination can be retried. +pub(super) fn complete_fence_downloads(fence: usize, value: u64) -> bool { + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { return true } + let mut batches = FENCE_DOWNLOADS.lock().unwrap(); + let mut ok = true; + let mut blocked = false; + for batch in batches.iter_mut().filter(|b| b.fence.as_raw() as usize == fence) { + if !batch_ready(&mut blocked, batch.value, value) { ok &= batch.value > value; continue } + for download in &mut batch.downloads { + let Some(ready) = download.as_ref() else { continue }; + match publish_download(ready) { + Ok(true) => { + unschedule(ready); + *download = None; + } + Ok(false) => { + ok = false; + blocked = true; + } + Err(error) => { + crate::xlog_warn!("D3D12.X: {error}; holding title fence {fence:#x} at {value:#x}"); + ok = false; + blocked = true; + } + } + } + blocked |= batch.downloads.iter().any(Option::is_some); + } + batches.retain(|batch| batch.downloads.iter().any(Option::is_some)); + DOWNLOADS_PENDING.store(!batches.is_empty(), Ordering::Release); + if ok { + SAFE_FENCE_VALUES.lock().unwrap().entry(fence).and_modify(|safe| *safe = (*safe).max(value)).or_insert(value); + } + ok +} + +pub(super) fn safe_fence_value(fence: usize, native: u64) -> u64 { + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { return native } + if native != u64::MAX && complete_fence_downloads(fence, native) { + native + } else { + SAFE_FENCE_VALUES.lock().unwrap().get(&fence).copied().unwrap_or(0) + } +} + +/// Poll pending title fences even when a title never requested a completed-value mirror. +pub(super) fn poll_fence_downloads() { + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { return } + let pending: Vec<_> = { + let batches = FENCE_DOWNLOADS.lock().unwrap(); + batches.iter().map(|batch| batch.fence.clone()).collect() + }; + for fence in pending { + let value = unsafe { super::real::native_fence_completed(&fence) }; + if value != u64::MAX { + let _ = complete_fence_downloads(fence.as_raw() as usize, value); + } + } +} + fn download_queue_type_supported(ty: D3D12_COMMAND_LIST_TYPE) -> bool { matches!(ty, D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE) } @@ -2704,8 +2975,24 @@ mod tests { let last = e.gpu_writers[4].unwrap(); assert_eq!(last.queue, q2); assert!(last.epoch > first_epoch); + let q1_writes = download_writes(res, e, q1); + let q2_writes = download_writes(res, e, q2); + assert_eq!(q1_writes.iter().map(|w| w.subresource).collect::<Vec<_>>(), [2]); + assert_eq!(q2_writes.iter().map(|w| w.subresource).collect::<Vec<_>>(), [4]); + let key = (res, generation, q1.generation, 2, first_epoch); + SCHEDULED_DOWNLOADS.lock().unwrap().insert(key); + assert!(download_writes(res, e, q1).is_empty(), "an in-flight epoch is not downloaded twice"); + SCHEDULED_DOWNLOADS.lock().unwrap().remove(&key); } + let stale = download_writes(res, &TEXTURES.lock().unwrap().by_res[&res], q1); + let key = (res, generation, q1.generation, 2, first_epoch); + SCHEDULED_DOWNLOADS.lock().unwrap().insert(key); + publish_gpu_writes(q2, &[GpuWrite { res, generation, subresource: 2 }]); + assert!(!download_current(&TEXTURES.lock().unwrap().by_res[&res], generation, 0x7E57_1000_0000, &stale)); + unschedule_writes(res, generation, &stale); + assert!(!SCHEDULED_DOWNLOADS.lock().unwrap().contains(&key)); + // Reusing the resource address creates another registration generation: a captured // effect from the old object must not mark it. { @@ -2719,6 +3006,23 @@ mod tests { TEXTURES.lock().unwrap().remove(res); } + #[test] + fn fence_download_batches_preserve_insertion_order() { + let mut blocked = false; + assert!(!batch_ready(&mut blocked, 20, 10)); + assert!(!batch_ready(&mut blocked, 5, 10), "later eligible batch passed an earlier one"); + blocked = true; + assert!(!batch_ready(&mut blocked, 10, 10), "later batch passed an incomplete one"); + } + + #[test] + fn download_reservation_rollback_clears_every_key() { + let keys = [(0xBAD0, 1, 2, 3, 4), (0xBAD1, 5, 6, 7, 8)]; + SCHEDULED_DOWNLOADS.lock().unwrap().extend(keys); + rollback_reservations(&keys); + assert!(keys.iter().all(|key| !SCHEDULED_DOWNLOADS.lock().unwrap().contains(key))); + } + /// A texture kept in step: the title's transitions count once their list is submitted, in /// submission order, each time it is; a Reset forgets them; other resources are not noted. #[test] From 2e76ec5f04c3b65c8e6b12f314d77007267152fc Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:46:00 -0800 Subject: [PATCH 119/265] D3D12.X: publish single descriptors outside shared heap locks Single-descriptor publication called CopyDescriptorsSimple while holding the heap registries, serializing unrelated descriptor work and allowing a driver callback to deadlock heap teardown. Snapshot the exact heap generation and strong source owner, validate the source and destination handles, and lease the destination slot before dropping all registry locks. Defer shared-range reuse until overlapping copies finish, and reject stale slots after raw-address reuse. Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/console_heap.rs | 237 +++++++++++++++++++--- crates/xcl/src/hle/d3d12x/list_x.rs | 2 +- 2 files changed, 211 insertions(+), 28 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 2a8c7e1f1e..882bfbbb8a 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -25,6 +25,7 @@ //! Without the shared heap (it could not be made) a heap keeps its own PC heap: SRV at 2k, //! UAV at 2k + 1. +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; use windows::core::Interface; @@ -46,6 +47,7 @@ enum Memory { } struct Heap { + generation: u64, obj: usize, shadow: usize, n: u32, @@ -73,6 +75,67 @@ impl Heap { } static HEAPS: Mutex<Vec<Heap>> = Mutex::new(Vec::new()); +static NEXT_HEAP_GENERATION: AtomicU64 = AtomicU64::new(0); + +/// Shared ranges being written by lock-free single-descriptor publication, and releases which +/// cannot return to the allocator until every overlapping write has finished. +#[derive(Default)] +struct PublishLeases { + active: Vec<(u32, u32)>, + deferred: Vec<(u32, u32)>, +} + +impl PublishLeases { + fn acquire(&mut self, first: u32, count: u32) { + self.active.push((first, count)); + } + + fn release_range(&mut self, free: &mut Vec<(u32, u32)>, first: u32, count: u32) { + let range = (first, count); + if self.active.iter().any(|&active| ranges_overlap(active, range)) { + self.deferred.push(range); + } else { + merge_release(free, first, count); + } + } + + fn finish(&mut self, free: &mut Vec<(u32, u32)>, range: (u32, u32)) { + if let Some(i) = self.active.iter().position(|&active| active == range) { + self.active.swap_remove(i); + } + let mut i = 0; + while i < self.deferred.len() { + let deferred = self.deferred[i]; + if self.active.iter().any(|&active| ranges_overlap(active, deferred)) { + i += 1; + } else { + self.deferred.swap_remove(i); + merge_release(free, deferred.0, deferred.1); + } + } + } +} + +fn ranges_overlap(a: (u32, u32), b: (u32, u32)) -> bool { + a.0 < b.0.saturating_add(b.1) && b.0 < a.0.saturating_add(a.1) +} + +struct PublishLease { + sampler: bool, + range: (u32, u32), +} + +impl Drop for PublishLease { + fn drop(&mut self) { + if self.sampler { + if let Some(global) = GLOBAL_SAMPLER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + global.leases.finish(&mut global.free, self.range); + } + } else if let Some(global) = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + global.leases.finish(&mut global.free, self.range); + } + } +} /// The shader-visible PC heap of all console view heaps. struct Global { @@ -85,6 +148,7 @@ struct Global { next: u32, /// released ranges (first, count) free: Vec<(u32, u32)>, + leases: PublishLeases, } // D3D12 descriptor heaps and devices are free-threaded @@ -182,6 +246,7 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { // the memory windows and their two out-of-range null UAVs come first next: crate::gpu::recomp::MEM_NULL_STORE + 1, free: Vec::new(), + leases: PublishLeases::default(), }); } true @@ -299,7 +364,7 @@ pub fn release_global(first: u32, count: u32) { return; } if let Some(s) = GLOBAL.lock().unwrap().as_mut() { - merge_release(&mut s.free, first, count); + s.leases.release_range(&mut s.free, first, count); } } @@ -391,7 +456,8 @@ pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32, sampler: } else { Vec::new() }; - HEAPS.lock().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler, pages, visible, memory }); + let generation = NEXT_HEAP_GENERATION.fetch_add(1, Ordering::Relaxed).wrapping_add(1); + HEAPS.lock().unwrap().push(Heap { generation, obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler, pages, visible, memory }); true } @@ -441,6 +507,7 @@ pub fn start(obj: usize) -> Option<u64> { /// A console slot: where its descriptor goes and its PC descriptors. #[derive(Clone, Copy, Debug)] pub struct Slot { + pub(super) generation: u64, pub at: usize, /// views: PC heap index of the SRV (the UAV is at + 1); samplers: of the sampler pub index: u32, @@ -475,7 +542,7 @@ pub fn slot(cpu: u64) -> Option<Slot> { // shared heap must map overflowed slots to reserved zero-sampler slot 0 rather than // aliasing unrelated heap entries at local index `k`. let (index, shared_srv) = shared.unwrap_or_else(|| (sampler_unmapped_index(!h.pages.is_empty(), k), 0)); - return Some(Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k, remaining: h.n - k }); + return Some(Slot { generation: h.generation, at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k, remaining: h.n - k }); } let uav = ((2 * k + 1) * h.inc) as u64; let shared = page_of(h, k).and_then(|(first, k0)| { @@ -485,7 +552,7 @@ pub fn slot(cpu: u64) -> Option<Slot> { Some((i, g.gpu + (i as u64 + 1) * g.inc as u64, g.cpu + i as u64 * g.inc as u64)) }); let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or((2 * k, if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0)); - Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k, remaining: h.n - k }) + Some(Slot { generation: h.generation, at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k, remaining: h.n - k }) } /// The view (or sampler) just made in slot `s` (its SRV, or with `uav` its UAV) goes to the shared heap. @@ -493,21 +560,55 @@ pub unsafe fn publish(s: &Slot, uav: bool) { if s.shared_srv == 0 { return; } - if s.sampler { - if let Some(g) = GLOBAL_SAMPLER.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple( - 1, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, - D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, - ); + // Keep the exact source heap generation alive and lease its shared destination before + // dropping HEAPS. A concurrent final Release can then detach its books, but cannot free the + // source object or recycle the shared index until CopyDescriptorsSimple returns. + let snapshot = (|| { + let heaps = HEAPS.lock().unwrap(); + let h = heaps.iter().find(|h| { + h.generation == s.generation + && h.sampler == s.sampler + && s.k < h.n + && s.at == h.shadow + (s.k * h.slot_bytes()) as usize + })?; + let raw = h.obj as *mut std::ffi::c_void; + let source_owner = ID3D12DescriptorHeap::from_raw_borrowed(&raw)?.clone(); + if h.sampler { + let first = *h.pages.get((s.k / SAMPLER_PAGE_SLOTS) as usize)?; + if first == UNMAPPED || h.pc_cpu + (s.k * h.inc) as u64 != s.pc_srv { + return None; + } + let idx = first + s.k % SAMPLER_PAGE_SLOTS; + let mut globals = GLOBAL_SAMPLER.lock().unwrap(); + let global = globals.as_mut()?; + let dst = global.cpu + idx as u64 * global.inc as u64; + if dst != s.shared_srv { + return None; + } + global.leases.acquire(idx, 1); + Some((global.dev.clone(), source_owner, PublishLease { sampler: true, range: (idx, 1) }, dst, s.pc_srv, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)) + } else { + let first = *h.pages.get((s.k / PAGE_SLOTS) as usize)?; + let src = if uav { s.pc_uav } else { s.pc_srv }; + let expected_src = h.pc_cpu + (2 * s.k + uav as u32) as u64 * h.inc as u64; + if first == UNMAPPED || expected_src != src { + return None; + } + let idx = first + 2 * (s.k % PAGE_SLOTS) + uav as u32; + let mut globals = GLOBAL.lock().unwrap(); + let global = globals.as_mut()?; + let dst = global.cpu + idx as u64 * global.inc as u64; + if dst != s.shared_srv + uav as u64 * global.inc as u64 { + return None; + } + global.leases.acquire(idx, 1); + Some((global.dev.clone(), source_owner, PublishLease { sampler: false, range: (idx, 1) }, dst, src, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)) } + })(); + let Some((dev, _source_owner, _lease, dst, src, ty)) = snapshot else { return; - } - if let Some(g) = GLOBAL.lock().unwrap().as_ref() { - let (dst, src) = if uav { (s.shared_srv + g.inc as u64, s.pc_uav) } else { (s.shared_srv, s.pc_srv) }; - g.dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - } + }; + dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, ty); } /// `n` view or sampler slots from `first` were copied (in the title's heap): they go to the shared heap, @@ -691,6 +792,7 @@ struct GlobalSampler { cap: u32, next: u32, free: Vec<(u32, u32)>, + leases: PublishLeases, } unsafe impl Send for GlobalSampler {} @@ -754,6 +856,7 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { // Reserve slot 0 as the immutable point-wrap zero sampler for empty/zeroed S# entries. next: 1, free: Vec::new(), + leases: PublishLeases::default(), }); } true @@ -789,7 +892,7 @@ fn release_global_sampler(first: u32, count: u32) { return; } if let Some(s) = GLOBAL_SAMPLER.lock().unwrap().as_mut() { - merge_release(&mut s.free, first, count); + s.leases.release_range(&mut s.free, first, count); } } @@ -898,7 +1001,7 @@ mod tests { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, - next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), + next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), leases: PublishLeases::default(), }); let window = (&mut resource as *mut _ as usize, 0x10000); assert!(set_window_views(&dev, &[window])); @@ -1090,7 +1193,7 @@ mod tests { *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev: ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), - cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), + cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), leases: PublishLeases::default(), }); assert_eq!(reserve_global_sampler(4), Some(1)); assert_eq!(reserve_global_sampler(4), Some(5)); @@ -1149,12 +1252,12 @@ mod tests { *GLOBAL.lock().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut view_heap as *mut _ as *mut c_void), - cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), + cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), leases: PublishLeases::default(), }); *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sampler_heap as *mut _ as *mut c_void), - cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), + cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), leases: PublishLeases::default(), }); if crate::gpu::uma::get().is_some() { assert!(register(0xC100, 16, 0x9000, 0, 16, true, true, true)); @@ -1176,8 +1279,8 @@ mod tests { assert_eq!(GLOBAL_SAMPLER.lock().unwrap().as_ref().unwrap().free, vec![(1, 8)]); } else { let mut heaps = HEAPS.lock().unwrap(); - heaps.push(Heap { obj: 0xC100, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); - heaps.push(Heap { obj: 0xC101, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 1, obj: 0xC100, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 2, obj: 0xC101, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); drop(heaps); assert!(!in_global(0xC100) && in_global_sampler(0xC100)); assert!(in_global(0xC101) && !in_global_sampler(0xC101)); @@ -1253,6 +1356,7 @@ mod tests { cap: 4096, next: 64, free: Vec::new(), + leases: PublishLeases::default(), }); *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev, @@ -1262,12 +1366,13 @@ mod tests { cap: 256, next: 1, free: Vec::new(), + leases: PublishLeases::default(), }); { let mut heaps = HEAPS.lock().unwrap(); - heaps.push(Heap { obj: 1, shadow: view4.as_ptr() as usize, n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); - heaps.push(Heap { obj: 2, shadow: sampler3.as_ptr() as usize, n: 3, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); - heaps.push(Heap { obj: 3, shadow: view260.as_ptr() as usize, n: 260, pc_cpu: 0x50_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 1, obj: 1, shadow: view4.as_ptr() as usize, n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 2, obj: 2, shadow: sampler3.as_ptr() as usize, n: 3, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 3, obj: 3, shadow: view260.as_ptr() as usize, n: 260, pc_cpu: 0x50_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); } let v1 = slot(view4.as_ptr() as u64 + SLOT as u64).unwrap(); publish_range(&v1, 10); @@ -1289,4 +1394,82 @@ mod tests { ] ); } + + #[test] + fn single_publish_runs_unlocked_and_holds_generation_and_range() { + const CHILD: &str = "XCL_TEST_SINGLE_PUBLISH_LEASE_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::single_publish_runs_unlocked_and_holds_generation_and_range", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}; + use std::sync::{Arc, Barrier, OnceLock}; + + static GATE: OnceLock<(Arc<Barrier>, Arc<Barrier>)> = OnceLock::new(); + static LOCKS_FREE: AtomicBool = AtomicBool::new(false); + static CALLS: AtomicUsize = AtomicUsize::new(0); + #[repr(C)] + struct Object { vt: *const usize, refs: AtomicU32 } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (*this.cast::<Object>()).refs.fetch_add(1, Ordering::Relaxed) + 1 + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + (*this.cast::<Object>()).refs.fetch_sub(1, Ordering::Relaxed) - 1 + } + unsafe extern "system" fn copy_simple(_this: *mut c_void, n: u32, dst: D3D12_CPU_DESCRIPTOR_HANDLE, src: D3D12_CPU_DESCRIPTOR_HANDLE, ty: D3D12_DESCRIPTOR_HEAP_TYPE) { + LOCKS_FREE.store(GLOBAL.try_lock().is_ok() && GLOBAL_SAMPLER.try_lock().is_ok() && HEAPS.try_lock().is_ok(), Ordering::Relaxed); + assert_eq!((n, dst.ptr, src.ptr, ty), (1, 0x10_0000 + 64 * 32, 0x30_0000, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + CALLS.fetch_add(1, Ordering::Relaxed); + let (entered, leave) = GATE.get().unwrap(); + entered.wait(); + leave.wait(); + } + let entered = Arc::new(Barrier::new(2)); + let leave = Arc::new(Barrier::new(2)); + GATE.set((entered.clone(), leave.clone())).ok(); + let mut vt = [0usize; 25]; + vt[1] = add_ref as usize; + vt[2] = release as usize; + vt[24] = copy_simple as usize; + let mut device = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + let mut global_heap = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + let mut source_heap = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + let shadow = vec![0u8; (4 * SLOT) as usize]; + unsafe { + *GLOBAL.lock().unwrap() = Some(Global { + dev: ID3D12Device::from_raw((&mut device as *mut Object).cast()), + heap: ID3D12DescriptorHeap::from_raw((&mut global_heap as *mut Object).cast()), + cpu: 0x10_0000, gpu: 0x18_0000, inc: 32, cap: 4096, next: 72, + free: Vec::new(), leases: PublishLeases::default(), + }); + HEAPS.lock().unwrap().push(Heap { + generation: 77, obj: &mut source_heap as *mut Object as usize, shadow: shadow.as_ptr() as usize, + n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![64], visible: true, memory: Memory::Uma, + }); + let stale = slot(shadow.as_ptr() as u64).unwrap(); + let worker = std::thread::spawn(move || publish(&stale, false)); + entered.wait(); + assert_eq!(source_heap.refs.load(Ordering::Relaxed), 2, "source heap must stay owned during the device call"); + let Taken(old) = take(&mut source_heap as *mut Object as usize).unwrap(); + release_global(old.pages[0], page_descriptors(old.n, 0)); + assert_ne!(reserve_global(8), Some(64), "an in-flight destination range must not be recycled"); + HEAPS.lock().unwrap().push(Heap { generation: 78, pages: vec![80], ..old }); + leave.wait(); + worker.join().unwrap(); + assert!(LOCKS_FREE.load(Ordering::Relaxed)); + assert_eq!(source_heap.refs.load(Ordering::Relaxed), 1); + assert_eq!(reserve_global(8), Some(64), "deferred range must return when publication finishes"); + publish(&stale, false); + assert_eq!(CALLS.load(Ordering::Relaxed), 1, "a stale generation must not publish into its replacement"); + HEAPS.lock().unwrap().clear(); + *GLOBAL.lock().unwrap() = None; + } + assert_eq!((device.refs.load(Ordering::Relaxed), global_heap.refs.load(Ordering::Relaxed), source_heap.refs.load(Ordering::Relaxed)), (0, 0, 1)); + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 8836772dd4..b1c8bac6f2 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -8778,7 +8778,7 @@ mod tests { #[test] fn uav_clear_handles_translate_console_slots() { use super::super::console_heap::Slot; - let s = |pc_uav: u64, pc_gpu_uav: u64, sampler: bool| Some(Slot { at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv: 0, k: 0, remaining: 1 }); + let s = |pc_uav: u64, pc_gpu_uav: u64, sampler: bool| Some(Slot { generation: 0, at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv: 0, k: 0, remaining: 1 }); assert_eq!(uav_clear_handles(s(0x10, 0x5010, false), s(0x20, 0, false)), UavClearHandles::Console { gpu: 0x5010, cpu: 0x20 }); assert_eq!(uav_clear_handles(None, None), UavClearHandles::Pc); // a console slot beside a PC handle, a GPU slot of a heap that is not shader visible, From dc7280f1c563348c785c7b14078b15c218563c5e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:50:07 -0800 Subject: [PATCH 120/265] D3D12.X: include texture refresh in submit stall timing SubmitPreparation started after title texture refresh, so write-watch scanning, detiling, and upload work was invisible in the coarse stall breakdown. Start the span before refresh while retaining the existing suspension around deferred pipeline waits. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 2d30886ddd..0ca46e3d16 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8508,11 +8508,11 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis // own work in the submission. Where that takes long, it is not the title's time // (`pso_async::title_held`) let _in_pc = super::pso_async::pc_call(); + let mut preparation_stall = crate::stall::span(crate::stall::StallKind::SubmitPreparation); // textures in title memory the CPU wrote since: uploaded again first super::title_textures::refresh(this); // console-shaped lists run as the PC lists they were translated into (split title lists expand // into all of their recorded PC segments in exact chronological order) - let mut preparation_stall = crate::stall::span(crate::stall::StallKind::SubmitPreparation); let mut mapped: Vec<*mut c_void> = Vec::with_capacity(n as usize); for &l in std::slice::from_raw_parts(lists, n as usize) { if let Some(pc) = super::console_list::pc_list(l) { From 6457c1884fa50d978380d8e1a273e7ba7c0a220c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:50:37 -0800 Subject: [PATCH 121/265] D3D12.X: fall back when extended cache deletion is unavailable Some filesystems do not support FileDispositionInfoEx with POSIX semantics. Fall back to legacy delete-on-close using the same DELETE-open handle so rejection still invalidates the exact loaded blob generation rather than a path replacement. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 43 ++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 2d30886ddd..db52818268 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4941,25 +4941,33 @@ pub(crate) mod driver_cache { /// process's newer replacement. pub fn invalidate(self) -> bool { use windows_sys::Win32::Storage::FileSystem::{ - FileDispositionInfoEx, SetFileInformationByHandle, - FILE_DISPOSITION_FLAG_DELETE, FILE_DISPOSITION_FLAG_POSIX_SEMANTICS, - FILE_DISPOSITION_INFO_EX, + SetFileInformationByHandle, }; let Some(file) = self.file else { return false }; let handle = file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE; - let ex = FILE_DISPOSITION_INFO_EX { Flags: FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS }; let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); - unsafe { - SetFileInformationByHandle( - handle, - FileDispositionInfoEx, - (&ex as *const FILE_DISPOSITION_INFO_EX).cast(), - std::mem::size_of::<FILE_DISPOSITION_INFO_EX>() as u32, - ) != 0 - } + set_disposition_with(|class, info, size| unsafe { + SetFileInformationByHandle(handle, class, info, size) != 0 + }) } } + /// Prefer immediate POSIX unlinking, but filesystems which do not implement the extended + /// disposition class can still mark this exact open file object for deletion on close. + fn set_disposition_with(mut set: impl FnMut(i32, *const std::ffi::c_void, u32) -> bool) -> bool { + use windows_sys::Win32::Storage::FileSystem::{ + FileDispositionInfo, FileDispositionInfoEx, + FILE_DISPOSITION_FLAG_DELETE, FILE_DISPOSITION_FLAG_POSIX_SEMANTICS, + FILE_DISPOSITION_INFO, FILE_DISPOSITION_INFO_EX, + }; + let ex = FILE_DISPOSITION_INFO_EX { Flags: FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS }; + if set(FileDispositionInfoEx, (&ex as *const FILE_DISPOSITION_INFO_EX).cast(), std::mem::size_of_val(&ex) as u32) { + return true; + } + let basic = FILE_DISPOSITION_INFO { DeleteFile: true }; + set(FileDispositionInfo, (&basic as *const FILE_DISPOSITION_INFO).cast(), std::mem::size_of_val(&basic) as u32) + } + pub fn load(p: &Path) -> Option<LoadedBlob> { use windows_sys::Win32::Foundation::GENERIC_READ; use windows_sys::Win32::Storage::FileSystem::{ @@ -5306,6 +5314,17 @@ pub(crate) mod driver_cache { assert!(!loaded.invalidate()); } + #[test] + fn unsupported_posix_disposition_falls_back_to_exact_handle_deletion() { + use windows_sys::Win32::Storage::FileSystem::{FileDispositionInfo, FileDispositionInfoEx}; + let mut classes = Vec::new(); + assert!(set_disposition_with(|class, _, _| { + classes.push(class); + class == FileDispositionInfo + })); + assert_eq!(classes, [FileDispositionInfoEx, FileDispositionInfo]); + } + #[test] fn a_cache_symlink_never_disposes_its_target() { use std::os::windows::fs::symlink_file; From cc64d204ababa08361d71764d3cdf184e8a449ac Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:52:09 -0800 Subject: [PATCH 122/265] D3D12.X: publish descriptor ranges outside heap locks Range publication still called the driver while holding shared heap metadata. Resolve and lease every exact destination run under the existing lock order, retain the source heap generation, then issue the batched copies without allocator locks. Tail bounds, unregister deferral, and address reuse remain validated. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/console_heap.rs | 170 ++++++++++++++++++---- 1 file changed, 140 insertions(+), 30 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 882bfbbb8a..718ceaa3e9 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -100,8 +100,14 @@ impl PublishLeases { } fn finish(&mut self, free: &mut Vec<(u32, u32)>, range: (u32, u32)) { - if let Some(i) = self.active.iter().position(|&active| active == range) { - self.active.swap_remove(i); + self.finish_ranges(free, &[range]); + } + + fn finish_ranges(&mut self, free: &mut Vec<(u32, u32)>, ranges: &[(u32, u32)]) { + for &range in ranges { + if let Some(i) = self.active.iter().position(|&active| active == range) { + self.active.swap_remove(i); + } } let mut i = 0; while i < self.deferred.len() { @@ -125,6 +131,23 @@ struct PublishLease { range: (u32, u32), } +struct PublishRangeLease { + sampler: bool, + ranges: Vec<(u32, u32)>, +} + +impl Drop for PublishRangeLease { + fn drop(&mut self) { + if self.sampler { + if let Some(global) = GLOBAL_SAMPLER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + global.leases.finish_ranges(&mut global.free, &self.ranges); + } + } else if let Some(global) = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + global.leases.finish_ranges(&mut global.free, &self.ranges); + } + } +} + impl Drop for PublishLease { fn drop(&mut self) { if self.sampler { @@ -614,29 +637,84 @@ pub unsafe fn publish(s: &Slot, uav: bool) { /// `n` view or sampler slots from `first` were copied (in the title's heap): they go to the shared heap, /// a run per page (a heap's pages lie apart there), stopping at the title heap's end. pub unsafe fn publish_range(first: &Slot, n: u32) { - let n = n.min(first.remaining); - let page_slots = if first.sampler { SAMPLER_PAGE_SLOTS } else { PAGE_SLOTS }; - let step = if first.sampler { SAMPLER_SLOT } else { SLOT }; - let mut done = 0; - while done < n { - let s = if done == 0 { Some(*first) } else { slot((first.at + (done * step) as usize) as u64) }; - let Some(s) = s else { return }; - let run = (page_slots - s.k % page_slots).min(n - done); - if s.shared_srv != 0 { - if s.sampler { - if let Some(g) = GLOBAL_SAMPLER.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple( - run, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, - D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, - ); - } - } else if let Some(g) = GLOBAL.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple(2 * run, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if n == 0 || first.shared_srv == 0 { + return; + } + // Resolve every page and lease every destination while HEAPS prevents unregister from + // detaching this exact generation. The device calls then need none of the allocator locks. + let snapshot = (|| { + let mut heaps = HEAPS.lock().unwrap(); + let h = heaps.iter_mut().find(|h| { + h.generation == first.generation + && h.sampler == first.sampler + && first.k < h.n + && first.at == h.shadow + (first.k * h.slot_bytes()) as usize + })?; + let mul = if h.sampler { 1u32 } else { 2u32 }; + if h.pc_cpu + mul as u64 * first.k as u64 * h.inc as u64 != first.pc_srv { + return None; + } + let raw = h.obj as *mut std::ffi::c_void; + let source_owner = ID3D12DescriptorHeap::from_raw_borrowed(&raw)?.clone(); + let page_slots = if h.sampler { SAMPLER_PAGE_SLOTS } else { PAGE_SLOTS }; + let limit = n.min(first.remaining).min(h.n - first.k); + let mut runs = Vec::with_capacity(limit.div_ceil(page_slots) as usize); + let mut done = 0; + while done < limit { + let k = first.k + done; + let run = (page_slots - k % page_slots).min(limit - done); + let (page, k0) = if h.sampler { sampler_page_of(h, k)? } else { page_of(h, k)? }; + runs.push((page + mul * (k - k0), h.pc_cpu + mul as u64 * k as u64 * h.inc as u64, mul * run)); + done += run; + } + if h.sampler { + let mut globals = GLOBAL_SAMPLER.lock().unwrap(); + let global = globals.as_mut()?; + if global.cpu + runs.first()?.0 as u64 * global.inc as u64 != first.shared_srv { + return None; } + for &(at, _, count) in &runs { + global.leases.acquire(at, count); + } + Some(( + global.dev.clone(), + source_owner, + PublishRangeLease { sampler: true, ranges: runs.iter().map(|&(at, _, count)| (at, count)).collect() }, + global.cpu, + global.inc, + runs, + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + )) + } else { + let mut globals = GLOBAL.lock().unwrap(); + let global = globals.as_mut()?; + if global.cpu + runs.first()?.0 as u64 * global.inc as u64 != first.shared_srv { + return None; + } + for &(at, _, count) in &runs { + global.leases.acquire(at, count); + } + Some(( + global.dev.clone(), + source_owner, + PublishRangeLease { sampler: false, ranges: runs.iter().map(|&(at, _, count)| (at, count)).collect() }, + global.cpu, + global.inc, + runs, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + )) } - done += run; + })(); + let Some((dev, _source_owner, _lease, cpu, inc, runs, ty)) = snapshot else { + return; + }; + for (at, src, count) in runs { + dev.CopyDescriptorsSimple( + count, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + at as u64 * inc as u64) as usize }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, + ty, + ); } } @@ -1321,7 +1399,9 @@ mod tests { return; } use std::ffi::c_void; + use std::sync::atomic::{AtomicBool, Ordering}; + static LOCKS_FREE: AtomicBool = AtomicBool::new(true); static CALLS: Mutex<Vec<(u32, u64, u64, i32)>> = Mutex::new(Vec::new()); #[repr(C)] struct Object { vt: *const usize } @@ -1333,6 +1413,10 @@ mod tests { src: D3D12_CPU_DESCRIPTOR_HANDLE, ty: D3D12_DESCRIPTOR_HEAP_TYPE, ) { + LOCKS_FREE.fetch_and( + GLOBAL.try_lock().is_ok() && GLOBAL_SAMPLER.try_lock().is_ok() && HEAPS.try_lock().is_ok(), + Ordering::Relaxed, + ); CALLS.lock().unwrap().push((n, dst.ptr as u64, src.ptr as u64, ty.0)); } @@ -1342,6 +1426,8 @@ mod tests { vt[24] = copy_simple as usize; let (mut device, mut view_heap, mut sampler_heap) = (Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }); + let (mut source4, mut source3, mut source260) = + (Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }); let view4 = vec![0u8; (4 * SLOT) as usize]; let sampler3 = vec![0u8; (3 * SAMPLER_SLOT) as usize]; let view260 = vec![0u8; (260 * SLOT) as usize]; @@ -1370,9 +1456,9 @@ mod tests { }); { let mut heaps = HEAPS.lock().unwrap(); - heaps.push(Heap { generation: 1, obj: 1, shadow: view4.as_ptr() as usize, n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); - heaps.push(Heap { generation: 2, obj: 2, shadow: sampler3.as_ptr() as usize, n: 3, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); - heaps.push(Heap { generation: 3, obj: 3, shadow: view260.as_ptr() as usize, n: 260, pc_cpu: 0x50_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 1, obj: &mut source4 as *mut Object as usize, shadow: view4.as_ptr() as usize, n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 2, obj: &mut source3 as *mut Object as usize, shadow: sampler3.as_ptr() as usize, n: 3, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 3, obj: &mut source260 as *mut Object as usize, shadow: view260.as_ptr() as usize, n: 260, pc_cpu: 0x50_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); } let v1 = slot(view4.as_ptr() as u64 + SLOT as u64).unwrap(); publish_range(&v1, 10); @@ -1384,6 +1470,7 @@ mod tests { *GLOBAL_SAMPLER.lock().unwrap() = None; *GLOBAL.lock().unwrap() = None; } + assert!(LOCKS_FREE.load(Ordering::Relaxed), "descriptor copies must run without heap locks"); assert_eq!( *CALLS.lock().unwrap(), vec![ @@ -1396,11 +1483,11 @@ mod tests { } #[test] - fn single_publish_runs_unlocked_and_holds_generation_and_range() { + fn publish_calls_run_unlocked_and_hold_generation_and_ranges() { const CHILD: &str = "XCL_TEST_SINGLE_PUBLISH_LEASE_CHILD"; if std::env::var_os(CHILD).is_none() { let output = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "hle::d3d12x::console_heap::tests::single_publish_runs_unlocked_and_holds_generation_and_range", "--nocapture"]) + .args(["--exact", "hle::d3d12x::console_heap::tests::publish_calls_run_unlocked_and_hold_generation_and_ranges", "--nocapture"]) .env(CHILD, "1") .output() .unwrap(); @@ -1424,8 +1511,15 @@ mod tests { } unsafe extern "system" fn copy_simple(_this: *mut c_void, n: u32, dst: D3D12_CPU_DESCRIPTOR_HANDLE, src: D3D12_CPU_DESCRIPTOR_HANDLE, ty: D3D12_DESCRIPTOR_HEAP_TYPE) { LOCKS_FREE.store(GLOBAL.try_lock().is_ok() && GLOBAL_SAMPLER.try_lock().is_ok() && HEAPS.try_lock().is_ok(), Ordering::Relaxed); - assert_eq!((n, dst.ptr, src.ptr, ty), (1, 0x10_0000 + 64 * 32, 0x30_0000, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); - CALLS.fetch_add(1, Ordering::Relaxed); + let call = CALLS.fetch_add(1, Ordering::Relaxed); + assert_eq!( + (n, dst.ptr, src.ptr, ty), + if call == 0 { + (1, 0x10_0000 + 64 * 32, 0x30_0000, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + } else { + (8, 0x10_0000 + 80 * 32, 0x30_0000, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + }, + ); let (entered, leave) = GATE.get().unwrap(); entered.wait(); leave.wait(); @@ -1467,6 +1561,22 @@ mod tests { assert_eq!(reserve_global(8), Some(64), "deferred range must return when publication finishes"); publish(&stale, false); assert_eq!(CALLS.load(Ordering::Relaxed), 1, "a stale generation must not publish into its replacement"); + + GLOBAL.lock().unwrap().as_mut().unwrap().next = 88; + let stale_range = slot(shadow.as_ptr() as u64).unwrap(); + let worker = std::thread::spawn(move || publish_range(&stale_range, 4)); + entered.wait(); + assert_eq!(source_heap.refs.load(Ordering::Relaxed), 2, "range source heap must stay owned during the device call"); + let Taken(old) = take(&mut source_heap as *mut Object as usize).unwrap(); + release_global(old.pages[0], page_descriptors(old.n, 0)); + assert_ne!(reserve_global(8), Some(80), "an in-flight range destination must not be recycled"); + HEAPS.lock().unwrap().push(Heap { generation: 79, pages: vec![96], ..old }); + leave.wait(); + worker.join().unwrap(); + assert_eq!(source_heap.refs.load(Ordering::Relaxed), 1); + assert_eq!(reserve_global(8), Some(80), "deferred range must return when range publication finishes"); + publish_range(&stale_range, 4); + assert_eq!(CALLS.load(Ordering::Relaxed), 2, "a stale range generation must not publish into its replacement"); HEAPS.lock().unwrap().clear(); *GLOBAL.lock().unwrap() = None; } From 88b82002a4831edabf39286eeeb23a31747b0377 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:55:50 -0800 Subject: [PATCH 123/265] D3D12.X: poll allocator backing fences outside global state Allocator reset, retirement, and release probing queried fence completion while holding the pool-wide state lock. Snapshot strong fence owners and exact backing generations, poll without the lock, and revalidate every namespace and mutable field before reuse or release. Carry replaced COM references out of the lock and fail closed on concurrent mutation. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 399 +++++++++++++++++++----- 1 file changed, 321 insertions(+), 78 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 67a1f448fe..62b71b99a8 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -26,6 +26,8 @@ use crate::util::HRESULT; #[derive(Default)] struct Backing { + /// Raw-address generation: a completed probe must not free a replacement at the same key. + generation: u64, /// PC lists whose recording is on this allocator users: HashSet<usize>, /// queue → (fence, value after the last submit of one of them) @@ -38,12 +40,6 @@ struct Backing { retire_when_free: bool, } -impl Backing { - unsafe fn free(&self) -> bool { - self.users.is_empty() && self.submit_pins == 0 && self.marks.values().all(|(f, v)| f.GetCompletedValue() >= *v) - } -} - #[derive(Default)] struct State { /// title allocator → the PC allocator in use (absent: itself) @@ -51,6 +47,7 @@ struct State { /// title allocator → PC allocators put aside aside: HashMap<usize, Vec<usize>>, backings: HashMap<usize, Backing>, + next_backing_generation: u64, of_list: HashMap<usize, usize>, /// title allocator → the type of the lists on it types: HashMap<usize, i32>, @@ -99,6 +96,84 @@ unsafe impl Send for State {} static STATE: Mutex<Option<State>> = Mutex::new(None); +#[derive(Clone)] +struct BackingProbe { + raw: usize, + generation: u64, + users: HashSet<usize>, + marks: Vec<(usize, ID3D12Fence, u64)>, + submit_pins: usize, + release_owner: Option<usize>, + retire_when_free: bool, +} + +impl BackingProbe { + fn new(raw: usize, backing: &Backing) -> Self { + Self { + raw, + generation: backing.generation, + users: backing.users.clone(), + marks: backing.marks.iter().map(|(&queue, (fence, value))| (queue, fence.clone(), *value)).collect(), + submit_pins: backing.submit_pins, + release_owner: backing.release_owner.as_ref().map(|owner| owner.as_raw() as usize), + retire_when_free: backing.retire_when_free, + } + } + + unsafe fn free(&self) -> bool { + self.users.is_empty() && self.submit_pins == 0 && self.marks.iter().all(|(_, fence, value)| fence.GetCompletedValue() >= *value) + } + + unsafe fn in_flight(&self) -> bool { + self.submit_pins != 0 || self.marks.iter().any(|(_, fence, value)| fence.GetCompletedValue() < *value) + } + + fn matches(&self, backing: &Backing) -> bool { + self.generation == backing.generation + && self.users == backing.users + && self.submit_pins == backing.submit_pins + && self.release_owner == backing.release_owner.as_ref().map(|owner| owner.as_raw() as usize) + && self.retire_when_free == backing.retire_when_free + && self.marks.len() == backing.marks.len() + && self.marks.iter().all(|(queue, fence, value)| { + backing.marks.get(queue).is_some_and(|(current, current_value)| current.as_raw() == fence.as_raw() && current_value == value) + }) + } +} + +fn backing_mut(state: &mut State, raw: usize) -> &mut Backing { + if !state.backings.contains_key(&raw) { + state.next_backing_generation = state.next_backing_generation.wrapping_add(1).max(1); + state.backings.insert(raw, Backing { generation: state.next_backing_generation, ..Default::default() }); + } + state.backings.get_mut(&raw).unwrap() +} + +fn namespace(state: &State, alloc: usize) -> Vec<usize> { + let mut mine: Vec<_> = state.cur.get(&alloc).into_iter().chain(state.aside.get(&alloc).into_iter().flatten()).chain([&alloc]).copied().collect(); + mine.sort_unstable(); + mine.dedup(); + mine +} + +fn namespace_probes(state: &State, alloc: usize) -> (Vec<usize>, Vec<BackingProbe>) { + let mine = namespace(state, alloc); + let probes = mine.iter().filter_map(|raw| state.backings.get(raw).map(|backing| BackingProbe::new(*raw, backing))).collect(); + (mine, probes) +} + +fn namespace_matches(state: &State, alloc: usize, mine: &[usize], probes: &[BackingProbe]) -> bool { + namespace(state, alloc) == mine + && mine.iter().all(|raw| match (state.backings.get(raw), probes.iter().find(|probe| probe.raw == *raw)) { + (None, None) => true, + (Some(backing), Some(probe)) => probe.matches(backing), + _ => false, + }) +} + +#[cfg(test)] +unsafe fn backing_free_for_test(backing: &Backing) -> bool { BackingProbe::new(0, backing).free() } + /// Remove completion caches for a retired queue before its raw address can be reused. This is /// called only after its retirement mark completes; every removed COM fence drops unlocked. pub(super) fn forget_queue(id: super::present::QueueId) { @@ -138,13 +213,30 @@ pub(super) fn release_with_probe( /// Transfer the caller's temporary AddRef probe into pool ownership when releasing `raw` would /// otherwise destroy an allocator that still owns recordings or unretired GPU work. pub(super) unsafe fn retain_release_probe(raw: *mut c_void) -> bool { - let mut g = STATE.lock().unwrap(); - let Some(backing) = g.as_mut().and_then(|s| s.backings.get_mut(&(raw as usize))) else { return false }; - if backing.free() || backing.release_owner.is_some() { - return false; + let key = raw as usize; + loop { + let probe = { + let g = STATE.lock().unwrap(); + let Some(backing) = g.as_ref().and_then(|s| s.backings.get(&key)) else { return false }; + if backing.release_owner.is_some() { return false } + BackingProbe::new(key, backing) + }; + let free = probe.free(); + let mut g = STATE.lock().unwrap(); + let Some(backing) = g.as_mut().and_then(|s| s.backings.get_mut(&key)) else { return false }; + if backing.release_owner.is_some() { + return false; + } + if backing.generation != probe.generation || !probe.matches(backing) { + drop(g); + continue; + } + if free { + return false; + } + backing.release_owner = Some(ID3D12CommandAllocator::from_raw(raw)); + return true; } - backing.release_owner = Some(ID3D12CommandAllocator::from_raw(raw)); - true } /// Drop transferred Release probes only after leaving STATE: their hooked Release re-enters here. @@ -157,25 +249,26 @@ fn sweep_release_owners_with( mut release_made: impl FnMut(ID3D12CommandAllocator), ) { loop { - let owner = { + let probes: Vec<_> = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return }; + s.backings.iter().filter_map(|(&raw, backing)| backing.retire_when_free.then(|| BackingProbe::new(raw, backing))).collect() + }; + let ready: Vec<_> = probes.into_iter().filter(|probe| unsafe { probe.free() }).collect(); + if ready.is_empty() { return } + let removed = { let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return }; - if let Some(raw) = s.backings.iter().find_map(|(&raw, b)| (b.retire_when_free && unsafe { b.free() }).then_some(raw)) { - let mut gone = s.backings.remove(&raw).unwrap(); - match gone.release_owner.take() { - Some(owner) => Some((owner, true)), - None => Some((unsafe { ID3D12CommandAllocator::from_raw(raw as *mut c_void) }, false)), - } - } else { - return; - } + ready.iter().find_map(|probe| { + s.backings.get(&probe.raw).is_some_and(|backing| probe.matches(backing)).then(|| probe.raw) + }).and_then(|raw| s.backings.remove(&raw).map(|backing| (raw, backing))) }; - if let Some((owner, transferred)) = owner { - if transferred { - release_transferred(owner); - } else { - release_made(owner); - } + let Some((raw, mut backing)) = removed else { continue }; + let owner = backing.release_owner.take(); + drop(backing); + match owner { + Some(owner) => release_transferred(owner), + None => release_made(unsafe { ID3D12CommandAllocator::from_raw(raw as *mut c_void) }), } } } @@ -305,22 +398,27 @@ fn release_submit_pins(s: &mut State, entries: &[SubmitEntry]) { } } -fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &ID3D12Fence, value: u64) -> u64 { +fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &ID3D12Fence, value: u64) -> (u64, Vec<ID3D12Fence>) { let mut backing_mark_writes = 0; + let mut replaced = Vec::new(); for entry in entries { if let Some(backing) = entry.backing { backing_mark_writes += 1; - s.backings.entry(backing).or_default().marks.insert(queue, (fence.clone(), value)); + if let Some((old, _)) = backing_mut(s, backing).marks.insert(queue, (fence.clone(), value)) { + replaced.push(old); + } } if s.list_lifetimes.get(&entry.list) == Some(&entry.lifetime) { - s.last_submit.insert( + if let Some(old) = s.last_submit.insert( entry.list, LastSubmit { queue, fence: fence.clone(), value, recording: entry.recording }, - ); + ) { + replaced.push(old.fence); + } } } release_submit_pins(s, entries); - backing_mark_writes + (backing_mark_writes, replaced) } /// Capture and pin the exact backing and recording that a native submit will execute. The caller @@ -459,11 +557,12 @@ impl PendingSubmit { if s.fences.get(&key).is_none_or(|current| !Arc::ptr_eq(current, &marker)) { return false; } - let backing_mark_writes = record_submit(s, &self.entries, key, &fence, value); + let (backing_mark_writes, replaced) = record_submit(s, &self.entries, key, &fence, value); SUBMIT.lists_marked.fetch_add(self.entries.len() as u64, Ordering::Relaxed); SUBMIT.backing_mark_writes.fetch_add(backing_mark_writes, Ordering::Relaxed); self.entries.clear(); drop(g); + drop(replaced); sweep_release_owners(); true } @@ -471,8 +570,10 @@ impl PendingSubmit { #[cfg(test)] fn finish_with_mark(mut self, queue: usize, fence: &ID3D12Fence, value: u64) { let mut g = STATE.lock().unwrap(); - let _ = record_submit(g.as_mut().unwrap(), &self.entries, queue, fence, value); + let (_, replaced) = record_submit(g.as_mut().unwrap(), &self.entries, queue, fence, value); self.entries.clear(); + drop(g); + drop(replaced); } } @@ -541,7 +642,7 @@ fn move_list(s: &mut State, list: usize, backing: usize) { } } } - s.backings.entry(backing).or_default().users.insert(list); + backing_mut(s, backing).users.insert(list); } /// The PC list's final Release ended its recording. Submitted work still holds the backing @@ -549,7 +650,7 @@ fn move_list(s: &mut State, list: usize, backing: usize) { pub(super) fn forget_list(list: usize) { let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return }; - s.last_submit.remove(&list); + let last_submit = s.last_submit.remove(&list); s.recordings.remove(&list); if let Some(lifetime) = s.list_lifetimes.remove(&list) { s.submit_pins.remove(&(list, lifetime)); @@ -560,6 +661,7 @@ pub(super) fn forget_list(list: usize) { } } drop(g); + drop(last_submit); sweep_release_owners(); } @@ -705,20 +807,24 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { /// Whether the GPU may still run a recording made on the title's allocator `alloc`. pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { - let g = STATE.lock().unwrap(); - let Some(s) = g.as_ref() else { return false }; - let mine = s.cur.get(&alloc).into_iter().chain(s.aside.get(&alloc).into_iter().flatten()).chain([&alloc]); - let busy = mine.filter_map(|b| s.backings.get(b)).any(|b| { - b.submit_pins != 0 || b.marks.values().any(|(f, v)| f.GetCompletedValue() < *v) - }); - drop(g); + let (mine, probes) = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return false }; + namespace_probes(s, alloc) + }; + let busy = probes.iter().any(|probe| probe.in_flight()); + let stable = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return false }; + namespace_matches(s, alloc, &mine, &probes) + }; sweep_release_owners(); - busy + busy || !stable } /// The title's allocator `alloc` reached its logical final Release. Detach its namespace now; /// backings still used by recordings/submits retain their native owner until a later sweep. -unsafe fn forget_in(s: &mut State, alloc: usize) -> (Vec<usize>, Vec<ID3D12CommandAllocator>) { +unsafe fn forget_in(s: &mut State, alloc: usize, free: &HashSet<usize>) -> (Vec<usize>, Vec<Backing>) { s.types.remove(&alloc); let mut mine: Vec<usize> = s.aside.remove(&alloc).unwrap_or_default(); mine.extend(s.cur.remove(&alloc)); @@ -726,38 +832,49 @@ unsafe fn forget_in(s: &mut State, alloc: usize) -> (Vec<usize>, Vec<ID3D12Comma mine.sort_unstable(); mine.dedup(); let mut made = Vec::new(); - let mut owners = Vec::new(); + let mut removed = Vec::new(); for b in mine { - let free = s.backings.get(&b).is_none_or(|x| x.free()); - if !free { + if s.backings.contains_key(&b) && !free.contains(&b) { if let Some(backing) = s.backings.get_mut(&b) { backing.retire_when_free = true; } continue; } - let owner = s.backings.remove(&b).and_then(|mut gone| { + if let Some(mut gone) = s.backings.remove(&b) { for l in gone.users.drain() { s.of_list.remove(&l); } - gone.release_owner.take() - }); - if let Some(owner) = owner { - owners.push(owner); + if gone.release_owner.is_none() && b != alloc { + made.push(b); + } + removed.push(gone); } else if b != alloc { made.push(b); } } - (made, owners) + (made, removed) } pub unsafe fn forget(alloc: usize) { - let (made, owners) = { + let (made, removed) = loop { + let (mine, probes) = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return }; + namespace_probes(s, alloc) + }; + let free: HashSet<_> = probes.iter().filter(|probe| unsafe { probe.free() }).map(|probe| probe.raw).collect(); let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return }; - forget_in(s, alloc) + if namespace_matches(s, alloc, &mine, &probes) { + break forget_in(s, alloc, &free); + } }; - for owner in owners { - super::real::release_retained_allocator(owner); + for mut backing in removed { + let owner = backing.release_owner.take(); + drop(backing); + if let Some(owner) = owner { + super::real::release_retained_allocator(owner); + } } // (outside the lock: their Release comes back here) for b in made { @@ -772,18 +889,39 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option<HRESULT> { if !enabled() { return None; } - let mut g = STATE.lock().unwrap(); - let s = g.get_or_insert_with(State::default); - title_reset_in(s, alloc, |raw| super::real::reset_pc_allocator(raw)) + let a = alloc as usize; + loop { + let (mine, probes) = { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + namespace_probes(s, a) + }; + let free: HashSet<_> = probes.iter().filter(|probe| unsafe { probe.free() }).map(|probe| probe.raw).collect(); + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return None }; + if namespace_matches(s, a, &mine, &probes) { + let mut retired = Vec::new(); + let result = title_reset_in(s, alloc, &free, &mut retired, |raw| super::real::reset_pc_allocator(raw)); + drop(g); + drop(retired); + return result; + } + } } /// The allocator transition, with the PC Reset supplied so failure/retry needs no GPU in tests. -unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMut(*mut c_void) -> HRESULT) -> Option<HRESULT> { +unsafe fn title_reset_in( + s: &mut State, + alloc: *mut c_void, + free: &HashSet<usize>, + retired: &mut Vec<ID3D12Fence>, + mut reset: impl FnMut(*mut c_void) -> HRESULT, +) -> Option<HRESULT> { let a = alloc as usize; let c = s.cur.get(&a).copied().unwrap_or(a); - if s.backings.get(&c).is_none_or(|b| b.free()) { + if !s.backings.contains_key(&c) || free.contains(&c) { if let Some(b) = s.backings.get_mut(&c) { - b.marks.clear(); + retired.extend(b.marks.drain().map(|(_, (fence, _))| fence)); } if c == a { return None; @@ -792,7 +930,7 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu } let ty = *s.types.get(&a)?; // one put aside earlier that nothing uses any more, or a new one - let reuse = s.aside.get(&a).and_then(|v| v.iter().copied().find(|f| s.backings.get(f).is_none_or(|b| b.free()))); + let reuse = s.aside.get(&a).and_then(|v| v.iter().copied().find(|f| !s.backings.contains_key(f) || free.contains(f))); let next = match reuse { Some(f) => { // Keep ownership until Reset succeeds so a failure can be retried. @@ -802,7 +940,7 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu } s.aside.get_mut(&a).unwrap().retain(|&x| x != f); if let Some(b) = s.backings.get_mut(&f) { - b.marks.clear(); + retired.extend(b.marks.drain().map(|(_, (fence, _))| fence)); } f } @@ -875,12 +1013,83 @@ mod tests { } #[test] - fn list_completion_queries_run_outside_allocator_state() { + fn release_probe_retries_a_same_address_backing_replacement() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + static REPLACE: AtomicBool = AtomicBool::new(false); + static KEY: AtomicUsize = AtomicUsize::new(0); + #[repr(C)] + struct Object { vtable: *const usize, value: Cell<u64>, refs: Cell<u32> } + unsafe extern "system" fn completed(this: *mut c_void) -> u64 { + if REPLACE.swap(false, Ordering::Relaxed) { + let gone = { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let key = KEY.load(Ordering::Relaxed); + let gone = s.backings.remove(&key).unwrap(); + backing_mut(s, key); + gone + }; + drop(gone); + } + (*this.cast::<Object>()).value.get() + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let o = &*this.cast::<Object>(); + o.refs.set(o.refs.get() + 1); + o.refs.get() + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let o = &*this.cast::<Object>(); + o.refs.set(o.refs.get() - 1); + o.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + const SLOT: usize = size_of::<usize>(); + let mut fence_vtable = [unexpected_call as usize; size_of::<ID3D12Fence_Vtbl>() / SLOT]; + fence_vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize; + fence_vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize; + fence_vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + let allocator_vtable = [unexpected_call as usize, add_ref as usize, release as usize]; + let mut fence_object = Object { vtable: fence_vtable.as_ptr(), value: Cell::new(1), refs: Cell::new(1) }; + let mut allocator_object = Object { vtable: allocator_vtable.as_ptr(), value: Cell::new(0), refs: Cell::new(2) }; + let fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut fence_object).cast()) }; + let root = unsafe { ID3D12CommandAllocator::from_raw(std::ptr::from_mut(&mut allocator_object).cast()) }; + let caller_probe = unsafe { ID3D12CommandAllocator::from_raw(root.as_raw()) }; + let key = root.as_raw() as usize; + let first_generation = { + let mut g = STATE.lock().unwrap(); + let backing = backing_mut(g.get_or_insert_with(State::default), key); + backing.marks.insert(7, (fence.clone(), 2)); + backing.generation + }; + KEY.store(key, Ordering::Relaxed); + REPLACE.store(true, Ordering::Relaxed); + let retained = unsafe { retain_release_probe(caller_probe.as_raw()) }; + if retained { std::mem::forget(caller_probe) } else { drop(caller_probe) } + let replacement = { + let mut g = STATE.lock().unwrap(); + g.as_mut().unwrap().backings.remove(&key).unwrap() + }; + assert!(!replacement.release_owner.is_some()); + assert_ne!(replacement.generation, first_generation); + drop(replacement); + drop(root); + drop(fence); + assert!(!retained, "the replacement must be probed before accepting the caller's reference"); + assert_eq!((allocator_object.refs.get(), fence_object.refs.get()), (0, 0)); + } + + #[test] + fn completion_queries_run_outside_allocator_state() { use std::cell::Cell; use std::mem::{offset_of, size_of}; - use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; static OUTSIDE: AtomicBool = AtomicBool::new(false); + static MUTATE: AtomicBool = AtomicBool::new(false); + static MUTATE_BACKING: AtomicUsize = AtomicUsize::new(0); #[repr(C)] struct Fence { vtable: *const usize, @@ -888,7 +1097,17 @@ mod tests { refs: Cell<u32>, } unsafe extern "system" fn completed(this: *mut c_void) -> u64 { - OUTSIDE.store(STATE.try_lock().is_ok(), Ordering::Relaxed); + let outside = STATE.try_lock().is_ok(); + OUTSIDE.store(outside, Ordering::Relaxed); + if outside && MUTATE.swap(false, Ordering::Relaxed) { + let mut g = STATE.lock().unwrap(); + if let Some(backing) = g + .as_mut() + .and_then(|s| s.backings.get_mut(&MUTATE_BACKING.load(Ordering::Relaxed))) + { + backing.submit_pins += 1; + } + } (*this.cast::<Fence>()).value.get() } unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { @@ -930,6 +1149,30 @@ mod tests { assert!(!in_flight(list)); assert!(OUTSIDE.load(Ordering::Relaxed), "completed polling must not hold STATE"); + let alloc = 0x7ffe_6a02usize; + { + let mut g = STATE.lock().unwrap(); + backing_mut(g.as_mut().unwrap(), alloc).marks.insert(0x81, (fence.clone(), 2)); + } + OUTSIDE.store(false, Ordering::Relaxed); + assert!(unsafe { allocator_in_flight(alloc) }); + assert!(OUTSIDE.load(Ordering::Relaxed), "allocator polling must not hold STATE"); + + object.value.set(2); + MUTATE_BACKING.store(alloc, Ordering::Relaxed); + MUTATE.store(true, Ordering::Relaxed); + OUTSIDE.store(false, Ordering::Relaxed); + assert!( + unsafe { allocator_in_flight(alloc) }, + "a state change during the unlocked probe must fail closed", + ); + assert!(OUTSIDE.load(Ordering::Relaxed), "allocator callback must be able to reenter STATE"); + + let backing = { + let mut g = STATE.lock().unwrap(); + g.as_mut().unwrap().backings.remove(&alloc).unwrap() + }; + drop(backing); { let mut g = STATE.lock().unwrap(); let s = g.as_mut().unwrap(); @@ -1108,7 +1351,7 @@ mod tests { let mut state = State::default(); state.cur.insert(alloc, made); state.aside.insert(alloc, vec![made, alloc, made]); - let (release, owners) = unsafe { forget_in(&mut state, alloc) }; + let (release, owners) = unsafe { forget_in(&mut state, alloc, &HashSet::new()) }; assert_eq!(release, vec![made]); assert!(owners.is_empty()); assert!(!state.cur.contains_key(&alloc) && !state.aside.contains_key(&alloc)); @@ -1267,7 +1510,7 @@ mod tests { s.aside.insert(alloc, vec![next]); s.backings.insert(next, Backing::default()); unsafe { - title_reset_in(s, alloc as *mut c_void, |candidate| { + title_reset_in(s, alloc as *mut c_void, &HashSet::from([next]), &mut Vec::new(), |candidate| { assert_eq!(candidate as usize, next); 0 }) @@ -1356,7 +1599,7 @@ mod tests { let s = g.as_mut().unwrap(); assert!(!s.backings[&alloc].users.contains(&list)); assert!(!s.submit_pins.keys().any(|&(p, _)| p == list), "a released address is not pinned against a later object"); - assert!(!unsafe { s.backings[&alloc].free() }); + assert!(!unsafe { backing_free_for_test(&s.backings[&alloc]) }); s.backings.get_mut(&alloc).unwrap().submit_pins = 0; } unsafe { forget(alloc) }; @@ -1374,7 +1617,7 @@ mod tests { for _ in 0..2 { let hr = unsafe { - title_reset_in(&mut s, alloc as *mut c_void, |raw| { + title_reset_in(&mut s, alloc as *mut c_void, &HashSet::from([spare]), &mut Vec::new(), |raw| { calls.push(raw as usize); crate::util::E_FAIL }) @@ -1388,7 +1631,7 @@ mod tests { } let hr = unsafe { - title_reset_in(&mut s, alloc as *mut c_void, |raw| { + title_reset_in(&mut s, alloc as *mut c_void, &HashSet::from([spare]), &mut Vec::new(), |raw| { calls.push(raw as usize); 0 }) @@ -1448,7 +1691,7 @@ mod tests { let s = g.as_ref().unwrap(); !s.of_list.contains_key(&first) && s.of_list.get(&second) == Some(&alloc) && s.backings[&alloc].users == HashSet::from([second]) - && !unsafe { s.backings[&alloc].free() } + && !unsafe { backing_free_for_test(&s.backings[&alloc]) } }; super::super::list_x::on_release(second); super::super::list_x::on_release(first); // duplicate cleanup is harmless @@ -1456,10 +1699,10 @@ mod tests { let g = STATE.lock().unwrap(); let s = g.as_ref().unwrap(); !s.of_list.contains_key(&second) && s.backings[&alloc].users.is_empty() - && s.backings[&alloc].marks.len() == 1 && !unsafe { s.backings[&alloc].free() } + && s.backings[&alloc].marks.len() == 1 && !unsafe { backing_free_for_test(&s.backings[&alloc]) } }; fence.value.set(7); - let reusable = unsafe { STATE.lock().unwrap().as_ref().unwrap().backings[&alloc].free() }; + let reusable = unsafe { backing_free_for_test(&STATE.lock().unwrap().as_ref().unwrap().backings[&alloc]) }; // Clean up the synthetic COM pointer before assertions, including on the old code. unsafe { forget(alloc) }; assert!(first_removed, "another live recording must remain while the released list goes"); From 3a984e35782b8110e8949e2789caac67c82951d9 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:56:36 -0800 Subject: [PATCH 124/265] D3D12.X: promote deferred compute before list preparation Correctness-critical deferred dispatches marked their pipeline wanted only after command-list split allocation and reset. Publish demand first so foreground worker promotion and compiler admission overlap that native preparation. Bounded waits and the immediate wait after a failed split retain their existing behavior. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 8 +++---- crates/xcl/src/hle/d3d12x/list_x.rs | 34 +++++++++++++++++++++-------- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 02c43da04e..3414e2e27b 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -295,8 +295,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); let raw_pso = with(this, |s| s.pso); let unbuilt_compute = signature_dispatches(sig) && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso); - if unbuilt_compute && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { - return super::pso_async::need_by_submit(raw_pso); + if unbuilt_compute && super::list_x::defer(this, raw_pso, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { + return; } let (pso, bound_unbuilt) = super::pso_async::resolve_wait_bound(raw_pso); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); @@ -938,8 +938,8 @@ fn dispatch_groups(pso: usize, dims: [u32; 3], flags: u32) -> Option<([u32; 3], /// `Dispatch` / `DispatchX(x, y, z, flags)`. pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { let pso = with(this, |s| s.pso); - if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z, flags)) { - return super::pso_async::need_by_submit(pso); + if super::pso_async::is_pending(pso) && super::list_x::defer(this, pso, super::list_x::Deferred::Dispatch(x, y, z, flags)) { + return; } let pso = super::pso_async::resolve_wait(pso); let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ba60ebf730..a69b70b74a 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3202,12 +3202,14 @@ fn wait_target_after_split(list: *mut c_void, placement: WaitPlacement, continua } /// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. -pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { +pub(super) unsafe fn defer(list: *mut c_void, pso: usize, what: Deferred) -> bool { // A bounded bind records now and waits for the same bound. Deferring it only adds a segment; // thousands of these exhausted command-list memory in a retail title with a 1 ms budget. - if !defer_pipeline_wait(super::pso_async::waits_bounded(), || { - split_recording(list, SegmentReason::DeferredDispatch(what)).is_some() - }) { + if !defer_pipeline_wait( + super::pso_async::waits_bounded(), + || super::pso_async::need_by_submit(pso), + || split_recording(list, SegmentReason::DeferredDispatch(what)).is_some(), + ) { return false; } static N: AtomicU64 = AtomicU64::new(0); @@ -3218,8 +3220,15 @@ pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { true } -fn defer_pipeline_wait(waits_bounded: bool, split: impl FnOnce() -> bool) -> bool { - !waits_bounded && split() +fn defer_pipeline_wait(waits_bounded: bool, demand: impl FnOnce(), split: impl FnOnce() -> bool) -> bool { + if waits_bounded { + return false; + } + // The split can allocate and reset native objects. Let the worker and its compiler/driver + // admission run concurrently with that preparation; a failed split waits for the same build + // immediately in the caller. + demand(); + split() } /// Records the deferred dispatches of `wrapper`'s recording, waiting for their pipelines as a bind did. @@ -6052,11 +6061,18 @@ mod tests { } #[test] - fn bounded_pipeline_wait_does_not_allocate_a_deferred_segment() { + fn bounded_wait_skips_defer_and_unbounded_demand_precedes_split() { + let demanded = std::cell::Cell::new(0); let mut splits = 0; - assert!(!defer_pipeline_wait(true, || { splits += 1; true })); + assert!(!defer_pipeline_wait(true, || demanded.set(demanded.get() + 1), || { splits += 1; true })); + assert_eq!(demanded.get(), 0); assert_eq!(splits, 0); - assert!(defer_pipeline_wait(false, || { splits += 1; true })); + assert!(defer_pipeline_wait(false, || demanded.set(demanded.get() + 1), || { + assert_eq!(demanded.get(), 1, "pipeline demand must be visible before split preparation"); + splits += 1; + true + })); + assert_eq!(demanded.get(), 1); assert_eq!(splits, 1, "the default still defers to the submit"); } From 23d7f4e810c2e63e6b34c0436d6bcab06f6eeea2 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:01:22 -0800 Subject: [PATCH 125/265] D3D12.X: serialize title texture uploads per queue The title-texture upload cache held one global mutex across fence creation, signaling, polling, and bounded waits. Lease an address-generation state from the registry and serialize only that queue, retaining removed generations through in-flight operations. Drop completed staging after the queue-local lock is released. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 88 +++++++++++++++++---- 1 file changed, 72 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ac5aa76762..778ca8c643 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1274,7 +1274,21 @@ struct QueueUploads { unsafe impl Send for QueueUploads {} -static ON_QUEUE: Mutex<BTreeMap<usize, QueueUploads>> = Mutex::new(BTreeMap::new()); +type QueueUploadState = Arc<Mutex<Option<QueueUploads>>>; + +/// Queue-local serialization for upload retirement. The registry is held only long enough to +/// acquire a strong state lease; driver calls and waits on one title queue do not block another. +static ON_QUEUE: Mutex<BTreeMap<usize, QueueUploadState>> = Mutex::new(BTreeMap::new()); + +fn queue_upload_state(key: usize) -> QueueUploadState { + Arc::clone( + ON_QUEUE + .lock() + .unwrap() + .entry(key) + .or_insert_with(|| Arc::new(Mutex::new(None))), + ) +} /// Drop completed uploads cached for a retired title queue after releasing the cache lock. pub(super) fn forget_queue(id: super::present::QueueId) { @@ -1297,11 +1311,13 @@ unsafe fn title_queue_for(dev: &ID3D12Device, title: Option<&ID3D12CommandQueue> (qd?.as_raw() == dev.as_raw()).then(|| q.clone()) } -unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u32) { +unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u32) -> Vec<texture::InFlight> { + let mut retired = Vec::new(); let done = q.fence.GetCompletedValue(); while q.in_flight.front().is_some_and(|&(v, _)| v <= done) { let (_, f) = q.in_flight.pop_front().unwrap(); q.bytes -= f.bytes; + retired.push(f); } while q.bytes > cap { let Some(&(v, _)) = q.in_flight.front() else { break }; @@ -1310,7 +1326,9 @@ unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u } let (_, f) = q.in_flight.pop_front().unwrap(); q.bytes -= f.bytes; + retired.push(f); } + retired } unsafe fn submit_on_title_queue( @@ -1326,30 +1344,35 @@ unsafe fn submit_on_title_queue( super::vram::before_execute(queue); let (failed, f) = texture::submit_batch_with_zero_mips(dev, queue, batch, zero_mips)?; let Some(f) = f else { return Ok(failed) }; - let mut g = ON_QUEUE.lock().unwrap(); let key = queue.as_raw() as usize; - if !g.contains_key(&key) { + let state = queue_upload_state(key); + let mut slot = state.lock().unwrap(); + if slot.is_none() { match dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) { Ok(fence) => { - g.insert(key, QueueUploads { fence, value: 0, in_flight: std::collections::VecDeque::new(), bytes: 0 }); + *slot = Some(QueueUploads { fence, value: 0, in_flight: std::collections::VecDeque::new(), bytes: 0 }); } Err(e) => { + drop(slot); texture::drop_after_wait(f, texture::wait(dev, queue))?; return Err(e.to_string()); } } } - let q = g.get_mut(&key).unwrap(); + let q = slot.as_mut().unwrap(); q.value += 1; if let Err(e) = super::real::native_queue_signal(queue, &q.fence, q.value) { q.value -= 1; + drop(slot); texture::drop_after_wait(f, texture::wait(dev, queue))?; return Err(e.to_string()); } q.bytes += f.bytes; let v = q.value; q.in_flight.push_back((v, f)); - reclaim(dev, q, IN_FLIGHT_BYTES, 10_000); + let retired = reclaim(dev, q, IN_FLIGHT_BYTES, 10_000); + drop(slot); + drop(retired); Ok(failed) } @@ -2581,12 +2604,15 @@ mod tests { } upload(0x5E); { - let mut g = ON_QUEUE.lock().unwrap(); - let q = g.get_mut(&key).unwrap(); + let state = ON_QUEUE.lock().unwrap().get(&key).unwrap().clone(); + let mut slot = state.lock().unwrap(); + let q = slot.as_mut().unwrap(); assert_eq!(q.value, 3); - reclaim(dev, q, 0, 10_000); + let retired = reclaim(dev, q, 0, 10_000); assert!(q.in_flight.is_empty() && q.bytes == 0, "over the cap the oldest uploads are waited for and released"); assert!(q.fence.GetCompletedValue() >= 3); + drop(slot); + drop(retired); } assert_eq!(read_r8(dev, &queue, &texture), vec![0x5E; 64 * 64]); ON_QUEUE.lock().unwrap().remove(&key); @@ -2662,18 +2688,24 @@ mod tests { let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x77; 64 * 64] }]; own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); { - let mut g = ON_QUEUE.lock().unwrap(); - let q = g.get_mut(&key).unwrap(); - reclaim(dev, q, 0, 50); + let state = ON_QUEUE.lock().unwrap().get(&key).unwrap().clone(); + let mut slot = state.lock().unwrap(); + let q = slot.as_mut().unwrap(); + let retired = reclaim(dev, q, 0, 50); assert_eq!(q.in_flight.len(), 1, "a batch the GPU has not run stays in flight when its wait times out"); assert!(q.bytes > 0); + drop(slot); + drop(retired); } gate.Signal(1).unwrap(); { - let mut g = ON_QUEUE.lock().unwrap(); - let q = g.get_mut(&key).unwrap(); - reclaim(dev, q, 0, 10_000); + let state = ON_QUEUE.lock().unwrap().get(&key).unwrap().clone(); + let mut slot = state.lock().unwrap(); + let q = slot.as_mut().unwrap(); + let retired = reclaim(dev, q, 0, 10_000); assert!(q.in_flight.is_empty() && q.bytes == 0); + drop(slot); + drop(retired); } assert_eq!(read_r8(dev, &queue, &texture), vec![0x77; 64 * 64]); ON_QUEUE.lock().unwrap().remove(&key); @@ -4200,4 +4232,28 @@ mod tests { // Different device always starts a new batch. assert!(!batch_fits(1, 4096, 1, 2, 4096)); } + + #[test] + fn title_queue_upload_states_are_leased_and_serialized_per_queue() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let (first_key, second_key) = (0x7ffe_7100usize, 0x7ffe_7200usize); + ON_QUEUE.lock().unwrap().remove(&first_key); + ON_QUEUE.lock().unwrap().remove(&second_key); + + let first = queue_upload_state(first_key); + let second = queue_upload_state(second_key); + let first_guard = first.lock().unwrap(); + assert!(ON_QUEUE.try_lock().is_ok(), "one queue must not hold the upload registry"); + assert!(second.try_lock().is_ok(), "one queue must not serialize another queue's uploads"); + + let removed = ON_QUEUE.lock().unwrap().remove(&first_key).unwrap(); + assert!(Arc::ptr_eq(&first, &removed), "registry removal returns the leased generation"); + let replacement = queue_upload_state(first_key); + assert!(!Arc::ptr_eq(&first, &replacement), "raw-address reuse gets a fresh queue-local state"); + + drop(first_guard); + drop(removed); + ON_QUEUE.lock().unwrap().remove(&first_key); + ON_QUEUE.lock().unwrap().remove(&second_key); + } } From 395103150d23c1b8ee5f3a58f0691f1d6b00d476 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:01:44 -0800 Subject: [PATCH 126/265] D3D12.X: poll VRAM retirement fences outside registry locks VRAM reclamation queried every retirement fence while holding the device-wide registry. Snapshot strong exact fence owners, poll and deduplicate them unlocked, then sweep current batches against those observations. Concurrent higher or new marks remain retired, and completed heaps and COM owners drop after the lock. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/vram.rs | 77 +++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index b35a310514..945c1f12a1 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1139,6 +1139,17 @@ impl<H, F: Clone> RetireQueue<H, F> { Vec::new() } + /// Strong owners of every fence whose completion can change a sweep decision. The caller + /// polls them after dropping the retirement-state lock, then rechecks the current batches. + fn completion_fences(&self) -> Vec<F> { + let mut fences: Vec<_> = self.fences.values().map(|(fence, _)| fence.clone()).collect(); + for batch in &self.batches { + fences.extend(batch.unmap_mark.as_ref().map(|(fence, _)| fence.clone())); + fences.extend(batch.marks.iter().map(|(fence, _)| fence.clone())); + } + fences + } + /// Reap completed batches and prune dead-queue fences once completed; caller drops outside locks. fn sweep_with(&mut self, live_queues: &HashSet<usize>, mut completed: impl FnMut(&F) -> u64) -> (Vec<RetiringBatch<H, F>>, Vec<F>) { let (mut done, mut kept) = (Vec::new(), Vec::new()); @@ -1157,6 +1168,10 @@ impl<H, F: Clone> RetireQueue<H, F> { } } +fn observed_completion<F>(observed: &[(F, u64)], fence: &F, mut same: impl FnMut(&F, &F) -> bool) -> u64 { + observed.iter().find_map(|(known, value)| same(known, fence).then_some(*value)).unwrap_or(0) +} + unsafe impl Send for RetireQueue<ID3D12Heap, ID3D12Fence> {} static RETIRE: Mutex<Option<std::collections::HashMap<usize, RetireQueue<ID3D12Heap, ID3D12Fence>>>> = Mutex::new(None); @@ -1208,17 +1223,33 @@ unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueu unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_reclaimed: Vec<ID3D12Heap>, unmap_mark: Option<(ID3D12Fence, u64)>, extra_queue: Option<&ID3D12CommandQueue>) { let queues = collect_device_queues(dev_key, extra_queue); let live_keys: HashSet<usize> = queues.iter().map(|&(k, _)| k).collect(); - let _drop_outside_locks = { + let (immediate, mut probes) = { let mut guard = RETIRE.lock().unwrap(); let map = guard.get_or_insert_with(std::collections::HashMap::new); if newly_reclaimed.is_empty() && !map.contains_key(&dev_key) { return; } let rq = map.entry(dev_key).or_insert_with(RetireQueue::new); let before = rq.batches.len(); let immediate = rq.retire_with(newly_reclaimed, unmap_mark, &queues, || dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok(), |q, f, v| super::real::native_queue_signal(q, f, v).is_ok()); - let (done, pruned) = rq.sweep_with(&live_keys, |f| f.GetCompletedValue()); - RETIRING_BATCHES.fetch_add(rq.batches.len().wrapping_sub(before), std::sync::atomic::Ordering::AcqRel); - (immediate, done, pruned) + RETIRING_BATCHES.fetch_add(rq.batches.len() - before, std::sync::atomic::Ordering::AcqRel); + (immediate, rq.completion_fences()) }; + // Deduplication and every COM call/drop happen without RETIRE held. The strong snapshots keep + // raw addresses from being reused while results are identified by their exact fence object. + probes.sort_unstable_by_key(|fence| fence.as_raw() as usize); + probes.dedup_by_key(|fence| fence.as_raw() as usize); + let observed: Vec<_> = probes.into_iter().map(|fence| { + let completed = fence.GetCompletedValue(); + (fence, completed) + }).collect(); + let (done, pruned) = { + let mut guard = RETIRE.lock().unwrap(); + let Some(rq) = guard.as_mut().and_then(|map| map.get_mut(&dev_key)) else { return }; + rq.sweep_with(&live_keys, |fence| { + observed_completion(&observed, fence, |known, current| known.as_raw() == current.as_raw()) + }) + }; + RETIRING_BATCHES.fetch_sub(done.len(), std::sync::atomic::Ordering::AcqRel); + drop((immediate, done, pruned, observed)); } /// Before GPU work on `queue`: have it wait for every tile mapping made so far on its device, @@ -1748,6 +1779,44 @@ mod tests { assert_eq!(rq.retire_with(vec![303], None, &[] as &[(usize, usize)], mk, |_, _, _| true), vec![303]); } + #[test] + fn retirement_completion_poll_is_unlocked_and_new_marks_fail_closed() { + use std::sync::{atomic::{AtomicU64, Ordering}, Arc}; + let first = Arc::new(AtomicU64::new(1)); + let late = Arc::new(AtomicU64::new(0)); + let state = Mutex::new(RetireQueue::<u32, Arc<AtomicU64>>::new()); + { + let mut rq = state.lock().unwrap(); + rq.fences.insert(1, (first.clone(), 1)); + rq.batches.push(RetiringBatch { heaps: vec![101], unmap_mark: None, marks: vec![(first.clone(), 1)] }); + } + + let probes = state.lock().unwrap().completion_fences(); + let mut inserted = false; + let observed: Vec<_> = probes.into_iter().map(|fence| { + assert!(state.try_lock().is_ok(), "completion polling held retirement state"); + if !inserted { + inserted = true; + state.lock().unwrap().batches.extend([ + RetiringBatch { heaps: vec![202], unmap_mark: None, marks: vec![(first.clone(), 2)] }, + RetiringBatch { heaps: vec![303], unmap_mark: None, marks: vec![(late.clone(), 1)] }, + ]); + } + let completed = fence.load(Ordering::SeqCst); + (fence, completed) + }).collect(); + + let (done, pruned) = state.lock().unwrap().sweep_with(&HashSet::from([1]), |fence| { + observed_completion(&observed, fence, Arc::ptr_eq) + }); + assert_eq!(done.iter().flat_map(|batch| &batch.heaps).copied().collect::<Vec<_>>(), [101]); + assert!(pruned.is_empty()); + let rq = state.lock().unwrap(); + assert_eq!(rq.batches.len(), 2); + assert_eq!(rq.batches[0].heaps, [202], "a higher requirement added during the poll must be tested against the observed value"); + assert_eq!(rq.batches[1].heaps, [303], "a new fence added during the poll had no observation and must remain retired"); + } + #[test] fn forgetting_queue_cache_preserves_inflight_batch_marks() { use std::sync::{atomic::AtomicU64, Arc}; From 547f32118fe66de6f15855ff8c431e44dd82466d Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:02:20 -0800 Subject: [PATCH 127/265] D3D12.X: publish texture downloads outside the fence registry Fence completion held the global download registry across polling, readback mapping, reverse tiling, and title-memory writes. Detach one fence's ordered batches under per-fence processing and installation markers, publish them unlocked, and restore unresolved work before concurrent arrivals. Cache every exposed completion so withholding remains monotonic. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 192 ++++++++++++++++++-- 1 file changed, 180 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ac5aa76762..ba3a1987fb 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2123,11 +2123,65 @@ pub(super) struct ReadyDownload { res: usize, generation: u64, target: usize, fo struct FenceDownloads { fence: ID3D12Fence, value: u64, downloads: Vec<Option<ReadyDownload>> } -static FENCE_DOWNLOADS: Mutex<Vec<FenceDownloads>> = Mutex::new(Vec::new()); +#[derive(Default)] +struct FenceDownloadState { + batches: Vec<FenceDownloads>, + /// A detached fence is being published outside this mutex. Its mirrored completion must + /// remain hidden until the owner restores any work which could not be published. + processing: BTreeSet<usize>, + /// Ties which have claimed a fence but have not installed their batch yet. Native polling, + /// event arming, and reservation bookkeeping stay outside this mutex during that interval. + tying: BTreeMap<usize, usize>, +} + +impl FenceDownloadState { + /// Register an installer. True means this is the first pending work for this fence and must + /// ensure that a safe baseline exists. Production fences are AddRef-retained for the process + /// lifetime, so their raw addresses cannot be reused while this state matters. + fn begin_tie(&mut self, fence: usize) -> bool { + let initialize_safe = !self.processing.contains(&fence) + && !self.tying.contains_key(&fence) + && !self.batches.iter().any(|batch| batch.fence.as_raw() as usize == fence); + *self.tying.entry(fence).or_insert(0) += 1; + initialize_safe + } + + fn finish_tie(&mut self, fence: usize) { + let count = self.tying.get_mut(&fence).expect("finishing an unregistered texture download tie"); + *count -= 1; + if *count == 0 { self.tying.remove(&fence); } + } + + fn tie_in_progress(&self, fence: usize) -> bool { + self.tying.contains_key(&fence) + } + + fn begin_processing(&mut self, fence: usize) -> bool { + !self.tie_in_progress(fence) && self.processing.insert(fence) + } + + fn any_pending(&self) -> bool { + !self.batches.is_empty() || !self.processing.is_empty() || !self.tying.is_empty() + } +} + +static FENCE_DOWNLOADS: Mutex<FenceDownloadState> = Mutex::new(FenceDownloadState { + batches: Vec::new(), + processing: BTreeSet::new(), + tying: BTreeMap::new(), +}); static DOWNLOADS_PENDING: AtomicBool = AtomicBool::new(false); static SCHEDULED_DOWNLOADS: Mutex<BTreeSet<(usize, u64, u64, u32, u64)>> = Mutex::new(BTreeSet::new()); static SAFE_FENCE_VALUES: Mutex<BTreeMap<usize, u64>> = Mutex::new(BTreeMap::new()); +fn ensure_safe_baseline(values: &mut BTreeMap<usize, u64>, fence: usize) { + values.entry(fence).or_insert(0); +} + +fn note_safe_value(values: &mut BTreeMap<usize, u64>, fence: usize, value: u64) { + values.entry(fence).and_modify(|safe| *safe = (*safe).max(value)).or_insert(value); +} + fn writer_at(entry: &Entry, subresource: usize) -> Option<GpuWriter> { match entry.gpu_writers.as_slice() { [] => None, [writer] => *writer, writers => writers.get(subresource).copied().flatten(), @@ -2234,7 +2288,14 @@ fn rollback_reservations(keys: &[(usize, u64, u64, u32, u64)]) { pub(super) unsafe fn tie_downloads(fence: *mut c_void, value: u64, downloads: Vec<ReadyDownload>) { if downloads.is_empty() { return } let Some(fence) = ID3D12Fence::from_raw_borrowed(&fence).cloned() else { return }; - SAFE_FENCE_VALUES.lock().unwrap().insert(fence.as_raw() as usize, super::real::native_fence_completed(&fence)); + let key = fence.as_raw() as usize; + { + let mut state = FENCE_DOWNLOADS.lock().unwrap(); + if state.begin_tie(key) { + ensure_safe_baseline(&mut SAFE_FENCE_VALUES.lock().unwrap(), key); + } + DOWNLOADS_PENDING.store(true, Ordering::Release); + } let event = super::fence_x::wake_event(); for download in &downloads { download.ticket.arm(event); } { @@ -2243,8 +2304,12 @@ pub(super) unsafe fn tie_downloads(fence: *mut c_void, value: u64, downloads: Ve scheduled.insert((download.res, download.generation, write.writer.queue.generation, write.subresource, write.writer.epoch)); } } } - FENCE_DOWNLOADS.lock().unwrap().push(FenceDownloads { fence: fence.clone(), value, downloads: downloads.into_iter().map(Some).collect() }); - DOWNLOADS_PENDING.store(true, Ordering::Release); + { + let mut state = FENCE_DOWNLOADS.lock().unwrap(); + state.batches.push(FenceDownloads { fence: fence.clone(), value, downloads: downloads.into_iter().map(Some).collect() }); + state.finish_tie(key); + DOWNLOADS_PENDING.store(true, Ordering::Release); + } let _ = fence.SetEventOnCompletion(value, event); } @@ -2322,14 +2387,46 @@ fn batch_ready(blocked: &mut bool, target: u64, completed: u64) -> bool { if *blocked || target > completed { *blocked = true; false } else { true } } +fn take_matching<T>(values: &mut Vec<T>, mut matches: impl FnMut(&T) -> bool) -> Vec<T> { + let mut taken = Vec::new(); + let mut kept = Vec::with_capacity(values.len()); + for value in values.drain(..) { + if matches(&value) { taken.push(value) } else { kept.push(value) } + } + *values = kept; + taken +} + +/// Put detached older work before work tied to the same fence while it was being processed. +fn restore_before_matching<T>(values: &mut Vec<T>, mut older: Vec<T>, matches: impl FnMut(&T) -> bool) { + older.extend(take_matching(values, matches)); + values.extend(older); +} + +fn matching_through<T>(values: &[T], completed: u64, mut target: impl FnMut(&T) -> Option<u64>) -> bool { + values.iter().any(|value| target(value).is_some_and(|target| target <= completed)) +} + /// Apply every completed download through `value`. False withholds the title's mirrored fence /// value until a transiently unavailable readback or destination can be retried. pub(super) fn complete_fence_downloads(fence: usize, value: u64) -> bool { if !DOWNLOADS_PENDING.load(Ordering::Acquire) { return true } - let mut batches = FENCE_DOWNLOADS.lock().unwrap(); + let mut batches = { + let mut state = FENCE_DOWNLOADS.lock().unwrap(); + if !state.begin_processing(fence) { + return false; + } + let batches = take_matching(&mut state.batches, |batch| batch.fence.as_raw() as usize == fence); + if batches.is_empty() { + state.processing.remove(&fence); + note_safe_value(&mut SAFE_FENCE_VALUES.lock().unwrap(), fence, value); + return true; + } + batches + }; let mut ok = true; let mut blocked = false; - for batch in batches.iter_mut().filter(|b| b.fence.as_raw() as usize == fence) { + for batch in &mut batches { if !batch_ready(&mut blocked, batch.value, value) { ok &= batch.value > value; continue } for download in &mut batch.downloads { let Some(ready) = download.as_ref() else { continue }; @@ -2352,15 +2449,30 @@ pub(super) fn complete_fence_downloads(fence: usize, value: u64) -> bool { blocked |= batch.downloads.iter().any(Option::is_some); } batches.retain(|batch| batch.downloads.iter().any(Option::is_some)); - DOWNLOADS_PENDING.store(!batches.is_empty(), Ordering::Release); - if ok { - SAFE_FENCE_VALUES.lock().unwrap().entry(fence).and_modify(|safe| *safe = (*safe).max(value)).or_insert(value); + { + let mut state = FENCE_DOWNLOADS.lock().unwrap(); + // A tie which arrived while this fence was detached was not in `batches`. If the caller's + // completed value already covers it, this pass cannot expose that value until another pass + // publishes the arrival. Check while holding the same lock which accepts new ties. + ok &= !matching_through(&state.batches, value, |batch| { + (batch.fence.as_raw() as usize == fence).then_some(batch.value) + }); + ok &= !state.tie_in_progress(fence); + restore_before_matching(&mut state.batches, batches, |batch| batch.fence.as_raw() as usize == fence); + state.processing.remove(&fence); + if ok { + note_safe_value(&mut SAFE_FENCE_VALUES.lock().unwrap(), fence, value); + } + DOWNLOADS_PENDING.store(state.any_pending(), Ordering::Release); } ok } pub(super) fn safe_fence_value(fence: usize, native: u64) -> u64 { - if !DOWNLOADS_PENDING.load(Ordering::Acquire) { return native } + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { + note_safe_value(&mut SAFE_FENCE_VALUES.lock().unwrap(), fence, native); + return native; + } if native != u64::MAX && complete_fence_downloads(fence, native) { native } else { @@ -2372,8 +2484,8 @@ pub(super) fn safe_fence_value(fence: usize, native: u64) -> u64 { pub(super) fn poll_fence_downloads() { if !DOWNLOADS_PENDING.load(Ordering::Acquire) { return } let pending: Vec<_> = { - let batches = FENCE_DOWNLOADS.lock().unwrap(); - batches.iter().map(|batch| batch.fence.clone()).collect() + let state = FENCE_DOWNLOADS.lock().unwrap(); + state.batches.iter().map(|batch| batch.fence.clone()).collect() }; for fence in pending { let value = unsafe { super::real::native_fence_completed(&fence) }; @@ -3013,6 +3125,62 @@ mod tests { assert!(!batch_ready(&mut blocked, 10, 10), "later batch passed an incomplete one"); } + #[test] + fn detached_fence_batches_return_before_concurrent_arrivals() { + let mut batches = vec![(1, "old-a"), (2, "other-a"), (1, "old-b")]; + let mut detached = take_matching(&mut batches, |batch| batch.0 == 1); + assert_eq!(detached, [(1, "old-a"), (1, "old-b")]); + assert_eq!(batches, [(2, "other-a")]); + + // The first old batch completed while detached; two newer batches were tied meanwhile. + detached.remove(0); + batches.extend([(1, "new-a"), (2, "other-b"), (1, "new-b")]); + restore_before_matching(&mut batches, detached, |batch| batch.0 == 1); + assert_eq!( + batches.iter().filter(|batch| batch.0 == 1).map(|batch| batch.1).collect::<Vec<_>>(), + ["old-b", "new-a", "new-b"], + "an unresolved older download must keep later fence work hidden", + ); + assert_eq!( + batches.iter().filter(|batch| batch.0 == 2).map(|batch| batch.1).collect::<Vec<_>>(), + ["other-a", "other-b"], + "processing one fence must preserve another fence's order", + ); + } + + #[test] + fn concurrent_arrival_through_completed_value_withholds_visibility() { + let arrivals = [(2, 4), (1, 11), (2, 7)]; + let for_fence_one = |batch: &(usize, u64)| (batch.0 == 1).then_some(batch.1); + assert!(!matching_through(&arrivals, 10, for_fence_one), "a future arrival does not hide value 10"); + + let arrivals = [(2, 4), (1, 11), (1, 10)]; + assert!( + matching_through(&arrivals, 10, for_fence_one), + "a concurrent arrival covered by value 10 must be published before value 10 is visible", + ); + } + + #[test] + fn in_progress_tie_withholds_fence_processing() { + let mut state = FenceDownloadState::default(); + let mut safe = BTreeMap::from([(7, 99)]); + if state.begin_tie(7) { ensure_safe_baseline(&mut safe, 7); } + assert_eq!(safe[&7], 99, "first pending work preserves the last exposed completion"); + if state.begin_tie(7) { note_safe_value(&mut safe, 7, 123); } + assert_eq!(safe[&7], 99, "another installer must not advance the safe baseline"); + assert!(state.any_pending()); + assert!(!state.begin_processing(7), "completion must not pass a partially installed tie"); + state.finish_tie(7); + assert!(!state.begin_processing(7), "every installer must finish before completion starts"); + state.finish_tie(7); + assert!(state.begin_processing(7)); + + assert!(FenceDownloadState::default().begin_tie(8)); + ensure_safe_baseline(&mut safe, 8); + assert_eq!(safe[&8], 0, "a fence never exposed before starts from the conservative baseline"); + } + #[test] fn download_reservation_rollback_clears_every_key() { let keys = [(0xBAD0, 1, 2, 3, 4), (0xBAD1, 5, 6, 7, 8)]; From bd36a0b86599802be802b1456d0b50afa679329d Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:06:58 -0800 Subject: [PATCH 128/265] D3D12.X: isolate VRAM retirement work per device The global retirement registry still covered fence creation, queue signals, polling, and device mutation. Lease an exact per-device state from the registry, preserving same-device signal ordering while allowing unrelated devices and cache invalidation to proceed independently. Removed generations remain owned through active operations. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/vram.rs | 74 ++++++++++++++++++++++++------- 1 file changed, 58 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 945c1f12a1..ccd6d674f7 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1174,9 +1174,23 @@ fn observed_completion<F>(observed: &[(F, u64)], fence: &F, mut same: impl FnMut unsafe impl Send for RetireQueue<ID3D12Heap, ID3D12Fence> {} -static RETIRE: Mutex<Option<std::collections::HashMap<usize, RetireQueue<ID3D12Heap, ID3D12Fence>>>> = Mutex::new(None); +type DeviceRetire = std::sync::Arc<Mutex<RetireQueue<ID3D12Heap, ID3D12Fence>>>; + +/// Per-device retirement states. The registry is held only while acquiring a strong state lease; +/// fence creation, queue signaling, polling, and COM destruction never hold it. +static RETIRE: Mutex<Option<std::collections::HashMap<usize, DeviceRetire>>> = Mutex::new(None); static RETIRING_BATCHES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +fn device_retire_state(dev_key: usize) -> DeviceRetire { + RETIRE + .lock() + .unwrap() + .get_or_insert_with(std::collections::HashMap::new) + .entry(dev_key) + .or_insert_with(|| std::sync::Arc::new(Mutex::new(RetireQueue::new()))) + .clone() +} + /// Remove raw queue-address state before a retired queue's final owner can be released. Fence /// objects are extracted from both locks and dropped afterward; retirement batches keep clones. pub(super) fn forget_queue(id: super::present::QueueId) { @@ -1187,15 +1201,11 @@ pub(super) fn forget_queue(id: super::present::QueueId) { pages.waited.remove(&queue); } } - let gone = { - let mut retire = RETIRE.lock().unwrap(); - retire - .as_mut() - .into_iter() - .flat_map(|devices| devices.values_mut()) - .filter_map(|queues| queues.forget_queue(queue)) - .collect::<Vec<_>>() - }; + let states: Vec<_> = RETIRE.lock().unwrap().as_ref().into_iter().flat_map(|devices| devices.values().cloned()).collect(); + let gone: Vec<_> = states + .iter() + .filter_map(|state| state.lock().unwrap().forget_queue(queue)) + .collect(); drop(gone); } @@ -1223,11 +1233,15 @@ unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueu unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_reclaimed: Vec<ID3D12Heap>, unmap_mark: Option<(ID3D12Fence, u64)>, extra_queue: Option<&ID3D12CommandQueue>) { let queues = collect_device_queues(dev_key, extra_queue); let live_keys: HashSet<usize> = queues.iter().map(|&(k, _)| k).collect(); + let state = if newly_reclaimed.is_empty() { + let registry = RETIRE.lock().unwrap(); + let Some(state) = registry.as_ref().and_then(|map| map.get(&dev_key)).cloned() else { return }; + state + } else { + device_retire_state(dev_key) + }; let (immediate, mut probes) = { - let mut guard = RETIRE.lock().unwrap(); - let map = guard.get_or_insert_with(std::collections::HashMap::new); - if newly_reclaimed.is_empty() && !map.contains_key(&dev_key) { return; } - let rq = map.entry(dev_key).or_insert_with(RetireQueue::new); + let mut rq = state.lock().unwrap(); let before = rq.batches.len(); let immediate = rq.retire_with(newly_reclaimed, unmap_mark, &queues, || dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok(), |q, f, v| super::real::native_queue_signal(q, f, v).is_ok()); RETIRING_BATCHES.fetch_add(rq.batches.len() - before, std::sync::atomic::Ordering::AcqRel); @@ -1242,8 +1256,7 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla (fence, completed) }).collect(); let (done, pruned) = { - let mut guard = RETIRE.lock().unwrap(); - let Some(rq) = guard.as_mut().and_then(|map| map.get_mut(&dev_key)) else { return }; + let mut rq = state.lock().unwrap(); rq.sweep_with(&live_keys, |fence| { observed_completion(&observed, fence, |known, current| known.as_raw() == current.as_raw()) }) @@ -1817,6 +1830,35 @@ mod tests { assert_eq!(rq.batches[1].heaps, [303], "a new fence added during the poll had no observation and must remain retired"); } + #[test] + fn device_retirement_state_is_leased_outside_the_registry() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let (first_key, second_key) = (0x7ffe_7600usize, 0x7ffe_7700usize); + { + let mut registry = RETIRE.lock().unwrap(); + let map = registry.get_or_insert_with(std::collections::HashMap::new); + map.remove(&first_key); + map.remove(&second_key); + } + + let first = device_retire_state(first_key); + let second = device_retire_state(second_key); + let first_guard = first.lock().unwrap(); + assert!(RETIRE.try_lock().is_ok(), "one device's driver turn must not hold the retirement registry"); + assert!(second.try_lock().is_ok(), "one device must not serialize another device's retirement work"); + + let removed = RETIRE.lock().unwrap().as_mut().unwrap().remove(&first_key).unwrap(); + assert!(std::sync::Arc::ptr_eq(&first, &removed)); + let replacement = device_retire_state(first_key); + assert!(!std::sync::Arc::ptr_eq(&first, &replacement), "a removed device key gets a fresh state while old work retains its lease"); + + drop(first_guard); + drop(removed); + let mut registry = RETIRE.lock().unwrap(); + registry.as_mut().unwrap().remove(&first_key); + registry.as_mut().unwrap().remove(&second_key); + } + #[test] fn forgetting_queue_cache_preserves_inflight_batch_marks() { use std::sync::{atomic::AtomicU64, Arc}; From 6dd9d53f1e140d4c69b61745c4ec41ed079344f8 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:09:36 -0800 Subject: [PATCH 129/265] D3D12.X: reuse bounded workers for texture detiling Large title-texture refreshes created and joined up to eight OS threads for every upload batch. Reuse a process-lifetime bounded detile pool while preserving synchronous batch ordering and source timing. Missing or panicked work requeues only the exact CPU-owned texture generation and clears its premature content fingerprint. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 186 ++++++++++++++++++-- 1 file changed, 169 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 0beaa697e6..258e8f168c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -37,8 +37,8 @@ extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; } -/// (device, address its bytes are read from, layout, states) of an upload -type Upload = (usize, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>); +/// (device, address its bytes are read from, layout, states, registration generation) of an upload +type Upload = (usize, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>, u64); /// One incarnation of a title command queue. The raw address alone can be reused after release. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -1000,7 +1000,8 @@ unsafe fn refresh_once(queue: *mut c_void) { PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p) + .map(|r| (r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone(), e.generation))) }) .collect() }); @@ -1122,7 +1123,7 @@ unsafe fn seed_stream_recheck(todo: &[(ID3D12Resource, Upload)], watched: &[(usi return; } let mut seeded = Vec::new(); - for (r, (_, src, tex, _)) in todo { + for (r, (_, src, tex, _, _)) in todo { let size = tex.size() as usize; if size == 0 || range_is_fully_watched(*src, size, watched) { continue; @@ -1376,6 +1377,33 @@ unsafe fn submit_on_title_queue( Ok(failed) } +/// A preparation worker failed before this exact batch could be submitted. A texture still at the +/// captured registration generation is made pending again; a replacement, removal, GPU writer, or +/// non-CPU-backed entry owns its own state and must not be changed by the stale work item. +fn requeue_failed_preparation(picked: &[(ID3D12Resource, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>, u64)]) { + let keys: Vec<_> = picked.iter().map(|(resource, _, _, _, generation)| (resource.as_raw() as usize, *generation)).collect(); + let mut table = TEXTURES.lock().unwrap(); + let added = requeue_generations(&mut table, &keys); + if !added.is_empty() { + PENDING.fetch_add(added.len(), Ordering::Relaxed); + } + drop(table); + let mut content = LAST_CONTENT.lock().unwrap(); + for resource in added { content.remove(&resource); } +} + +fn requeue_generations(table: &mut Table, keys: &[(usize, u64)]) -> Vec<usize> { + let mut added = Vec::new(); + for &(resource, generation) in keys { + let Some(entry) = table.by_res.get_mut(&resource) else { continue }; + if entry.generation == generation && entry.cpu_backed && !entry.gpu_written && !entry.pending { + entry.pending = true; + added.push(resource); + } + } + added +} + /// The uploads `todo`, in batches of up to `BATCH_BYTES` and `BATCH_ITEMS` (one list and one wait each). unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12CommandQueue>) { static N: AtomicU64 = AtomicU64::new(0); @@ -1389,11 +1417,11 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12C let mut picked = Vec::new(); let mut bytes = 0usize; let mut device = 0usize; - while let Some((_, (dev, _, tex, _))) = todo.peek() { + while let Some((_, (dev, _, tex, _, _))) = todo.peek() { if !batch_fits(picked.len(), bytes, device, *dev, tex.size() as usize) { break; } - let (r, (dev, va, tex, states)) = todo.next().unwrap(); + let (r, (dev, va, tex, states, generation)) = todo.next().unwrap(); // The same bytes as at this texture's last upload: nothing to do. The write watch is // per page and a title writes next to its textures (and rewrites what it wrote): a // retail title's video planes and UI targets went up again for every submit, ~25 MB @@ -1410,16 +1438,20 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12C } device = dev; bytes += tex.size() as usize; - picked.push((r, va, tex, states)); + picked.push((r, va, tex, states, generation)); } if picked.is_empty() { continue; } - let subs = subresources_of_all(&picked, bytes); + let Some(subs) = subresources_of_all(&picked, bytes) else { + requeue_failed_preparation(&picked); + warn("a texture preparation worker stopped; the batch will be retried"); + continue; + }; let mut batch = Vec::with_capacity(picked.len()); let mut zero_mips = Vec::new(); let level_pages = super::vram::level_pages(); - for ((r, va, _, states), subs) in picked.into_iter().zip(subs) { + for ((r, va, _, states, _), subs) in picked.into_iter().zip(subs) { if super::present::trace_frame() { note_content(va, &r, &subs); } @@ -1718,16 +1750,94 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec<u8> { /// Batches of at least this many bytes are detiled on several threads (`subresources_of_all`) const PARALLEL_BYTES: usize = 1 << 20; +struct DetileJob { + index: usize, + va: usize, + tex: Arc<xg::Texture>, + done: std::sync::mpsc::Sender<(usize, Option<Vec<Subresource>>)>, +} + +struct DetilePool { + jobs: std::sync::mpsc::Sender<DetileJob>, + workers: usize, +} + +fn detile_pool() -> &'static DetilePool { + static POOL: std::sync::OnceLock<DetilePool> = std::sync::OnceLock::new(); + POOL.get_or_init(|| { + let wanted = std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8); + let (jobs, receive) = std::sync::mpsc::channel::<DetileJob>(); + let receive = Arc::new(Mutex::new(receive)); + let mut workers = 0; + for k in 0..wanted { + let receive = Arc::clone(&receive); + let made = std::thread::Builder::new().name(format!("xcl-detile-{k}")).spawn(move || loop { + let job = { + let receive = receive.lock().unwrap_or_else(|e| e.into_inner()); + receive.recv() + }; + let Ok(job) = job else { break }; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { + subresources(job.va, &job.tex) + })) + .ok(); + let _ = job.done.send((job.index, result)); + }); + if made.is_ok() { + workers += 1; + } + } + DetilePool { jobs, workers } + }) +} + /// `subresources` of every texture of a batch (`bytes` of them), in order: on several threads -/// when the batch is big. They were read and detiled one after another in the title's own -/// submit – most of a retail game's render thread while it streamed textures the CPU writes. -unsafe fn subresources_of_all(picked: &[(ID3D12Resource, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>)], bytes: usize) -> Vec<Vec<Subresource>> { - let picked: Vec<(usize, &xg::Texture)> = picked.iter().map(|(_, va, tex, _)| (*va, &**tex)).collect(); - let threads = if bytes < PARALLEL_BYTES { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8) }; - subresources_on(&picked, threads) +/// when the batch is big. Process-lifetime workers avoid creating and joining up to eight OS +/// threads in every title submit. None means a worker or its queue stopped; the caller retries the +/// exact registration generation rather than uploading an incomplete texture. +unsafe fn subresources_of_all( + picked: &[(ID3D12Resource, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>, u64)], + bytes: usize, +) -> Option<Vec<Vec<Subresource>>> { + let work: Vec<_> = picked.iter().map(|(_, va, tex, _, _)| (*va, Arc::clone(tex))).collect(); + pooled_subresources(&work, bytes) +} + +unsafe fn pooled_subresources(picked: &[(usize, Arc<xg::Texture>)], bytes: usize) -> Option<Vec<Vec<Subresource>>> { + if bytes < PARALLEL_BYTES || picked.len() <= 1 { + return Some(picked.iter().map(|(va, tex)| subresources(*va, tex)).collect()); + } + let pool = detile_pool(); + if pool.workers == 0 { + return None; + } + let (done, results) = std::sync::mpsc::channel(); + for (index, (va, tex)) in picked.iter().enumerate() { + if pool.jobs.send(DetileJob { index, va: *va, tex: Arc::clone(tex), done: done.clone() }).is_err() { + return None; + } + } + drop(done); + ordered_subresources(picked.len(), results) +} + +fn ordered_subresources( + count: usize, + results: impl IntoIterator<Item = (usize, Option<Vec<Subresource>>)>, +) -> Option<Vec<Vec<Subresource>>> { + let mut out: Vec<Option<Vec<Subresource>>> = (0..count).map(|_| None).collect(); + let mut failed = false; + for (index, result) in results { + match (out.get_mut(index), result) { + (Some(slot), Some(result)) if slot.is_none() => *slot = Some(result), + _ => failed = true, + } + } + (!failed).then(|| out.into_iter().collect()).flatten() } /// `subresources` of each (address, texture), in order, on up to `threads` threads. +#[cfg(test)] unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> Vec<Vec<Subresource>> { let threads = threads.min(picked.len()); if threads <= 1 { @@ -3361,19 +3471,61 @@ mod tests { console_desc(3, 128, 32, 3, 2, 28, 0x105), console_desc(3, 64, 64, 1, 1, 28, 0x105), ]; - let textures: Vec<xg::Texture> = descs.iter().map(|d| xg::Texture::new(d).unwrap()).collect(); + let textures: Vec<Arc<xg::Texture>> = descs.iter().map(|d| Arc::new(xg::Texture::new(d).unwrap())).collect(); // each texture's console memory: distinct bytes per texture let mems: Vec<Vec<u8>> = textures.iter().enumerate().map(|(t, x)| (0..x.size() as usize).map(|i| (i * 7 + t * 61) as u8).collect()).collect(); - let picked: Vec<(usize, &xg::Texture)> = mems.iter().zip(&textures).map(|(m, x)| (m.as_ptr() as usize, x)).collect(); + let picked: Vec<(usize, &xg::Texture)> = mems.iter().zip(&textures).map(|(m, x)| (m.as_ptr() as usize, &**x)).collect(); unsafe { let one = subresources_on(&picked, 1); assert!(one.iter().all(|s| !s.is_empty()), "a texture gave no subresources"); for threads in [2, 3, 8] { assert!(subresources_on(&picked, threads) == one, "{threads} threads differ from one"); } + let pooled: Vec<_> = picked.iter().zip(&textures).map(|(&(va, _), tex)| (va, Arc::clone(tex))).collect(); + assert_eq!(pooled_subresources(&pooled, usize::MAX), Some(one), "persistent workers preserve order and content"); } } + #[test] + fn failed_preparation_requeues_only_the_exact_cpu_generation() { + let tex = Arc::new(xg::Texture::new(&console_desc(3, 4, 4, 1, 1, 28, 0x105)).unwrap()); + let entry = |generation, gpu_written| Entry { + device: 0, + committed_bytes: 0, + va: 0x1000, + src: 0x1000, + in_gpu_view: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written, + gpu_writers: Vec::new(), + cpu_backed: true, + placed: false, + unmapped: false, + generation, + }; + let mut table = Table::new(); + table.by_res.insert(1, entry(7, false)); + table.by_res.insert(2, entry(8, false)); + table.by_res.insert(3, entry(9, true)); + + assert_eq!(requeue_generations(&mut table, &[(1, 7), (2, 7), (3, 9), (4, 1)]), [1]); + assert!(table.by_res[&1].pending); + assert!(!table.by_res[&2].pending, "a replacement generation owns its own pending state"); + assert!(!table.by_res[&3].pending, "GPU-written content must not be overwritten by a retry"); + } + + #[test] + fn preparation_results_fail_closed_on_worker_loss() { + assert!(ordered_subresources(2, [(1, Some(Vec::new())), (0, Some(Vec::new()))]).is_some()); + assert!(ordered_subresources(2, [(0, Some(Vec::new()))]).is_none(), "a missing worker result must fail the batch"); + assert!( + ordered_subresources(2, [(0, Some(Vec::new())), (1, None)]).is_none(), + "a caught worker panic must fail the batch", + ); + } + #[test] fn small_cpu_filled_target_accepts_wide_glyph_atlas_and_rejects_large_or_depth() { assert!(is_small_cpu_filled_target(2048, 128, 1, 0x300005), "2048x128 R8 glyph atlas must sync"); From d451e402f49f3c76b535a59aef7c9dd8e4ec22b7 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:11:24 -0800 Subject: [PATCH 130/265] D3D12.X: reset allocator backings outside global state Allocator Reset, GetDevice, and CreateCommandAllocator ran while holding the pool-wide state lock. Reserve one exact title operation, retain strong candidate owners, perform driver work unlocked, and commit only if the namespace and every backing field still match. Failures and stale completions cancel only their own token and roll back outside the lock. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 325 +++++++++++++++++------- 1 file changed, 238 insertions(+), 87 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 62b71b99a8..9e17bcc14f 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -48,6 +48,9 @@ struct State { aside: HashMap<usize, Vec<usize>>, backings: HashMap<usize, Backing>, next_backing_generation: u64, + /// Title allocator -> exact reset operation currently outside this lock. + resetting: HashMap<usize, u64>, + next_reset_generation: u64, of_list: HashMap<usize, usize>, /// title allocator → the type of the lists on it types: HashMap<usize, i32>, @@ -66,6 +69,20 @@ struct State { submit_pins: HashMap<(usize, u64), usize>, } +enum ResetWork { + Reset { owner: ID3D12CommandAllocator, swap: bool }, + Create { owner: ID3D12CommandAllocator, ty: i32 }, +} + +struct ResetClaim { + alloc: usize, + current: usize, + token: u64, + mine: Vec<usize>, + probes: Vec<BackingProbe>, + work: ResetWork, +} + #[derive(Clone)] struct LastSubmit { queue: usize, @@ -171,6 +188,26 @@ fn namespace_matches(state: &State, alloc: usize, mine: &[usize], probes: &[Back }) } +fn reserve_reset(state: &mut State, alloc: usize) -> Option<u64> { + if state.resetting.contains_key(&alloc) { + return None; + } + state.next_reset_generation = state.next_reset_generation.wrapping_add(1).max(1); + let token = state.next_reset_generation; + state.resetting.insert(alloc, token); + Some(token) +} + +fn cancel_reset(state: &mut State, alloc: usize, token: u64) { + if state.resetting.get(&alloc) == Some(&token) { + state.resetting.remove(&alloc); + } +} + +fn run_reset(raw: *mut c_void, reset: impl FnOnce(*mut c_void) -> HRESULT) -> HRESULT { + reset(raw) +} + #[cfg(test)] unsafe fn backing_free_for_test(backing: &Backing) -> bool { BackingProbe::new(0, backing).free() } @@ -826,6 +863,7 @@ pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { /// backings still used by recordings/submits retain their native owner until a later sweep. unsafe fn forget_in(s: &mut State, alloc: usize, free: &HashSet<usize>) -> (Vec<usize>, Vec<Backing>) { s.types.remove(&alloc); + s.resetting.remove(&alloc); let mut mine: Vec<usize> = s.aside.remove(&alloc).unwrap_or_default(); mine.extend(s.cur.remove(&alloc)); mine.push(alloc); @@ -890,77 +928,145 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option<HRESULT> { return None; } let a = alloc as usize; - loop { + let claim = loop { let (mine, probes) = { let mut g = STATE.lock().unwrap(); let s = g.get_or_insert_with(State::default); + if s.resetting.contains_key(&a) { + return Some(crate::util::E_FAIL); + } namespace_probes(s, a) }; let free: HashSet<_> = probes.iter().filter(|probe| unsafe { probe.free() }).map(|probe| probe.raw).collect(); let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return None }; - if namespace_matches(s, a, &mine, &probes) { - let mut retired = Vec::new(); - let result = title_reset_in(s, alloc, &free, &mut retired, |raw| super::real::reset_pc_allocator(raw)); - drop(g); - drop(retired); - return result; + if !namespace_matches(s, a, &mine, &probes) { + continue; } - } -} - -/// The allocator transition, with the PC Reset supplied so failure/retry needs no GPU in tests. -unsafe fn title_reset_in( - s: &mut State, - alloc: *mut c_void, - free: &HashSet<usize>, - retired: &mut Vec<ID3D12Fence>, - mut reset: impl FnMut(*mut c_void) -> HRESULT, -) -> Option<HRESULT> { - let a = alloc as usize; - let c = s.cur.get(&a).copied().unwrap_or(a); - if !s.backings.contains_key(&c) || free.contains(&c) { - if let Some(b) = s.backings.get_mut(&c) { - retired.extend(b.marks.drain().map(|(_, (fence, _))| fence)); - } - if c == a { - return None; - } - return Some(reset(c as *mut c_void)); - } - let ty = *s.types.get(&a)?; - // one put aside earlier that nothing uses any more, or a new one - let reuse = s.aside.get(&a).and_then(|v| v.iter().copied().find(|f| !s.backings.contains_key(f) || free.contains(f))); - let next = match reuse { - Some(f) => { - // Keep ownership until Reset succeeds so a failure can be retried. - let hr = reset(f as *mut c_void); - if hr < 0 { - return Some(hr); - } - s.aside.get_mut(&a).unwrap().retain(|&x| x != f); - if let Some(b) = s.backings.get_mut(&f) { - retired.extend(b.marks.drain().map(|(_, (fence, _))| fence)); + if s.resetting.contains_key(&a) { + return Some(crate::util::E_FAIL); + } + let current = s.cur.get(&a).copied().unwrap_or(a); + if !s.backings.contains_key(¤t) || free.contains(¤t) { + if current == a { + let retired = s.backings.get_mut(¤t) + .map(|backing| backing.marks.drain().map(|(_, (fence, _))| fence).collect::<Vec<_>>()) + .unwrap_or_default(); + drop(g); + drop(retired); + drop(probes); + return None; } - f + let raw = current as *mut c_void; + let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&raw).cloned() else { return Some(crate::util::E_FAIL) }; + let token = reserve_reset(s, a).unwrap(); + break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: false } }; + } + let Some(&ty) = s.types.get(&a) else { return Some(crate::util::E_FAIL) }; + if let Some(candidate) = s.aside.get(&a).and_then(|values| values.iter().copied().find(|raw| !s.backings.contains_key(raw) || free.contains(raw))) { + let raw = candidate as *mut c_void; + let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&raw).cloned() else { return Some(crate::util::E_FAIL) }; + let token = reserve_reset(s, a).unwrap(); + break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: true } }; + } + let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&alloc).cloned() else { return Some(crate::util::E_FAIL) }; + let token = reserve_reset(s, a).unwrap(); + break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Create { owner, ty } }; + }; + + let ResetClaim { alloc, current, token, mine, probes, work } = claim; + match work { + ResetWork::Reset { owner, swap } => { + let candidate = owner.as_raw() as usize; + let hr = run_reset(owner.as_raw(), |raw| super::real::reset_pc_allocator(raw)); + let mut retired = Vec::new(); + let result = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return Some(crate::util::E_FAIL) }; + if hr >= 0 && commit_reset(s, alloc, current, candidate, token, &mine, &probes, swap, false, &mut retired) { + hr + } else { + cancel_reset(s, alloc, token); + if hr < 0 { hr } else { crate::util::E_FAIL } + } + }; + drop(retired); + drop(owner); + Some(result) } - None => { - let this = ID3D12CommandAllocator::from_raw_borrowed(&alloc)?; + ResetWork::Create { owner, ty } => { let mut dev: Option<ID3D12Device> = None; - this.GetDevice(&mut dev).ok()?; - let made: ID3D12CommandAllocator = dev?.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE(ty)).ok()?; + let made: Result<ID3D12CommandAllocator, HRESULT> = match owner.GetDevice(&mut dev) { + Err(error) => Err(error.code().0), + Ok(()) => match dev { + Some(dev) => dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE(ty)).map_err(|error| error.code().0), + None => Err(crate::util::E_FAIL), + }, + }; + let made = match made { + Ok(made) => made, + Err(error) => { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { cancel_reset(s, alloc, token); } + return Some(error); + } + }; let raw = made.into_raw(); - // (made through the title's device it is adopted already) if !super::real::is_adopted(raw) { super::real::adopt(raw, super::real::Kind::CommandAllocator); } - s.made += 1; - raw as usize + let mut retired = Vec::new(); + let committed = { + let mut g = STATE.lock().unwrap(); + g.as_mut().is_some_and(|s| commit_reset(s, alloc, current, raw as usize, token, &mine, &probes, true, true, &mut retired)) + }; + drop(retired); + drop(owner); + if committed { + Some(0) + } else { + drop(ID3D12CommandAllocator::from_raw(raw)); + Some(crate::util::E_FAIL) + } } - }; - s.aside.entry(a).or_default().push(c); - s.cur.insert(a, next); + } +} + +fn commit_reset( + s: &mut State, + alloc: usize, + current: usize, + candidate: usize, + token: u64, + mine: &[usize], + probes: &[BackingProbe], + swap: bool, + created: bool, + retired: &mut Vec<ID3D12Fence>, +) -> bool { + if s.resetting.get(&alloc) != Some(&token) || !namespace_matches(s, alloc, mine, probes) { + cancel_reset(s, alloc, token); + return false; + } + if swap && !created { + let Some(position) = s.aside.get(&alloc).and_then(|values| values.iter().position(|raw| *raw == candidate)) else { + cancel_reset(s, alloc, token); + return false; + }; + s.aside.get_mut(&alloc).unwrap().remove(position); + } + if let Some(backing) = s.backings.get_mut(&candidate) { + retired.extend(backing.marks.drain().map(|(_, (fence, _))| fence)); + } + if !swap { + cancel_reset(s, alloc, token); + return true; + } + s.aside.entry(alloc).or_default().push(current); + s.cur.insert(alloc, candidate); + if created { s.made += 1; } s.swaps += 1; + cancel_reset(s, alloc, token); if s.swaps.is_power_of_two() { let aside: usize = s.aside.values().map(|v| v.len()).sum(); crate::xlog_info!( @@ -969,7 +1075,7 @@ unsafe fn title_reset_in( s.made ); } - Some(0) + true } #[cfg(test)] @@ -1509,16 +1615,14 @@ mod tests { let s = g.as_mut().unwrap(); s.aside.insert(alloc, vec![next]); s.backings.insert(next, Backing::default()); - unsafe { - title_reset_in(s, alloc as *mut c_void, &HashSet::from([next]), &mut Vec::new(), |candidate| { - assert_eq!(candidate as usize, next); - 0 - }) - } + let (mine, probes) = namespace_probes(s, alloc); + let token = reserve_reset(s, alloc).unwrap(); + let mut retired = Vec::new(); + commit_reset(s, alloc, alloc, next, token, &mine, &probes, true, false, &mut retired) }) .join() .unwrap(); - assert_eq!(reset, Some(0), "the reserved backing is put aside instead of Reset"); + assert!(reset, "the reserved backing is put aside instead of Reset"); assert_eq!(reset_list(list, alloc, -1, |backing| { assert_eq!(backing, next); 0 @@ -1606,44 +1710,91 @@ mod tests { } #[test] - fn a_spare_whose_reset_fails_stays_available_for_retry() { + fn reset_reservation_runs_unlocked_and_failed_attempt_keeps_the_spare() { let (alloc, spare, list) = (0x1000usize, 0x2000usize, 0x3000usize); let mut s = State::default(); s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); move_list(&mut s, list, alloc); s.aside.insert(alloc, vec![spare]); s.backings.insert(spare, Backing::default()); - let mut calls = Vec::new(); - - for _ in 0..2 { - let hr = unsafe { - title_reset_in(&mut s, alloc as *mut c_void, &HashSet::from([spare]), &mut Vec::new(), |raw| { - calls.push(raw as usize); - crate::util::E_FAIL - }) - }; - assert_eq!(hr, Some(crate::util::E_FAIL)); - assert_eq!(s.aside.get(&alloc), Some(&vec![spare]), "the failed candidate is still owned and reusable"); - assert!(!s.cur.contains_key(&alloc), "the current backing did not change"); - assert_eq!(s.of_list.get(&list), Some(&alloc)); - assert!(s.backings[&alloc].users.contains(&list), "the old recording is still held"); - assert_eq!((s.made, s.swaps), (0, 0)); - } - - let hr = unsafe { - title_reset_in(&mut s, alloc as *mut c_void, &HashSet::from([spare]), &mut Vec::new(), |raw| { - calls.push(raw as usize); - 0 - }) - }; - assert_eq!(hr, Some(0)); - assert_eq!(calls, vec![spare; 3], "all attempts used the same spare without creating another"); + let (mine, probes) = namespace_probes(&s, alloc); + let token = reserve_reset(&mut s, alloc).unwrap(); + let hr = run_reset(spare as *mut c_void, |raw| { + assert_eq!(raw as usize, spare); + crate::util::E_FAIL + }); + assert_eq!(hr, crate::util::E_FAIL); + cancel_reset(&mut s, alloc, token); + assert_eq!(s.aside.get(&alloc), Some(&vec![spare]), "the failed candidate is still owned and reusable"); + assert!(!s.cur.contains_key(&alloc), "the current backing did not change"); + + let token = reserve_reset(&mut s, alloc).unwrap(); + let mut retired = Vec::new(); + assert!(commit_reset(&mut s, alloc, alloc, spare, token, &mine, &probes, true, false, &mut retired)); assert_eq!(s.cur.get(&alloc), Some(&spare)); assert_eq!(s.aside.get(&alloc), Some(&vec![alloc]), "only the successful reset switches backings"); assert_eq!(s.of_list.get(&list), Some(&alloc), "the earlier recording stays on its original backing"); assert_eq!((s.made, s.swaps), (0, 1)); } + #[test] + fn reset_commit_rejects_reentrant_backing_mutation() { + let (alloc, spare, list) = (0x7ffe_7a10usize, 0x7ffe_7a20usize, 0x7ffe_7a30usize); + let (mine, probes, token) = { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + move_list(s, list, alloc); + s.aside.insert(alloc, vec![spare]); + backing_mut(s, spare); + let (mine, probes) = namespace_probes(s, alloc); + let token = reserve_reset(s, alloc).unwrap(); + (mine, probes, token) + }; + assert_eq!(run_reset(spare as *mut c_void, |_| { + let started = std::time::Instant::now(); + let mut state = loop { + if let Ok(state) = STATE.try_lock() { break state; } + assert!(started.elapsed() < std::time::Duration::from_secs(1), "driver Reset callback could not reenter allocator state"); + std::thread::yield_now(); + }; + state.as_mut().unwrap().backings.get_mut(&spare).unwrap().submit_pins += 1; + 0 + }), 0); + let committed = { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let committed = commit_reset(s, alloc, alloc, spare, token, &mine, &probes, true, false, &mut Vec::new()); + s.of_list.remove(&list); + s.backings.remove(&alloc); + s.backings.remove(&spare); + s.aside.remove(&alloc); + s.types.remove(&alloc); + committed + }; + assert!(!committed, "state changed during the unlocked driver call must fail closed"); + } + + #[test] + fn final_release_cancels_reset_before_raw_namespace_reuse() { + let (alloc, spare, list) = (0x7ffe_7b10usize, 0x7ffe_7b20usize, 0x7ffe_7b30usize); + let mut s = State::default(); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + move_list(&mut s, list, alloc); + s.aside.insert(alloc, vec![spare]); + backing_mut(&mut s, spare); + let (mine, probes) = namespace_probes(&s, alloc); + let old_token = reserve_reset(&mut s, alloc).unwrap(); + + let _ = unsafe { forget_in(&mut s, alloc, &HashSet::new()) }; + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.aside.insert(alloc, vec![spare]); + let new_token = reserve_reset(&mut s, alloc).unwrap(); + assert_ne!(old_token, new_token); + assert!(!commit_reset(&mut s, alloc, alloc, spare, old_token, &mine, &probes, true, false, &mut Vec::new())); + assert_eq!(s.resetting.get(&alloc), Some(&new_token), "a stale completion cannot cancel the replacement's claim"); + } + /// Final-release cleanup drops only the recording's hold: another live list and a pending /// GPU fence each still prevent reuse, then completion makes the backing reusable. #[test] From 6f2a73b4c6549f4e2925e25e49722f61f707f55e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:12:15 -0800 Subject: [PATCH 131/265] D3D12.X: poll sparse retirement fences outside global state Sparse submit preparation queried quarantine and pool fences while holding the entire sparse state. Snapshot strong exact fence owners, deduplicate and poll them unlocked, then drain only the FIFO prefix satisfied by those observations. Concurrent new fences and higher marks remain quarantined. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 72 ++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 8571e71455..a570aef890 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -719,9 +719,8 @@ impl State { /// Pools whose every tile is free again go (their video memory – and as much of the /// system's commit: a retail game's homes of physical pages left 0.75 GB of pools for /// 0.29 GB of tiles in use). Call after their tiles are unmapped and signalled. - fn retire_free_pools(&mut self) { + fn retire_free_pools_with(&mut self, done: u64) { let now = std::time::Instant::now(); - let done = unsafe { self.fence.GetCompletedValue() }; self.retired.retain(|(_, v, at)| !(done >= *v && now.duration_since(*at).as_secs() >= 2)); if self.free.len() < POOL_TILES as usize { return; @@ -743,6 +742,10 @@ impl State { } } + fn retire_free_pools(&mut self) { + self.retire_free_pools_with(unsafe { self.fence.GetCompletedValue() }); + } + /// Map `tiles` (tile addresses) of `res` (starting at `res_base`) onto pool tiles, /// batched per pool heap with contiguous runs merged into single regions. unsafe fn map_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[(usize, (u32, u32))]) { @@ -1528,10 +1531,10 @@ impl State { self.quarantined.push_back(RetiredTiles { tiles, marks: ok.then_some(marks) }); } - unsafe fn drain_quarantined(&mut self) -> bool { + unsafe fn drain_quarantined_with(&mut self, mut completed: impl FnMut(&ID3D12Fence) -> u64) -> bool { let mut freed = false; while let Some(front) = self.quarantined.front() { - let ready = front.marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)); + let ready = front.marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| completed(f) >= *v)); if !ready { break; } @@ -1546,6 +1549,10 @@ impl State { freed } + unsafe fn drain_quarantined(&mut self) -> bool { + self.drain_quarantined_with(|fence| fence.GetCompletedValue()) + } + /// The parked tiles unmapped from their windows (one call per window) and their unpinned /// pool tiles quarantined behind `self.queue` and every known title queue's completion fence. /// Pools left all free are not retired here: callers do that (`retire_free_pools`) unless @@ -1627,18 +1634,49 @@ pub fn note_watch(t: std::time::Duration, pages: usize) { WATCH[1].fetch_add(pages as u64, Ordering::Relaxed); } +fn poll_unique<F>(mut fences: Vec<F>, key: impl Fn(&F) -> usize, mut completed: impl FnMut(&F) -> u64) -> Vec<(F, u64)> { + fences.sort_unstable_by_key(&key); + fences.dedup_by(|a, b| key(a) == key(b)); + fences.into_iter().map(|fence| { + let value = completed(&fence); + (fence, value) + }).collect() +} + +fn observed_completion<F>(observed: &[(F, u64)], fence: &F, same: impl Fn(&F, &F) -> bool) -> u64 { + observed.iter().find_map(|(known, value)| same(known, fence).then_some(*value)).unwrap_or(0) +} + +/// Snapshot strong fence owners under `STATE`, then query them without it. A batch or a higher +/// mark added while polling is checked against the same observation; a new fence has no +/// observation and therefore remains quarantined. +unsafe fn poll_retirement_fences() -> Vec<(ID3D12Fence, u64)> { + let fences = { + let g = lock_state(); + let Some(s) = g.as_ref() else { return Vec::new() }; + std::iter::once(s.fence.clone()) + .chain(s.quarantined.iter().flat_map(|batch| batch.marks.iter().flatten().map(|(fence, _)| fence.clone()))) + .collect() + }; + poll_unique(fences, |fence| fence.as_raw() as usize, |fence| fence.GetCompletedValue()) +} + /// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB /// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video /// memory, and `queue` GPU-waits for that and for new tile mappings. pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) { let t0 = std::time::Instant::now(); + let observed = poll_retirement_fences(); let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; // the title's work sees what was decommitted unmapped, as it was let flushed = s.flush_parked_with(Some(queue)); - let drained = s.drain_quarantined(); + let drained = s.drain_quarantined_with(|fence| { + observed_completion(&observed, fence, |known, current| known.as_raw() == current.as_raw()) + }); if flushed || drained { - s.retire_free_pools(); + let sparse_done = observed_completion(&observed, &s.fence, |known, current| known.as_raw() == current.as_raw()); + s.retire_free_pools_with(sparse_done); } let t_locked = std::time::Instant::now(); PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Ordering::Relaxed); @@ -1859,6 +1897,28 @@ mod tests { assert!(!Arc::ptr_eq(&batch_mark, &fences[&0xA].0), "reused raw address kept the retired generation's fence"); } + #[test] + fn retirement_fence_poll_is_unlocked_and_new_requirements_fail_closed() { + use std::sync::{atomic::{AtomicU64, AtomicUsize, Ordering}, Arc}; + let first = Arc::new(AtomicU64::new(1)); + let late = Arc::new(AtomicU64::new(9)); + let state = Mutex::new(vec![first.clone(), first.clone()]); + let polls = AtomicUsize::new(0); + + let snapshot = state.lock().unwrap().clone(); + let observed = poll_unique(snapshot, |fence| Arc::as_ptr(fence) as usize, |fence| { + assert!(state.try_lock().is_ok(), "completion polling held sparse state"); + state.lock().unwrap().push(late.clone()); + polls.fetch_add(1, Ordering::Relaxed); + fence.load(Ordering::Relaxed) + }); + + assert_eq!(polls.load(Ordering::Relaxed), 1, "the same fence is queried once"); + assert_eq!(observed_completion(&observed, &first, Arc::ptr_eq), 1); + assert!(observed_completion(&observed, &first, Arc::ptr_eq) < 2, "a higher mark added during polling remains held"); + assert_eq!(observed_completion(&observed, &late, Arc::ptr_eq), 0, "a newly added fence remains held"); + } + #[test] fn quarantine_uses_installed_retirement_marks_and_fails_closed_without_one() { use std::sync::Arc; From bdce892c38181a09a9ef7ad92816d8fc97e21132 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:15:52 -0800 Subject: [PATCH 132/265] D3D12.X: enqueue sparse title waits outside global state Sparse submission preparation called the native title-queue Wait while holding the global sparse state. A driver-side callback or an unrelated sparse operation could therefore stall behind that state even though the wait only needs an exact fence/value snapshot.\n\nSerialize preparation per title queue, reserve its monotonic wait under sparse state, then enqueue the native wait after releasing that state. The per-queue gate prevents a concurrent submission from overtaking the thread that reserved its wait.\n\nChecked with the Windows GNU target; Windows MSVC runtime, GPU, and smoke tests were not available here.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 44 +++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index a570aef890..33f6c1734c 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -20,7 +20,7 @@ use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; use std::hash::{BuildHasherDefault, Hasher}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use windows::core::Interface; use windows::Win32::Foundation::{CloseHandle, HANDLE}; @@ -413,6 +413,11 @@ unsafe impl Send for State {} static STATE: Mutex<Option<State>> = Mutex::new(None); +/// Serializes sparse preparation through wait enqueue for one title queue. Without this, a +/// concurrent submission could observe a reserved `waited` value and execute before the thread +/// which reserved it has called the native queue `Wait`. +static WAIT_GATES: Mutex<FxHashMap<usize, Arc<Mutex<()>>>> = Mutex::new(FxHashMap::with_hasher(BuildHasherDefault::new())); + /// The state's queue again, outside `STATE` (`queue`). `STATE` is held around D3D12 calls (an /// upload's allocator `Reset` in `begin_slot`), and `late_release` asks for the queue from a /// resource's last `Release`, which D3D12 can make inside a call of its own on another thread @@ -437,7 +442,9 @@ pub(super) fn forget_queue(id: super::present::QueueId) { remove_queue_fence(&mut state.queue_fences, id.raw()) }) }; + let gate = WAIT_GATES.lock().unwrap().remove(&id.raw()); drop(gone); + drop(gate); } /// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY` @@ -1647,6 +1654,14 @@ fn observed_completion<F>(observed: &[(F, u64)], fence: &F, same: impl Fn(&F, &F observed.iter().find_map(|(known, value)| same(known, fence).then_some(*value)).unwrap_or(0) } +fn reserve_queue_wait(waited: &mut FxHashMap<usize, u64>, queue: usize, value: u64) -> bool { + if value == 0 || waited.get(&queue).copied().unwrap_or(0) >= value { + return false; + } + waited.insert(queue, value); + true +} + /// Snapshot strong fence owners under `STATE`, then query them without it. A batch or a higher /// mark added while polling is checked against the same observation; a new fence has no /// observation and therefore remains quarantined. @@ -1665,6 +1680,9 @@ unsafe fn poll_retirement_fences() -> Vec<(ID3D12Fence, u64)> { /// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video /// memory, and `queue` GPU-waits for that and for new tile mappings. pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) { + let q = queue.as_raw() as usize; + let queue_gate = WAIT_GATES.lock().unwrap().entry(q).or_default().clone(); + let _queue_serial = queue_gate.lock().unwrap(); let t0 = std::time::Instant::now(); let observed = poll_retirement_fences(); let mut g = lock_state(); @@ -1749,11 +1767,13 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } dirty_runs.clear(); s.scratch_runs = dirty_runs; - let q = queue.as_raw() as usize; - if s.value > 0 && s.waited.get(&q).copied().unwrap_or(0) < s.value { - let _ = super::real::native_queue_wait(queue, &s.fence, s.value); - super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &s.fence, s.value); - s.waited.insert(q, s.value); + let value = s.value; + let wait = reserve_queue_wait(&mut s.waited, q, value).then(|| (s.fence.clone(), value)); + drop(g); + drop(observed); + if let Some((fence, value)) = wait { + let _ = super::real::native_queue_wait(queue, &fence, value); + super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &fence, value); } } @@ -1919,6 +1939,18 @@ mod tests { assert_eq!(observed_completion(&observed, &late, Arc::ptr_eq), 0, "a newly added fence remains held"); } + #[test] + fn title_queue_wait_reservation_is_monotonic_and_per_queue() { + let mut waited = FxHashMap::default(); + assert!(!reserve_queue_wait(&mut waited, 1, 0)); + assert!(reserve_queue_wait(&mut waited, 1, 4)); + assert!(!reserve_queue_wait(&mut waited, 1, 4)); + assert!(!reserve_queue_wait(&mut waited, 1, 3)); + assert!(reserve_queue_wait(&mut waited, 2, 3)); + assert!(reserve_queue_wait(&mut waited, 1, 5)); + assert_eq!(waited, FxHashMap::from_iter([(1, 5), (2, 3)])); + } + #[test] fn quarantine_uses_installed_retirement_marks_and_fails_closed_without_one() { use std::sync::Arc; From 78828d4fdc0e27f61567d0edc4d804e68f1bc99c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:18:35 -0800 Subject: [PATCH 133/265] Recompiler: prune unused split-piece resource bindings Split pieces inherited the whole shader's static resource metadata even when optimization removed every handle use in that piece. Derive the reachable binding ranges after optimization and retain only matching metadata, while preserving survivor order and the shared chain root-signature ABI. The split parity fixture checks that scratch-only pieces omit the title-memory binding without changing GPU results. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/module.rs | 25 ++++++++++++++++ crates/xcl/src/gpu/dxil/module/split.rs | 39 +++++++++++++++++++++++-- crates/xcl/src/gpu/dxil/shader.rs | 11 +++++++ 3 files changed, 73 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index b9712d4b57..da9932c11d 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -817,6 +817,31 @@ impl Module { self.try_to_bitcode(triple, datalayout).unwrap_or_else(|e| panic!("DXIL builder: {e}")) } + /// Static resource ranges referenced by reachable `createHandleFromBinding` + /// calls. A dynamic binding descriptor makes the result unknowable. + pub(super) fn referenced_bindings(&self) -> Option<Vec<(u8, u32, u32, u32)>> { + let (order, _) = self.block_layout(); + let mut refs = Vec::new(); + for &block in &order { + for &inst in &self.blocks[block] { + let Op::Call(func, args) = &self.insts[inst as usize].op else { continue }; + if self.funcs[*func as usize].name != "dx.op.createHandleFromBinding" { + continue; + } + let Some(&Value::Const(bind)) = args.get(1) else { return None }; + let ConstDef::Aggregate(_, fields) = &self.consts[bind as usize] else { return None }; + let [lower, upper, space, class] = fields.as_slice() else { return None }; + refs.push(( + self.const_u64(*class)? as u8, + self.const_u64(*space)? as u32, + self.const_u64(*lower)? as u32, + self.const_u64(*upper)? as u32, + )); + } + } + Some(refs) + } + fn write_bitcode(&mut self, triple: &str, datalayout: &str) -> Vec<u8> { // Every type the writer references must exist before the type table: // pointers to the declared functions (call / metadata operands). diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 7a88b9ae11..dd3fe3e4fd 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -271,7 +271,12 @@ impl Shader { // a refused piece leaves the whole program unsplit: say so let refused = |e: String| crate::xlog_warn!("compute split: piece {} of {} refused, the program stays whole: {}", stage + 1, plan.blocks.len(), e.lines().next().unwrap_or_default()); - let blob = dst.try_finish(threads, Some(32)).map_err(|e| refused(e.to_string())).ok()?; + if !dst.m.terminated() { + dst.m.ret(); + } + dst.m.optimize(); + dst.prune_unused_bindings(); + let blob = dst.finish_optimized(threads, Some(32)).map_err(|e| refused(e.to_string())).ok()?; crate::gpu::dxil::validate::validate(&blob).map_err(refused).ok()?; Some(blob) } @@ -711,10 +716,33 @@ impl Module { #[cfg(test)] mod tests { use crate::gpu::{ - dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::{BinOp, CastOp, Pred}}, + dxil::{ + container::Stage, + kernel::{Entry, KernelOptions}, + lower::Lw, + module::{BinOp, CastOp, Pred}, + shader::{ResClass, Shader}, + }, recomp::{runner, CsInterface}, }; + #[test] + fn optimized_piece_prunes_only_unreferenced_static_bindings() { + let mut shader = Shader::new(Stage::Compute, (6, 6)); + let used = shader.raw_uav(2, 0); + let _unused = shader.cbv(7, 1, 16); + let zero = shader.m.i32c(0); + shader.raw_store(used, zero, &[zero]); + shader.m.ret(); + shader.m.optimize(); + + shader.prune_unused_bindings(); + + assert_eq!(shader.bindings.len(), 1); + assert_eq!(shader.bindings[0].class, ResClass::Uav); + assert_eq!((shader.bindings[0].space, shader.bindings[0].lower), (0, 2)); + } + #[test] fn oversized_loop_occupies_one_piece_up_to_the_hard_ceiling() { use super::{Block, Module}; @@ -844,6 +872,13 @@ mod tests { crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); let chain = chain.expect("split the synthetic program"); assert!(chain.pieces.len() >= 3); + let has_memory_binding: Vec<_> = chain.pieces.iter().map(|piece| { + crate::gpu::dxil::validate::disassemble(piece).unwrap() + .contains("ResBind { i32 0, i32 0, i32 0, i8 1 }") + }).collect(); + assert!(has_memory_binding.iter().any(|&present| present)); + assert!(has_memory_binding.iter().any(|&present| !present), + "pieces that only transport scratch must omit the title-memory binding"); let initial: Vec<_> = (1..=threads * 3).collect(); let expected: Vec<_> = initial.iter().enumerate().map(|(i, &v)| { let n = (i as u32 % 4) + 1; diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index a0a970925d..b72e1066e6 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -518,6 +518,17 @@ impl Shader { } } + /// Drop static binding metadata that this optimized shader cannot reach. + /// Dynamic binding descriptors conservatively keep the complete table. + pub(super) fn prune_unused_bindings(&mut self) { + let Some(refs) = self.m.referenced_bindings() else { return }; + self.bindings.retain(|binding| refs.iter().any(|&(class, space, lower, upper)| { + class == binding.class as u8 + && space == binding.space + && (lower..=upper).contains(&binding.lower) + })); + } + /// Writes metadata, bitcode and the signed container (panics on a builder error: tests; /// translators use [`Shader::try_finish`]). pub fn finish(self, numthreads: [u32; 3], wave_size: Option<u32>) -> Vec<u8> { From 5d1a657dc68b3ceb7982abce28cdfd51ec62756a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:19:59 -0800 Subject: [PATCH 134/265] D3D12.X: retire spare recordings and reclaim idle allocators Inactive split segments kept their allocator users alive after leaving the submission graph, and idle aside allocators retained driver storage until selected again. Detach only the retired recording association while preserving submit lifetime state. Reset idle aside backings outside allocator state, then commit once-only reset state through exact namespace tokens and backing probes. The Windows-GNU test configuration compiles. Runtime and smoke measurements require Windows hardware. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 218 +++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 1 + crates/xcl/src/hle/d3d12x/title_list.rs | 6 + 3 files changed, 216 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 9e17bcc14f..2649d631b5 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -38,6 +38,8 @@ struct Backing { release_owner: Option<ID3D12CommandAllocator>, /// Its allocator namespace is gone; release its retained/raw owner once it becomes free. retire_when_free: bool, + /// The driver Reset this backing while idle, and no recording has used it since. + already_reset: bool, } #[derive(Default)] @@ -70,7 +72,7 @@ struct State { } enum ResetWork { - Reset { owner: ID3D12CommandAllocator, swap: bool }, + Reset { owner: ID3D12CommandAllocator, swap: bool, needed: bool }, Create { owner: ID3D12CommandAllocator, ty: i32 }, } @@ -83,6 +85,14 @@ struct ResetClaim { work: ResetWork, } +struct IdleResetClaim { + alloc: usize, + token: u64, + mine: Vec<usize>, + probes: Vec<BackingProbe>, + work: Vec<(BackingProbe, ID3D12CommandAllocator)>, +} + #[derive(Clone)] struct LastSubmit { queue: usize, @@ -122,6 +132,7 @@ struct BackingProbe { submit_pins: usize, release_owner: Option<usize>, retire_when_free: bool, + already_reset: bool, } impl BackingProbe { @@ -134,6 +145,7 @@ impl BackingProbe { submit_pins: backing.submit_pins, release_owner: backing.release_owner.as_ref().map(|owner| owner.as_raw() as usize), retire_when_free: backing.retire_when_free, + already_reset: backing.already_reset, } } @@ -151,6 +163,7 @@ impl BackingProbe { && self.submit_pins == backing.submit_pins && self.release_owner == backing.release_owner.as_ref().map(|owner| owner.as_raw() as usize) && self.retire_when_free == backing.retire_when_free + && self.already_reset == backing.already_reset && self.marks.len() == backing.marks.len() && self.marks.iter().all(|(queue, fence, value)| { backing.marks.get(queue).is_some_and(|(current, current_value)| current.as_raw() == fence.as_raw() && current_value == value) @@ -441,7 +454,9 @@ fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &I for entry in entries { if let Some(backing) = entry.backing { backing_mark_writes += 1; - if let Some((old, _)) = backing_mut(s, backing).marks.insert(queue, (fence.clone(), value)) { + let backing = backing_mut(s, backing); + backing.already_reset = false; + if let Some((old, _)) = backing.marks.insert(queue, (fence.clone(), value)) { replaced.push(old); } } @@ -679,7 +694,27 @@ fn move_list(s: &mut State, list: usize, backing: usize) { } } } - backing_mut(s, backing).users.insert(list); + let backing = backing_mut(s, backing); + backing.users.insert(list); + backing.already_reset = false; +} + +/// Detach a recording that is no longer in the title list's submission graph. Its object +/// lifetime, last submit and submit pins remain, so address reuse and GPU completion stay exact. +pub(super) fn retire_recording(list: usize) { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + retire_recording_in(s, list); + drop(g); + sweep_release_owners(); +} + +fn retire_recording_in(s: &mut State, list: usize) { + if let Some(backing) = s.of_list.remove(&list) { + if let Some(backing) = s.backings.get_mut(&backing) { + backing.users.remove(&list); + } + } } /// The PC list's final Release ended its recording. Submitted work still holds the backing @@ -920,6 +955,77 @@ pub unsafe fn forget(alloc: usize) { } } +/// Reset every idle aside backing once. The namespace token and backing probes make a driver +/// callback, final Release, or newly recorded list invalidate the whole unlocked batch. +unsafe fn reclaim_idle_aside(alloc: *mut c_void) { + let a = alloc as usize; + let claim = loop { + let (mine, probes, free) = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return }; + if s.resetting.contains_key(&a) { return } + let (mine, probes) = namespace_probes(s, a); + let free = probes.iter().filter(|probe| probe.free()).map(|probe| probe.raw).collect::<HashSet<_>>(); + (mine, probes, free) + }; + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if !namespace_matches(s, a, &mine, &probes) { continue } + if s.resetting.contains_key(&a) { return } + let mut work = Vec::new(); + for raw in s.aside.get(&a).into_iter().flatten().copied() { + let Some(probe) = probes.iter().find(|probe| probe.raw == raw && free.contains(&raw) && !probe.already_reset) else { continue }; + let raw_ptr = raw as *mut c_void; + if let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&raw_ptr).cloned() { + work.push((probe.clone(), owner)); + } + } + if work.is_empty() { return } + let token = reserve_reset(s, a).unwrap(); + break IdleResetClaim { alloc: a, token, mine, probes, work }; + }; + + let IdleResetClaim { alloc, token, mine, probes, work } = claim; + let results = work.into_iter().map(|(probe, owner)| { + let ok = run_reset(owner.as_raw(), |raw| super::real::reset_pc_allocator(raw)) >= 0; + (probe, owner, ok) + }).collect::<Vec<_>>(); + let successful = results.iter().filter(|(_, _, ok)| *ok).map(|(probe, _, _)| probe.clone()).collect::<Vec<_>>(); + let mut retired = Vec::new(); + { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + commit_idle_resets(s, alloc, token, &mine, &probes, &successful, &mut retired); + } + } + drop(retired); + drop(results); +} + +fn commit_idle_resets( + s: &mut State, + alloc: usize, + token: u64, + mine: &[usize], + probes: &[BackingProbe], + successful: &[BackingProbe], + retired: &mut Vec<ID3D12Fence>, +) -> bool { + let valid = s.resetting.get(&alloc) == Some(&token) && namespace_matches(s, alloc, mine, probes); + if valid { + for probe in successful { + if s.aside.get(&alloc).is_some_and(|aside| aside.contains(&probe.raw)) { + if let Some(backing) = s.backings.get_mut(&probe.raw) { + retired.extend(backing.marks.drain().map(|(_, (fence, _))| fence)); + backing.already_reset = true; + } + } + } + } + cancel_reset(s, alloc, token); + valid +} + /// The title resets its allocator `alloc`. `None`: reset it as it is (nothing holds a /// recording on it, or this is off). `Some(hr)`: done here – the PC allocator in use was put /// aside with its recordings and another one took its place. @@ -955,19 +1061,22 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option<HRESULT> { drop(g); drop(retired); drop(probes); + reclaim_idle_aside(alloc); return None; } let raw = current as *mut c_void; let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&raw).cloned() else { return Some(crate::util::E_FAIL) }; let token = reserve_reset(s, a).unwrap(); - break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: false } }; + let needed = s.backings.get(¤t).is_none_or(|backing| !backing.already_reset); + break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: false, needed } }; } let Some(&ty) = s.types.get(&a) else { return Some(crate::util::E_FAIL) }; if let Some(candidate) = s.aside.get(&a).and_then(|values| values.iter().copied().find(|raw| !s.backings.contains_key(raw) || free.contains(raw))) { let raw = candidate as *mut c_void; let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&raw).cloned() else { return Some(crate::util::E_FAIL) }; let token = reserve_reset(s, a).unwrap(); - break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: true } }; + let needed = s.backings.get(&candidate).is_none_or(|backing| !backing.already_reset); + break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: true, needed } }; } let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&alloc).cloned() else { return Some(crate::util::E_FAIL) }; let token = reserve_reset(s, a).unwrap(); @@ -976,9 +1085,9 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option<HRESULT> { let ResetClaim { alloc, current, token, mine, probes, work } = claim; match work { - ResetWork::Reset { owner, swap } => { + ResetWork::Reset { owner, swap, needed } => { let candidate = owner.as_raw() as usize; - let hr = run_reset(owner.as_raw(), |raw| super::real::reset_pc_allocator(raw)); + let hr = if needed { run_reset(owner.as_raw(), |raw| super::real::reset_pc_allocator(raw)) } else { 0 }; let mut retired = Vec::new(); let result = { let mut g = STATE.lock().unwrap(); @@ -992,6 +1101,9 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option<HRESULT> { }; drop(retired); drop(owner); + if result >= 0 { + reclaim_idle_aside(alloc as *mut c_void); + } Some(result) } ResetWork::Create { owner, ty } => { @@ -1023,6 +1135,7 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option<HRESULT> { drop(retired); drop(owner); if committed { + reclaim_idle_aside(alloc as *mut c_void); Some(0) } else { drop(ID3D12CommandAllocator::from_raw(raw)); @@ -1057,6 +1170,7 @@ fn commit_reset( } if let Some(backing) = s.backings.get_mut(&candidate) { retired.extend(backing.marks.drain().map(|(_, (fence, _))| fence)); + backing.already_reset = true; } if !swap { cancel_reset(s, alloc, token); @@ -1737,6 +1851,90 @@ mod tests { assert_eq!((s.made, s.swaps), (0, 1)); } + #[test] + fn retired_recording_keeps_lifetime_and_submit_pin_until_exact_reuse() { + let (list, old, next) = (0x7ffe_7601usize, 0x7ffe_7602usize, 0x7ffe_7603usize); + let mut s = State::default(); + move_list(&mut s, list, old); + s.recordings.insert(list, 4); + s.list_lifetimes.insert(list, 9); + s.submit_pins.insert((list, 9), 1); + s.backings.get_mut(&old).unwrap().submit_pins = 1; + let old_generation = s.backings[&old].generation; + + retire_recording_in(&mut s, list); + assert!(!s.of_list.contains_key(&list)); + assert!(!s.backings[&old].users.contains(&list)); + assert_eq!(s.recordings.get(&list), Some(&4)); + assert_eq!(s.list_lifetimes.get(&list), Some(&9)); + assert_eq!(s.submit_pins.get(&(list, 9)), Some(&1)); + assert_eq!(s.backings[&old].submit_pins, 1, "an in-flight submit still owns the old backing"); + + move_list(&mut s, list, next); + *s.recordings.get_mut(&list).unwrap() += 1; + assert_eq!(s.of_list.get(&list), Some(&next)); + assert!(s.backings[&next].users.contains(&list)); + assert_eq!(s.backings[&old].generation, old_generation, "reuse cannot replace the old backing generation"); + assert_eq!(s.recordings.get(&list), Some(&5)); + } + + #[test] + fn retired_list_stays_in_flight_and_old_token_cannot_unpin_reused_address() { + let (list, old, next) = (0x7ffe_7681usize, 0x7ffe_7682usize, 0x7ffe_7683usize); + created_on(list, old, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let old_submit = begin_submit(&[list as *mut c_void]).unwrap(); + retire_recording(list); + assert!(in_flight(list), "retirement keeps the exact pending submit alive"); + + forget_list(list); + created_on(list, next, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let reused_submit = begin_submit(&[list as *mut c_void]).unwrap(); + drop(old_submit); + assert!(in_flight(list), "an old lifetime token cannot unpin the reused raw address"); + drop(reused_submit); + assert!(!in_flight(list)); + forget_list(list); + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.backings.remove(&old); + s.backings.remove(&next); + s.types.remove(&old); + s.types.remove(&next); + } + + #[test] + fn idle_reset_commit_is_once_only_and_rejects_concurrent_recording() { + let (alloc, spare, failed, list) = (0x7ffe_7701usize, 0x7ffe_7702usize, 0x7ffe_7703usize, 0x7ffe_7704usize); + let mut s = State::default(); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.aside.insert(alloc, vec![spare]); + backing_mut(&mut s, spare); + + let (mine, probes) = namespace_probes(&s, alloc); + let successful = vec![probes.iter().find(|probe| probe.raw == spare).unwrap().clone()]; + let token = reserve_reset(&mut s, alloc).unwrap(); + assert!(commit_idle_resets(&mut s, alloc, token, &mine, &probes, &successful, &mut Vec::new())); + assert!(s.backings[&spare].already_reset); + assert!(namespace_probes(&s, alloc).1.iter().find(|probe| probe.raw == spare).unwrap().already_reset, + "the next reclaim pass skips an unchanged backing"); + + s.aside.get_mut(&alloc).unwrap().push(failed); + backing_mut(&mut s, failed); + let (mine, probes) = namespace_probes(&s, alloc); + let token = reserve_reset(&mut s, alloc).unwrap(); + assert!(commit_idle_resets(&mut s, alloc, token, &mine, &probes, &[], &mut Vec::new())); + assert!(!s.backings[&failed].already_reset, "a failed driver Reset remains retryable"); + assert!(!s.resetting.contains_key(&alloc), "a failed idle batch releases its token"); + + let (mine, probes) = namespace_probes(&s, alloc); + let token = reserve_reset(&mut s, alloc).unwrap(); + move_list(&mut s, list, spare); + assert!(!commit_idle_resets(&mut s, alloc, token, &mine, &probes, &successful, &mut Vec::new()), + "a recording created during the unlocked Reset invalidates its exact claim"); + assert!(!s.backings[&spare].already_reset); + assert!(!s.resetting.contains_key(&alloc)); + } + #[test] fn reset_commit_rejects_reentrant_backing_mutation() { let (alloc, spare, list) = (0x7ffe_7a10usize, 0x7ffe_7a20usize, 0x7ffe_7a30usize); @@ -1761,18 +1959,20 @@ mod tests { state.as_mut().unwrap().backings.get_mut(&spare).unwrap().submit_pins += 1; 0 }), 0); - let committed = { + let (committed, token_released) = { let mut g = STATE.lock().unwrap(); let s = g.as_mut().unwrap(); let committed = commit_reset(s, alloc, alloc, spare, token, &mine, &probes, true, false, &mut Vec::new()); + let token_released = !s.resetting.contains_key(&alloc); s.of_list.remove(&list); s.backings.remove(&alloc); s.backings.remove(&spare); s.aside.remove(&alloc); s.types.remove(&alloc); - committed + (committed, token_released) }; assert!(!committed, "state changed during the unlocked driver call must fail closed"); + assert!(token_released, "a rejected reset commit must release its operation token"); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index a69b70b74a..379169913f 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4061,6 +4061,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { for seg in reclaimed { super::bind::reset(seg as *mut c_void, 0, 0); clear_segment_state(seg); + super::alloc_pool::retire_recording(seg); } if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(primary as usize))) { s.allocator = alloc; diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 90aca4aa20..55004fa291 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -225,6 +225,11 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: for seg in moved { super::bind::reset(seg as *mut c_void, 0, 0); super::list_x::clear_segment_state(seg); + super::alloc_pool::retire_recording(seg); + } + if stand_in.is_some() { + super::bind::reset(primary, 0, 0); + super::alloc_pool::retire_recording(primary as usize); } } *((this as usize + F_RING_AT) as *mut usize) = 0; @@ -359,6 +364,7 @@ pub(super) fn pop_spare(wrapper: *mut c_void) -> Option<*mut c_void> { /// Give back to `wrapper`'s spare pool a closed PC command list that did not become a segment. pub(super) fn put_spare(wrapper: *mut c_void, pc: *mut c_void) { + super::alloc_pool::retire_recording(pc as usize); let mut sg = SEGMENTS.lock().unwrap(); sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().spares.push(pc as usize); } From 77eb9e7f11ac603088dc7c1a5c79383c00c57ff5 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:20:42 -0800 Subject: [PATCH 135/265] D3D12.X: preserve used pipelines when the writer stops Retain sequenced keys when the journal worker cannot start or exits, and append them only after its file handle is gone at a flush boundary. Mark torn retry fragments invalid so they cannot become false preload ranks while complete retried keys keep their order. The worker-start fallback concept was adapted from #2635 by Decodere, authored there with Google Antigravity (Gemini 4 Neon), and reworked for the integrated ordered journal. Windows-GNU cargo check passed; focused tests could not link because x86_64-w64-mingw32-dlltool is unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/used_journal.rs | 137 ++++++++++++++++++---- 1 file changed, 117 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/used_journal.rs b/crates/xcl/src/hle/d3d12x/used_journal.rs index 1c058df440..11f6083082 100644 --- a/crates/xcl/src/hle/d3d12x/used_journal.rs +++ b/crates/xcl/src/hle/d3d12x/used_journal.rs @@ -27,7 +27,7 @@ impl Sink for FileSink { } self.file = std::fs::OpenOptions::new().create(true).append(true).open(&self.path).ok(); } - let ok = self.file.as_mut().is_some_and(|file| file.write_all(bytes).is_ok()); + let ok = self.file.as_mut().is_some_and(|file| file.write_all(bytes).and_then(|_| file.flush()).is_ok()); if !ok { self.file = None; } @@ -45,6 +45,8 @@ struct State { seen: HashSet<u64>, pending: Vec<(u64, u64)>, in_flight: Option<Batch>, + fallback_path: Option<PathBuf>, + fallback_writing: bool, next_seq: u64, completed_seq: u64, flush_now: bool, @@ -66,7 +68,7 @@ pub(super) struct Journal { impl Journal { pub(super) fn file(path: PathBuf, seen: HashSet<u64>) -> Self { - Self::with_sink(seen, Box::new(FileSink { path, file: None }), COALESCE) + Self::with_sink(seen, Box::new(FileSink { path: path.clone(), file: None }), COALESCE, Some(path)) } pub(super) fn memory(seen: HashSet<u64>) -> Self { @@ -75,6 +77,8 @@ impl Journal { seen, pending: Vec::new(), in_flight: None, + fallback_path: None, + fallback_writing: false, next_seq: 0, completed_seq: 0, flush_now: false, @@ -87,12 +91,14 @@ impl Journal { Self { shared } } - fn with_sink(seen: HashSet<u64>, sink: Box<dyn Sink>, coalesce: Duration) -> Self { + fn with_sink(seen: HashSet<u64>, sink: Box<dyn Sink>, coalesce: Duration, fallback_path: Option<PathBuf>) -> Self { let shared = Arc::new(Shared { state: Mutex::new(State { seen, pending: Vec::new(), in_flight: None, + fallback_path, + fallback_writing: false, next_seq: 0, completed_seq: 0, flush_now: false, @@ -109,6 +115,27 @@ impl Journal { Self { shared } } + #[cfg(test)] + fn stopped_file(path: PathBuf, seen: HashSet<u64>) -> Self { + let shared = Arc::new(Shared { + state: Mutex::new(State { + seen, + pending: Vec::new(), + in_flight: None, + fallback_path: Some(path), + fallback_writing: false, + next_seq: 0, + completed_seq: 0, + flush_now: false, + closed: false, + stopped: true, + }), + wake: Condvar::new(), + completed: Condvar::new(), + }); + Self { shared } + } + pub(super) fn note(&self, key: u64) { if key == 0 { return; @@ -117,8 +144,9 @@ impl Journal { if state.closed || !state.seen.insert(key) { return; } - // An in-memory/test journal, or a worker that could not start, still deduplicates. - if state.stopped { + // An in-memory journal still deduplicates. A file journal retains keys for the bounded + // shutdown fallback when its worker could not start. + if state.stopped && state.fallback_path.is_none() { return; } state.next_seq += 1; @@ -165,7 +193,53 @@ impl Journal { break; } } - state.completed_seq >= target && (!close || state.stopped) + let complete = state.completed_seq >= target && (!close || state.stopped); + drop(state); + complete || self.append_after_worker_stopped() + } + + /// A failed spawn (or a worker panic) has dropped its sink, so this is the only writer. Keep + /// the bind path memory-only and persist its ordered backlog at an explicit flush boundary. + fn append_after_worker_stopped(&self) -> bool { + let (path, end_seq, interrupted_append, keys) = { + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if !state.stopped || state.fallback_writing { + return false; + } + let Some(path) = state.fallback_path.clone() else { return false }; + let mut entries = Vec::new(); + let interrupted_append = state.in_flight.is_some(); + if let Some(batch) = &state.in_flight { + entries.extend(batch.keys.iter().copied().map(|key| (batch.end_seq, key))); + } + entries.extend(state.pending.iter().copied()); + let Some(end_seq) = entries.last().map(|entry| entry.0) else { return true }; + state.fallback_writing = true; + (path, end_seq, interrupted_append, entries.into_iter().map(|(_, key)| key).collect::<Vec<_>>()) + }; + + // A stopped worker may have left a partial hexadecimal line. The marker makes that + // fragment invalid before the complete records are retried without rejecting old files + // that used shorter hexadecimal keys. + let mut bytes = String::new(); + if interrupted_append { + bytes.push_str("!\n"); + } + bytes.reserve(keys.len() * 17); + for key in keys { + let _ = writeln!(bytes, "{key:016x}"); + } + let written = (FileSink { path, file: None }).append(bytes.as_bytes()); + + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + state.fallback_writing = false; + if written && state.stopped { + state.in_flight = state.in_flight.take().filter(|batch| batch.end_seq > end_seq); + state.pending.retain(|(seq, _)| *seq > end_seq); + state.completed_seq = state.completed_seq.max(end_seq); + self.shared.completed.notify_all(); + } + written && state.completed_seq >= end_seq } } @@ -175,18 +249,24 @@ impl Drop for Journal { } } -struct Stopped(Arc<Shared>); +struct Stopped { + shared: Arc<Shared>, + sink: Option<Box<dyn Sink>>, +} impl Drop for Stopped { fn drop(&mut self) { - let mut state = self.0.state.lock().unwrap_or_else(|e| e.into_inner()); + // Publish `stopped` only after the worker's append handle is gone. The fallback can then + // open the path without ever overlapping the worker, including during panic unwinding. + drop(self.sink.take()); + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); state.stopped = true; - self.0.completed.notify_all(); + self.shared.completed.notify_all(); } } -fn writer(shared: Arc<Shared>, mut sink: Box<dyn Sink>, coalesce: Duration) { - let stopped = Stopped(shared.clone()); +fn writer(shared: Arc<Shared>, sink: Box<dyn Sink>, coalesce: Duration) { + let mut stopped = Stopped { shared: shared.clone(), sink: Some(sink) }; let mut bytes = String::new(); let mut retrying = false; loop { @@ -220,15 +300,15 @@ fn writer(shared: Arc<Shared>, mut sink: Box<dyn Sink>, coalesce: Duration) { bytes.clear(); if retrying { - // `write_all` may have appended an arbitrary prefix before reporting failure. End - // that fragment so replay cannot concatenate it with the first key into a lost line. - bytes.push('\n'); + // `write_all` may have appended an arbitrary prefix before reporting failure. Make + // that fragment invalid so replay cannot rank a torn hexadecimal prefix as a key. + bytes.push_str("!\n"); } bytes.reserve(batch.keys.len() * 17); for key in batch.keys.iter() { let _ = writeln!(bytes, "{key:016x}"); } - let written = sink.append(bytes.as_bytes()); + let written = stopped.sink.as_mut().unwrap().append(bytes.as_bytes()); retrying = !written; let mut state = shared.state.lock().unwrap_or_else(|e| e.into_inner()); if written { @@ -242,7 +322,6 @@ fn writer(shared: Arc<Shared>, mut sink: Box<dyn Sink>, coalesce: Duration) { drop(next); } } - drop(sink); drop(stopped); } @@ -279,6 +358,7 @@ mod tests { HashSet::new(), Box::new(Blocking { first: true, entered: entered_tx, release: release_rx, output: output.clone() }), Duration::ZERO, + None, )); journal.note(1); entered_rx.recv_timeout(Duration::from_secs(2)).expect("writer did not take the first batch"); @@ -317,15 +397,16 @@ mod tests { HashSet::new(), Box::new(FailOnce { failed: false, output: output.clone() }), Duration::from_millis(1), + None, ); - journal.note(3); - journal.note(4); + journal.note(0xdead_beef_0000_0003); + journal.note(0xdead_beef_0000_0004); assert!(journal.flush_bounded(Duration::from_secs(2))); - journal.note(5); + journal.note(0xdead_beef_0000_0005); assert!(journal.flush_bounded(Duration::from_secs(2))); let text = String::from_utf8(output.lock().unwrap().clone()).unwrap(); let keys: Vec<u64> = text.lines().filter_map(|line| u64::from_str_radix(line, 16).ok()).filter(|&key| key != 0).collect(); - assert_eq!(keys, [3, 4, 5]); + assert_eq!(keys, [0xdead_beef_0000_0003, 0xdead_beef_0000_0004, 0xdead_beef_0000_0005]); assert!(journal.shutdown_bounded(Duration::from_secs(2))); } @@ -337,6 +418,7 @@ mod tests { HashSet::new(), Box::new(Blocking { first: true, entered: entered_tx, release: release_rx, output: Arc::new(Mutex::new(Vec::new())) }), Duration::ZERO, + None, ); journal.note(6); entered_rx.recv_timeout(Duration::from_secs(2)).expect("writer did not block"); @@ -346,4 +428,19 @@ mod tests { release_tx.send(()).unwrap(); assert!(journal.shutdown_bounded(Duration::from_secs(2))); } + + #[test] + fn worker_start_failure_defers_ordered_unique_writes_until_shutdown() { + let path = std::env::temp_dir().join(format!("xcl-used-no-worker-{}.txt", std::process::id())); + let _ = std::fs::remove_file(&path); + let journal = Journal::stopped_file(path.clone(), [7].into()); + journal.note(8); + journal.note(7); + journal.note(9); + journal.note(8); + assert!(!path.exists(), "the producer performed file I/O"); + assert!(journal.shutdown_bounded(Duration::from_secs(2))); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "0000000000000008\n0000000000000009\n"); + let _ = std::fs::remove_file(path); + } } From 67f42619a4fd1c5b94be82b1dd55b10529868264 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:21:17 -0800 Subject: [PATCH 136/265] D3D12.X: count queued pipeline builds without a frame scan Every present walked every title-visible stand-in and locked its shared build just to update the compiling title. Cold runs can retain tens of thousands of dormant lazy stand-ins, so this both reported work that was never queued and added O(N) render-thread contention with completion.\n\nAdapt the measured accounting idea from #1168 to the integrated coalesced Build model. Track each unique title-visible build through idle, active, and done, publish the counter before a worker can complete, and finish it exactly once on completion or last-owner orphaning. Auxiliary foreground builds remain outside the title-pipeline metric.\n\nThe Windows GNU library/test cross-check passed with the existing warnings. Windows MSVC runtime, GPU, and smoke tests were not available here.\n\nSource concept: #1168 by eizispark, written with Antigravity (Google DeepMind, Gemini 4 Carbon / Claude Opus 5.5).\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 70 ++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index d54bb6c580..92698e74c2 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -8,11 +8,15 @@ //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock, Weak}; use super::build_queue::{BuildQueue, JobHandle, Priority}; +const QUEUE_IDLE: u8 = 0; +const QUEUE_ACTIVE: u8 = 1; +const QUEUE_DONE: u8 = 2; + /// Process-lifetime ranked-preload outcomes; `started` means dequeued in the Preload band. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(default)] @@ -44,6 +48,9 @@ struct Build { job: Mutex<Option<Job>>, /// the build went to the workers (a lazy one goes on its first `resolve`) sent: std::sync::atomic::AtomicBool, + /// Whether a title-visible stand-in owns this build, and its exact queued-count state. + tracked: AtomicBool, + queue_state: AtomicU8, /// the real pipeline state (one owned raw pointer shared by all `Pending`s), 0 until built /// or when building failed real: AtomicUsize, @@ -151,6 +158,8 @@ impl Build { compute_key, job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(sent), + tracked: AtomicBool::new(false), + queue_state: AtomicU8::new(QUEUE_IDLE), real: AtomicUsize::new(0), done: Mutex::new(false), cv: Condvar::new(), @@ -162,6 +171,23 @@ impl Build { } } + fn note_queued(&self) { + if self.tracked.load(Ordering::Acquire) { + // Publish the count before ACTIVE: completion may run as soon as the queue accepts + // the job and must never subtract an entry which has not been added yet. + QUEUED_BUILDS.fetch_add(1, Ordering::Relaxed); + if !mark_queued(&self.queue_state) { + QUEUED_BUILDS.fetch_sub(1, Ordering::Relaxed); + } + } + } + + fn finish_queued(&self) { + if mark_queue_done(&self.queue_state) { + QUEUED_BUILDS.fetch_sub(1, Ordering::Relaxed); + } + } + fn promote(&self, priority: Priority) { if let Some(job) = self.queued.lock().unwrap().as_ref() { let _ = job.promote(priority); @@ -198,6 +224,14 @@ impl Build { } } +fn mark_queued(state: &AtomicU8) -> bool { + state.compare_exchange(QUEUE_IDLE, QUEUE_ACTIVE, Ordering::AcqRel, Ordering::Acquire).is_ok() +} + +fn mark_queue_done(state: &AtomicU8) -> bool { + state.swap(QUEUE_DONE, Ordering::AcqRel) == QUEUE_ACTIVE +} + impl Pending { fn note_use(&self) { if self.key != 0 && !self.used.swap(true, Ordering::Relaxed) { @@ -299,6 +333,7 @@ fn complete(build: &Arc<Build>, real: usize) { build.real.store(real, Ordering::Release); } *done = true; + build.finish_queued(); build.cv.notify_all(); orphan }; @@ -310,6 +345,7 @@ fn complete(build: &Arc<Build>, real: usize) { } static BUILT: AtomicUsize = AtomicUsize::new(0); static FAILED: AtomicUsize = AtomicUsize::new(0); +static QUEUED_BUILDS: AtomicUsize = AtomicUsize::new(0); /// binds waiting right now for a pipeline still being built (`title_held`) static HELD: AtomicUsize = AtomicUsize::new(0); @@ -444,6 +480,7 @@ fn drop_unstarted_job(build: &Arc<Build>) { { let mut done = build.done.lock().unwrap(); *done = true; + build.finish_queued(); build.cv.notify_all(); } drop(job); @@ -606,6 +643,9 @@ fn schedule(build: &Arc<Build>, priority: Priority, preload: bool, preload_rank: priority }; *queued = submit_job(queue(), build, priority, preload, preload_rank); + if queued.is_some() { + build.note_queued(); + } } } @@ -759,6 +799,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, comp late: Default::default(), spared: Default::default(), }); + build.tracked.store(true, Ordering::Release); PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { @@ -885,6 +926,29 @@ fn preload_enabled() -> bool { mod used_tests { use super::*; + #[test] + fn queued_count_state_is_once_only_and_completion_wins_races() { + let state = AtomicU8::new(QUEUE_IDLE); + assert!(mark_queued(&state)); + assert!(!mark_queued(&state)); + assert!(mark_queue_done(&state)); + assert!(!mark_queue_done(&state)); + assert!(!mark_queued(&state)); + + let completed_first = AtomicU8::new(QUEUE_IDLE); + assert!(!mark_queue_done(&completed_first)); + assert!(!mark_queued(&completed_first)); + + let build = Build::new(Box::new(|| 0), false); + build.note_queued(); + assert_eq!(build.queue_state.load(Ordering::Relaxed), QUEUE_IDLE, "auxiliary builds are not reported as title pipelines"); + build.tracked.store(true, Ordering::Release); + build.note_queued(); + assert_eq!(build.queue_state.load(Ordering::Relaxed), QUEUE_ACTIVE); + build.finish_queued(); + assert_eq!(build.queue_state.load(Ordering::Relaxed), QUEUE_DONE); + } + #[test] fn demanded_auxiliary_build_runs_on_a_worker() { let caller = std::thread::current().id(); @@ -1956,6 +2020,7 @@ pub fn released(pso: usize) -> usize { if owners == 0 { // the worker stores its result into a Build nobody will read: mark it orphaned p.build.orphan.store(true, Ordering::Release); + p.build.finish_queued(); orphaned = true; } } @@ -1984,6 +2049,5 @@ pub fn need_by_submit(pso: usize) { /// (built in the background, failed, still building) pub fn counts() -> (usize, usize, usize) { - let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.build.done.lock().unwrap()).count()); - (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), pending) + (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), QUEUED_BUILDS.load(Ordering::Relaxed)) } From 2b878052552f91775cbdc053c4f798161ff26a2c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:24:32 -0800 Subject: [PATCH 137/265] D3D12.X: reuse pending pipeline entries on bind A bind looked up the same stand-in twice in the global pending map. Completed compute pipelines also entered the wait path, taking completion and demand locks and trying to promote work whose real pointer was already published.\n\nAdapt #1708 to the integrated shared Build model: resolve through the first retained Pending entry and return a completed real pipeline after one acquire load. Zero still takes the existing budget, spared, wait, and failed-build paths.\n\nThe Windows GNU library/test cross-check passed with the existing warnings. Windows MSVC runtime, GPU, and smoke tests were not available here.\n\nSource implementation and measurements: #1708 by CallMeBrado, written with OpenAI Codex (GPT-6).\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 27 ++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 92698e74c2..2c2d4d6540 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1418,6 +1418,19 @@ mod used_tests { assert_eq!(released(standin), 0x5757); } + #[test] + fn binding_a_completed_compute_pipeline_neither_relooks_it_up_nor_requests_work() { + let standin = 0x7E57_B00Ausize; + submit(standin, true, Box::new(|| 0x5455)); + let p = entry(standin).unwrap(); + drop(p.build.cv.wait_while(p.build.done.lock().unwrap(), |done| !*done).unwrap()); + + assert_eq!(resolve_for_bind(standin), 0x5455); + assert_eq!(resolve_wait_for(standin, None), 0x5455); + assert!(!p.build.wanted.load(Ordering::Acquire)); + assert_eq!(released(standin), 0x5455); + } + /// A bind waits for a pipeline still being built no longer than its budget and goes on with /// the stand-in; later binds do not wait for it again; once built it is the real one. #[test] @@ -1843,6 +1856,10 @@ pub fn shared(standin: usize, driver: usize) { /// pipeline (`pso` itself when it is one). pub fn resolve(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; + resolve_pending(&p, pso) +} + +fn resolve_pending(p: &Pending, pso: usize) -> usize { p.note_use(); match p.build.real.load(Ordering::Acquire) { 0 => { @@ -1882,6 +1899,9 @@ fn resolve_wait_bound_for(pso: usize, budget: Option<std::time::Duration>) -> (u } fn resolve_wait_pending(p: &Arc<Pending>, pso: usize, budget: Option<std::time::Duration>) -> usize { + if let real @ 1.. = p.build.real.load(Ordering::Acquire) { + return real; + } let bound = if p.spared.load(Ordering::Acquire) { resolve_spared(p, pso) } else { @@ -1998,8 +2018,11 @@ fn resolve_spared(p: &Arc<Pending>, pso: usize) -> usize { /// For binding: compute pipelines are waited for, graphics ones are not. pub fn resolve_for_bind(pso: usize) -> usize { match entry(pso) { - Some(p) if p.compute => resolve_wait(pso), - Some(_) => resolve(pso), + Some(p) if p.compute => { + p.note_use(); + resolve_wait_pending(&p, pso, wait_budget()) + } + Some(p) => resolve_pending(&p, pso), None => pso, } } From d5aa0a6a578a90a1023ad200a4ac76d2638bb4e3 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:25:03 -0800 Subject: [PATCH 138/265] D3D12.X: reserve split continuations without allocators The transactional split already reserves a closed continuation before closing the producer, but a cache miss made a private allocator, opened a list on it, and closed the list only to Reset it later onto the title allocator. CreateCommandList1 directly makes the required closed allocator-free object. Use that path when ID3D12Device4 is available and retain the existing allocator-backed path for older devices and Close-failure injection tests. This preserves the integrated preflight/commit/rollback model and allocator generation tracking. The Windows GNU library/test cross-check passed with existing warnings. Windows MSVC, GPU tests, and title smoke were not available here. Adapted from the CreateCommandList1 reservation concept in #2717 by Kalmarv with Claude Code (Claude Opus 5.5); its core close-before-create fix was already superseded by the integrated transactional split. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 12 ++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 379169913f..963c041e04 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3534,6 +3534,18 @@ unsafe fn reserve_closed_segment( note_reserved_closed(spare as usize, ty); return Some(spare); } + // CreateCommandList1 produces exactly the allocator-free closed object the transaction + // needs. Keep the older path as a compatibility fallback for devices without ID3D12Device4. + #[cfg(test)] + let close_is_hooked = CLOSE_HOOK.lock().unwrap().iter().any(|h| h.0 == wrapper as usize); + #[cfg(not(test))] + let close_is_hooked = false; + if !close_is_hooked { + if let Some(made) = real::create_closed_pc_command_list(dev.as_raw(), ty) { + note_reserved_closed(made as usize, ty); + return Some(made); + } + } let temp: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).ok()?; if !real::is_adopted(temp.as_raw()) { real::adopt(temp.as_raw(), real::Kind::CommandAllocator); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 906855ca43..b44098780a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3312,6 +3312,31 @@ pub(super) unsafe fn create_raw_pc_command_list( }; (hr >= 0 && !out.is_null()).then_some(out) } + +/// Create a raw adopted PC command list already closed and without an allocator. Split +/// preparation can reserve this while the producer still records; it is Reset onto the title's +/// allocator only after that producer has closed. +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 = std::ptr::null_mut(); + let hr = if is_ext(vt(dev) as usize) { + dev_create_command_list1(dev, 0, ty.0 as usize, D3D12_COMMAND_LIST_FLAG_NONE.0 as usize, &iid, &mut out) + } else { + let dev4 = ID3D12Device::from_raw_borrowed(&dev)?.cast::<ID3D12Device4>().ok()?; + match dev4.CreateCommandList1::<ID3D12GraphicsCommandList>(0, ty, D3D12_COMMAND_LIST_FLAG_NONE) { + Ok(list) => { + out = list.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]); From be772deb26aff46479e3185f45504b8814f8eae5 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:25:22 -0800 Subject: [PATCH 139/265] D3D12.X: key compute driver blobs by static samplers Identical DXIL and pipeline flags can use different ordered static samplers in their root signatures. The disk cache previously assigned those pipelines one filename, so a whole, split-chain, or two-pass compute build could reject and replace another root signature's blob before paying for an uncached driver retry. Include the sampler identity in runtime and offline cache names while preserving exact legacy names for empty-sampler roots. Adapted from the collision identified and reproduced by PR #1420, extended to the integrated dispatch-chain and two-pass paths. Checked with the Windows GNU target; Windows MSVC runtime, GPU cache reuse, and smoke tests were not available here. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 1 + crates/xcl/src/hle/d3d12x/real.rs | 70 +++++++++++++++---- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 5 +- crates/xcl/src/shaders.rs | 4 +- 4 files changed, 63 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 78c357ed09..7660f15e99 100644 --- a/README.md +++ b/README.md @@ -268,6 +268,7 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - XCL saves an eligible driver blob when its pipeline takes at least 250 ms to build, even after the bounded in-memory blob cache fills. This is off by default on AMD; `XCL_PSO_DISK_CACHE=1` forces it on, and `XCL_PSO_DISK_CACHE=0` disables it elsewhere. + Compute blobs with different ordered static-sampler root signatures use separate entries. - Direct compute dispatches can split large programs into pipelines built in parallel. `XCL_DIRECT_SPLIT_INSTRUCTIONS` sets the target instructions per piece (default 12500, zero disables splitting). Loops stay in one piece. A strongly connected component over the diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 906855ca43..404e1787a0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4628,7 +4628,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const let record = crate::gpu::shader::fnv64(cs); let warm = compiled.dispatch_chain.as_ref().and_then(|_| { let rs = abi_rs_for(this, &compiled.samplers)?; - let result = compute_container(this, f, d, rs, &dxil, record, riid, ppv, ComputeBuild::CachedWhole); + let result = compute_container(this, f, d, rs, &dxil, &compiled.samplers, record, riid, ppv, ComputeBuild::CachedWhole); (result.0 >= 0).then_some((rs, result)) }); if let Some(plan) = compiled.dispatch_chain.filter(|_| warm.is_none()) { @@ -4648,7 +4648,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const Some(hit) => hit, None => { let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; - (rs, compute_container(this, f, d, rs, &dxil, record, riid, ppv, ComputeBuild::Whole)) + (rs, compute_container(this, f, d, rs, &dxil, &compiled.samplers, record, riid, ppv, ComputeBuild::Whole)) } }; LAST_COMPUTE_RS.with(|c| c.set(rs as usize)); @@ -4663,7 +4663,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const crate::xlog_warn!( "D3D12.X: the driver refused the compute PSO of record {record:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver: its dispatches are skipped", dxil.len(), - driver_cache::name(&dxil, d.Flags.0), + driver_cache::name_for_root(&dxil, d.Flags.0, false, &compiled.samplers), in_driver.as_millis() ); } @@ -4677,7 +4677,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_pso_dispatch_remap(*ppv, compiled.dispatch_remap); - remap_fallback::note(*ppv as usize, this, f, rs as usize, d.Flags, d.NodeMask, record, cs, + remap_fallback::note(*ppv as usize, this, f, rs as usize, &compiled.samplers, d.Flags, d.NodeMask, record, cs, wave32_only(this), crate::gpu::recomp::pso::mem_windows(), compiled.dispatch_remap.is_some()); note_translated_compute(hr, ppv); crate::xlog_info!( @@ -4700,6 +4700,7 @@ pub(super) mod remap_fallback { device: ID3D12Device, create: PsoFn, signature: ID3D12RootSignature, + samplers: Vec<crate::gpu::recomp::pso::StaticSampler>, flags: D3D12_PIPELINE_STATE_FLAGS, node: u32, record: u64, @@ -4716,13 +4717,15 @@ pub(super) mod remap_fallback { } pub(super) unsafe fn note(pso: usize, this: *mut c_void, create: PsoFn, rs: usize, - flags: D3D12_PIPELINE_STATE_FLAGS, node: u32, record: u64, cs: &[u8], split_wave64: bool, windows: u32, remapped: bool) { + samplers: &[crate::gpu::recomp::pso::StaticSampler], flags: D3D12_PIPELINE_STATE_FLAGS, + node: u32, record: u64, cs: &[u8], split_wave64: bool, windows: u32, remapped: bool) { if remapped && pso != 0 { let Some(device) = ID3D12Device::from_raw_borrowed(&this) else { return }; let raw_rs = rs as *mut c_void; let Some(signature) = ID3D12RootSignature::from_raw_borrowed(&raw_rs) else { return }; let old = FALLBACKS.lock().unwrap().insert(pso, Arc::new(Fallback { - device: device.clone(), create, signature: signature.clone(), flags, node, record, cs: cs.to_vec(), split_wave64, windows, + device: device.clone(), create, signature: signature.clone(), samplers: samplers.to_vec(), flags, node, record, + cs: cs.to_vec(), split_wave64, windows, whole: dispatch_chain::WholeBuild::new(), })); drop(old); @@ -4746,7 +4749,8 @@ pub(super) mod remap_fallback { let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: job_fb.node, Flags: job_fb.flags, ..Default::default() }; let mut raw = std::ptr::null_mut(); let (hr, _, _) = compute_container(job_fb.device.as_raw(), job_fb.create, &desc, - job_fb.signature.as_raw(), &dxil, job_fb.record, &pc_iid(Kind::PipelineState), &mut raw, ComputeBuild::Whole); + job_fb.signature.as_raw(), &dxil, &job_fb.samplers, job_fb.record, + &pc_iid(Kind::PipelineState), &mut raw, ComputeBuild::Whole); job_status.store(hr, Ordering::Release); if hr >= 0 { raw as usize } else { 0 } })); @@ -4772,7 +4776,8 @@ enum ComputeBuild { } unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void, - dxil: &[u8], record: u64, riid: *const GUID, ppv: *mut *mut c_void, mode: ComputeBuild) -> (HRESULT, std::time::Duration, bool) { + dxil: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], record: u64, riid: *const GUID, + ppv: *mut *mut c_void, mode: ComputeBuild) -> (HRESULT, std::time::Duration, bool) { let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop<Option<ID3D12RootSignature>>>(rs); copy.CS = bytecode(dxil); @@ -4782,7 +4787,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL let key = compute_blob_key(dxil, rs as usize, copy.Flags.0); let mut cached = compute_blob(key); // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) - let disk = driver_cache::path_for(dxil, copy.Flags.0, mode == ComputeBuild::Chain); + let disk = driver_cache::path_for_root(dxil, copy.Flags.0, mode == ComputeBuild::Chain, samplers); let from_disk = cached.is_none(); let mut loaded = None; if from_disk { @@ -4848,6 +4853,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL /// and the program compiled as before). Off by default on AMD; `XCL_PSO_DISK_CACHE=1` forces /// it on, and `XCL_PSO_DISK_CACHE=0` turns it off everywhere. pub(crate) mod driver_cache { + use crate::gpu::recomp::pso::StaticSampler; use std::io::Read; use std::os::windows::fs::OpenOptionsExt; use std::os::windows::io::AsRawHandle; @@ -4878,15 +4884,31 @@ pub(crate) mod driver_cache { } /// The file of the pipeline made from `dxil` with `flags`. + #[cfg(test)] pub fn name(dxil: &[u8], flags: i32) -> String { name_for(dxil, flags, false) } - /// Like [`name`], using `.chain.pso` for pipelines built with the dispatch chain's root - /// signature (`dispatch_chain`). + /// The legacy empty-sampler name, using `.chain.pso` for the dispatch-chain root signature. + #[cfg(test)] pub fn name_for(dxil: &[u8], flags: i32, chained: bool) -> String { + name_for_root(dxil, flags, chained, &[]) + } + + /// The cache file for a pipeline whose fixed ABI root-signature layout has these ordered + /// static samplers. Empty samplers retain the existing name and cache compatibility. + pub fn name_for_root(dxil: &[u8], flags: i32, chained: bool, samplers: &[StaticSampler]) -> String { let ext = if chained { "chain.pso" } else { "pso" }; - format!("{:016x}-{:x}-{:x}.{ext}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags) + let base = format!("{:016x}-{:x}-{:x}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags); + if samplers.is_empty() { + return format!("{base}.{ext}"); + } + let bytes: Vec<u8> = samplers + .iter() + .flat_map(|(words, compare)| words.iter().copied().chain([u32::from(*compare)])) + .flat_map(u32::to_le_bytes) + .collect(); + format!("{base}-{:016x}-{:x}.{ext}", crate::gpu::shader::fnv64(&bytes), samplers.len()) } /// The file of a translated graphics pipeline keyed by its full state + shader digest. @@ -4911,14 +4933,20 @@ pub(crate) mod driver_cache { enabled_with(env_setting(), REFERENCE_BLOBS.load(Ordering::Relaxed)) } + #[cfg(test)] pub fn path(dxil: &[u8], flags: i32) -> Option<PathBuf> { path_for(dxil, flags, false) } + #[cfg(test)] pub fn path_for(dxil: &[u8], flags: i32, chained: bool) -> Option<PathBuf> { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for(dxil, flags, chained))) } + pub fn path_for_root(dxil: &[u8], flags: i32, chained: bool, samplers: &[StaticSampler]) -> Option<PathBuf> { + enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for_root(dxil, flags, chained, samplers))) + } + pub fn graphics_path(hash: u64, bytes: usize) -> Option<PathBuf> { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(graphics_name(hash, bytes))) } @@ -5242,6 +5270,22 @@ pub(crate) mod driver_cache { assert!(name_for(&[0u8; 0x1234], 2, true).ends_with("-1234-2.chain.pso")); } + #[test] + fn static_sampler_root_signatures_have_distinct_compatible_names() { + let wrap = ([0, 0, 0, 0], false); + let clamp_u = ([2, 0, 0, 0], false); + let comparison = (wrap.0, true); + let file = |chained, samplers: &[StaticSampler]| name_for_root(b"same dxil", 0, chained, samplers); + + assert_eq!(file(false, &[]), name_for(b"same dxil", 0, false), "empty sampler cache compatibility"); + assert_eq!(file(true, &[]), name_for(b"same dxil", 0, true), "empty chain cache compatibility"); + assert_ne!(file(false, &[]), file(false, &[wrap])); + assert_ne!(file(false, &[wrap]), file(false, &[clamp_u])); + assert_ne!(file(false, &[wrap]), file(false, &[comparison])); + assert_ne!(file(false, &[wrap, clamp_u]), file(false, &[clamp_u, wrap])); + assert_ne!(file(false, &[wrap]), file(true, &[wrap])); + } + #[test] fn disk_blobs_default_off_only_for_amd_and_can_be_overridden() { assert!(reference_blob_vendor(0x1002)); @@ -6916,7 +6960,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: // share `tp.cs` (in memory and on disk), matching `translated_compute_pso_once`. let ckey = compute_blob_key(&tp.cs, rs as usize, 0); let mut ccached = compute_blob(ckey); - let cdisk = driver_cache::path(&tp.cs, 0); + let cdisk = driver_cache::path_for_root(&tp.cs, 0, false, &tp.samplers); let cfrom_disk = ccached.is_none(); let mut cloaded = None; if cfrom_disk { diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index a7fba17f21..6c5235c9ec 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -33,6 +33,7 @@ struct PipelineBuilder { device: ID3D12Device, create: PsoFn, signature: ID3D12RootSignature, + samplers: Vec<pso::StaticSampler>, flags: D3D12_PIPELINE_STATE_FLAGS, node: u32, record: u64, @@ -43,7 +44,7 @@ impl PipelineBuilder { let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; let mut raw = std::ptr::null_mut(); let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), - dxil, self.record, iid, &mut raw, ComputeBuild::Chain); + dxil, &self.samplers, self.record, iid, &mut raw, ComputeBuild::Chain); if hr >= 0 && !raw.is_null() { Ok(ID3D12PipelineState::from_raw(raw)) } else { Err(hr) } } } @@ -112,7 +113,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let dev = ID3D12Device::from_raw_borrowed(&this)?; let signature = pso::dispatch_chain_root_signature(dev, samplers).ok()?; let rs = signature.as_raw() as usize; - let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, samplers: samplers.to_vec(), flags: desc.Flags, node: desc.NodeMask, record }); let jobs = (0..plan.pieces.len()).map(|i| { let plan = plan.clone(); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index ef5fca9440..5cd63f8780 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1512,9 +1512,9 @@ impl Pipelines { let path = path_override.or_else(|| { #[cfg(test)] if let Some(dir) = self.cache_dir.as_deref() { - return Some(dir.join(driver_cache::name_for(dxil, desc.Flags.0, chained))); + return Some(dir.join(driver_cache::name_for_root(dxil, desc.Flags.0, chained, samplers))); } - driver_cache::path_for(dxil, desc.Flags.0, chained) + driver_cache::path_for_root(dxil, desc.Flags.0, chained, samplers) }); let mut loaded = path.as_deref().and_then(driver_cache::load); let cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); From 7619ff8cd0c1e5212ccb47eab9f0975839cab854 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:26:25 -0800 Subject: [PATCH 140/265] D3D12.X: create sparse placed buffers outside global state CreateReservedResource ran while holding the global sparse state, so driver callbacks and unrelated sparse work could block behind resource creation. A deferred final Release could also be applied after a reused COM address was recorded, removing the live buffer's pins. Adapt the measured direction from PR #2539 with stronger current-tree lifetime rules: serialize placements and state replacement, snapshot a strong fence generation, create unlocked, drain deferred releases, and publish only after exact generation and window revalidation. Abort releases the returned COM owner outside state. The Windows GNU target check passed. Windows MSVC runtime, GPU tests, and smoke runs were not available here; #2539 supplied the earlier Windows/NVIDIA full-suite and paired-smoke evidence for the underlying change. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 171 +++++++++++++++++++++++++--- 1 file changed, 155 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 33f6c1734c..70d9dee22b 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -413,6 +413,10 @@ unsafe impl Send for State {} static STATE: Mutex<Option<State>> = Mutex::new(None); +/// A placement may release `STATE` while the driver creates its reserved resource. Keep sparse +/// state replacement and another placement from crossing that exact-state transaction. +static PLACEMENT: Mutex<()> = Mutex::new(()); + /// Serializes sparse preparation through wait enqueue for one title queue. Without this, a /// concurrent submission could observe a reserved `waited` value and execute before the thread /// which reserved it has called the native queue `Wait`. @@ -652,6 +656,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { // a state this replaces (the windows set up again) goes after the lock: the release of // its last buffers reaches `forget_buffer`, which takes the lock (#344) // (the queue first: `queue()` never answers with one older than the state's) + let _placement = PLACEMENT.lock().unwrap(); let old_queue = QUEUE.lock().unwrap().replace(s.queue.clone()); let old = STATE.lock().unwrap().replace(s); drop(old); @@ -1781,16 +1786,49 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: /// description): a reserved resource over the window's tiles there, starting at the 64 KiB /// below `va` (returned: its distance from there). pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<(crate::util::HRESULT, usize)> { - let mut g = lock_state(); - let s = g.as_mut()?; + let _placement = PLACEMENT.lock().unwrap(); + place_buffer_in( + &STATE, + &FORGOTTEN, + va, + desc, + state, + |d| { + let hr = super::real::dev_create_reserved_resource(this, d as *const _ as usize, state as usize, 0, riid, ppv); + (hr >= 0 && !ppv.is_null() && !(*ppv).is_null()).then_some((hr, *ppv)) + }, + |raw| { + if !ppv.is_null() && *ppv == raw { + *ppv = std::ptr::null_mut(); + } + drop(ID3D12Resource::from_raw(raw)); + }, + ) +} + +unsafe fn place_buffer_in( + state_lock: &Mutex<Option<State>>, + forgotten: &Mutex<Vec<usize>>, + va: usize, + desc: &D3D12_RESOURCE_DESC, + state: u32, + create: impl FnOnce(&D3D12_RESOURCE_DESC) -> Option<(crate::util::HRESULT, *mut c_void)>, + on_abort: impl FnOnce(*mut c_void), +) -> Option<(crate::util::HRESULT, usize)> { let start = va & !(TILE - 1); let delta = va - start; let bytes = desc.Width as usize; if bytes == 0 { return None; } - s.window_index(start)?; - s.window_index(va.checked_add(bytes)?.checked_sub(1)?)?; + let end = va.checked_add(bytes)?.checked_sub(1)?; + let generation = { + let g = lock_state_in(state_lock, forgotten); + let s = g.as_ref()?; + s.window_index(start)?; + s.window_index(end)?; + s.fence.clone() + }; let mut d = *desc; d.Width = (delta + bytes) as u64; d.Alignment = 0; @@ -1800,22 +1838,36 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D if state & (D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32) != 0 { d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; } - let hr = super::real::dev_create_reserved_resource(this, &d as *const _ as usize, state as usize, 0, riid, ppv); - if hr < 0 || ppv.is_null() || (*ppv).is_null() { + // Driver creation may call back into a release path which needs `STATE`. Revalidate the + // strongly owned fence generation before publishing the resulting resource. + let (hr, raw) = create(&d)?; + let mut g = lock_state_in(state_lock, forgotten); + let valid = g.as_ref().is_some_and(|s| { + s.fence.as_raw() == generation.as_raw() && s.window_index(start).is_some() && s.window_index(end).is_some() + }); + let Some(res) = valid.then(|| ID3D12Resource::from_raw_borrowed(&raw).cloned()).flatten() else { + drop(g); + drop(generation); + on_abort(raw); return None; - } + }; + let s = g.as_mut().unwrap(); // its tiles: the window's video memory at the same addresses; probe actual OS commitment // so uncommitted pages (e.g. [start, va) or reserved tails) stay marked as holes s.ensure_mapped(start, delta + bytes, |t| query_tile_holes(t)); let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|e| (t, e.pool))).collect(); - let raw = *ppv; - let res = ID3D12Resource::from_raw_borrowed(&raw)?.clone(); s.map_tiles(&res, start, &tiles); + if s.buffers.contains_key(&(raw as usize)) { + forget_in(s, raw as usize); + } for &(_, tile) in &tiles { *s.pinned.entry(tile).or_default() += 1; } s.buffers.insert(raw as usize, tiles.iter().map(|x| x.1).collect()); s.signal(); + drop(g); + drop(res); + drop(generation); Some((hr, delta)) } @@ -1825,13 +1877,17 @@ static FORGOTTEN: Mutex<Vec<usize>> = Mutex::new(Vec::new()); /// `STATE`, with the buffers released while it was held let go first. fn lock_state() -> std::sync::MutexGuard<'static, Option<State>> { - let mut g = STATE.lock().unwrap(); - forget_released(&mut g); + lock_state_in(&STATE, &FORGOTTEN) +} + +fn lock_state_in<'a>(state: &'a Mutex<Option<State>>, forgotten: &Mutex<Vec<usize>>) -> std::sync::MutexGuard<'a, Option<State>> { + let mut g = state.lock().unwrap(); + forget_released_in(&mut g, forgotten); g } -fn forget_released(g: &mut Option<State>) { - let gone = std::mem::take(&mut *FORGOTTEN.lock().unwrap()); +fn forget_released_in(g: &mut Option<State>, forgotten: &Mutex<Vec<usize>>) { + let gone = std::mem::take(&mut *forgotten.lock().unwrap()); let Some(s) = g.as_mut() else { return }; for res in gone { forget_in(s, res); @@ -1844,9 +1900,13 @@ fn forget_released(g: &mut Option<State>) { /// here deadlocked the two threads. So it does not wait: with `STATE` held, the holder's next /// `lock_state` lets the buffer go. pub fn forget_buffer(res: usize) { - FORGOTTEN.lock().unwrap().push(res); - match STATE.try_lock() { - Ok(mut g) => forget_released(&mut g), + forget_buffer_in(&STATE, &FORGOTTEN, res); +} + +fn forget_buffer_in(state: &Mutex<Option<State>>, forgotten: &Mutex<Vec<usize>>, res: usize) { + forgotten.lock().unwrap().push(res); + match state.try_lock() { + Ok(mut g) => forget_released_in(&mut g, forgotten), Err(std::sync::TryLockError::WouldBlock) => {} Err(e) => panic!("sparse state: {e}"), } @@ -2545,6 +2605,85 @@ mod tests { (base, s) } + #[test] + fn placement_create_is_unlocked_drains_releases_and_rejects_a_new_generation() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; + + unsafe { + let (base, mut s) = test_state_with_reserved(2); + assert_eq!(VirtualAlloc(base as *mut c_void, 2 * TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); + s.commit_range(base, 2 * TILE); + s.wait_for(s.value); + let old_tile = s.mapped[&base].pool; + let new_tile = s.mapped[&(base + TILE)].pool; + + let mut placed: Option<ID3D12Resource> = None; + s.dev.CreateReservedResource(&buffer_desc(TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut placed) + .expect("placed resource"); + let placed = placed.unwrap(); + let ptr = placed.as_raw() as usize; + s.buffers.insert(ptr, vec![old_tile]); + s.pinned.insert(old_tile, 1); + + let state = Mutex::new(Some(s)); + let forgotten = Mutex::new(Vec::new()); + let desc = buffer_desc(TILE as u64); + let returned = placed.clone().into_raw(); + let mut unlocked = false; + let result = place_buffer_in( + &state, + &forgotten, + base + TILE, + &desc, + 0, + |_| { + unlocked = state.try_lock().is_ok(); + forget_buffer_in(&state, &forgotten, ptr); + forgotten.lock().unwrap().push(ptr); + Some((0, returned)) + }, + |_| panic!("same-generation placement aborted"), + ); + assert_eq!(result, Some((0, 0))); + assert!(unlocked, "resource creation held sparse STATE"); + { + let g = lock_state_in(&state, &forgotten); + let s = g.as_ref().unwrap(); + assert_eq!(s.buffers.get(&ptr), Some(&vec![new_tile])); + assert!(!s.pinned.contains_key(&old_tile)); + assert_eq!(s.pinned.get(&new_tile), Some(&1)); + } + + let original_fence = state.lock().unwrap().as_ref().unwrap().fence.clone(); + let replacement = state.lock().unwrap().as_ref().unwrap().dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let returned2 = placed.clone().into_raw(); + let mut aborted = false; + let result = place_buffer_in( + &state, + &forgotten, + base + TILE, + &desc, + 0, + |_| { + state.lock().unwrap().as_mut().unwrap().fence = replacement; + Some((0, returned2)) + }, + |raw| { + aborted = true; + drop(ID3D12Resource::from_raw(raw)); + }, + ); + assert!(result.is_none() && aborted, "a replacement state accepted the old generation's resource"); + state.lock().unwrap().as_mut().unwrap().fence = original_fence; + + drop(ID3D12Resource::from_raw(returned)); + let s = state.lock().unwrap().take().unwrap(); + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + /// `flush_parked` must keep unmapped pool tiles out of `free` (and `take_tile` must not reuse /// them) while the sparse queue's unmap fence is still in flight on the GPU. #[test] From 7346c6ff7e10f7003bff45a5393f46d3c5282fdd Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:27:33 -0800 Subject: [PATCH 141/265] D3D12.X: cache invariant slots in hot hooks Hot resource, command-list, allocator, fence, and queue hooks locked the global adopted-class table and scanned method names on every call. A translated draw paid this for both its draw and pipeline bind, and all recording threads contended on the same lock.\n\nAdapt #903 by caching the first slot at each interface-family call site. COM interface versions append methods, and a table-driven test verifies every cached method has one nonzero slot throughout its family. Cold or interface-dependent lookups remain dynamic.\n\nThe Windows GNU library/test cross-check passed with the existing warnings. Windows MSVC runtime, GPU, and smoke tests were not available here.\n\nSource implementation and native tests: #903 by mastrr9, authored with Claude Code (Claude Opus 5.5) and audited with Antigravity.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 88 +++++++++++++++++++++++++------ 1 file changed, 73 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 906855ca43..5ce067cdd7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -60,6 +60,44 @@ pub enum Kind { StateObject, } +#[cfg(test)] +mod slot_cache_tests { + use super::*; + + #[test] + fn cached_hot_methods_keep_one_nonzero_slot_across_interface_versions() { + let families: [(&str, &[&str]); 5] = [ + ( + "ID3D12GraphicsCommandList", + &[ + "Close", + "Reset", + "ClearState", + "DrawInstanced", + "DrawIndexedInstanced", + "SetPipelineState", + "OMSetRenderTargets", + "ClearRenderTargetView", + "ExecuteIndirect", + ], + ), + ("ID3D12Resource", &["Map", "Unmap", "WriteToSubresource"]), + ("ID3D12CommandQueue", &["ExecuteCommandLists"]), + ("ID3D12CommandAllocator", &["Reset"]), + ("ID3D12Fence", &["Signal"]), + ]; + for (base, methods) in families { + let versions = layout::chain(base); + assert!(!versions.is_empty(), "{base}"); + for method in methods { + let slots: BTreeSet<_> = versions.iter().filter_map(|iface| layout::slot(iface, method)).collect(); + assert_eq!(slots.len(), 1, "{base}::{method} at {slots:?}"); + assert_ne!(slots.first(), Some(&0), "slot zero is the cache's empty value"); + } + } + } +} + impl Kind { pub fn base(self) -> &'static str { match self { @@ -638,6 +676,26 @@ pub unsafe fn orig_fn(this: *mut c_void, slot: usize) -> usize { *orig.add(slot) } +/// `slot_of(this, method)`, looked up once for this call site. COM interface versions append +/// methods, so one method keeps its slot throughout the interface family served by a hook. +macro_rules! slot { + ($this:expr, $method:literal) => {{ + static SLOT: AtomicUsize = AtomicUsize::new(0); + cached_slot(&SLOT, $this, $method) + }}; +} + +unsafe fn cached_slot(cache: &AtomicUsize, this: *mut c_void, method: &str) -> usize { + match cache.load(Ordering::Relaxed) { + 0 => { + let slot = slot_of(this, method); + cache.store(slot, Ordering::Relaxed); + slot + } + slot => slot, + } +} + unsafe fn native_queue_fn(queue: *mut c_void, slot: usize) -> usize { let table = vt(queue); if is_ext(table as usize) { orig_fn(queue, slot) } else { *table.add(slot) } @@ -1643,7 +1701,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v // the PC's Map only on a resource it can map: on a reserved one or one without CPU pages it is // an invalid call (debug layer 824 / 822) that the runtime answers with E_INVALIDARG let hr = if pc_can_map(this) { - let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void, *mut *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Map"))); + let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void, *mut *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot!(this, "Map"))); f(this, sub, range, data) } else { E_INVALIDARG @@ -1674,7 +1732,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v /// Every console resource is CPU-visible memory, a PC texture only in a CPU-visible heap. unsafe extern "system" fn res_write_to_subresource(this: *mut c_void, sub: u32, dst_box: *const D3D12_BOX, data: *const c_void, row_pitch: u32, depth_pitch: u32) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_BOX, *const c_void, u32, u32) -> HRESULT; - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "WriteToSubresource"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "WriteToSubresource"))); let hr = f(this, sub, dst_box, data, row_pitch, depth_pitch); static CALLS: AtomicU64 = AtomicU64::new(0); static FAILED: AtomicU64 = AtomicU64::new(0); @@ -1711,7 +1769,7 @@ unsafe extern "system" fn res_unmap(this: *mut c_void, sub: u32, range: *const c if UNMAPPABLE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { return; } - let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void) = std::mem::transmute(orig_fn(this, slot_of(this, "Unmap"))); + let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void) = std::mem::transmute(orig_fn(this, slot!(this, "Unmap"))); f(this, sub, range) } @@ -3086,7 +3144,7 @@ macro_rules! as_usize { 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 f: RefFn = std::mem::transmute(orig_fn(this, slot!(this, "Close"))); let hr = f(this) as HRESULT; preserve_vtable(this, ext); if hr < 0 { @@ -3100,7 +3158,7 @@ unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, initial_state: *mut c_void) -> HRESULT { let ext = *(this as *const usize); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT = - std::mem::transmute(orig_fn(this, slot_of(this, "Reset"))); + std::mem::transmute(orig_fn(this, slot!(this, "Reset"))); 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); @@ -8085,7 +8143,7 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de /// ClearRenderTargetView: as on the PC (`XCL_TRACE_FRAME`: the colours logged) unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *const [f32; 4], n: u32, rects: *const c_void) { type F = unsafe extern "system" fn(*mut c_void, usize, *const [f32; 4], u32, *const c_void); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ClearRenderTargetView"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ClearRenderTargetView"))); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 16 { @@ -8100,7 +8158,7 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) { type F = unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "OMSetRenderTargets"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "OMSetRenderTargets"))); f(this, n, rtvs, single, dsv); super::list_x::note_render_targets(this, n, rtvs, single, dsv); if super::present::trace_frame() { @@ -8131,7 +8189,7 @@ pub(super) unsafe fn bind_pipeline(this: *mut c_void, pso: *mut c_void) { unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetPipelineState"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "SetPipelineState"))); let bound = super::pso_async::resolve(pso as usize); f(this, bound as *mut c_void); super::dred::mark_pipeline(this, pso as usize, bound); @@ -8148,7 +8206,7 @@ unsafe extern "system" fn cl_set_marker(this: *mut c_void, metadata: u32, data: unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ClearState"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ClearState"))); let bound = super::pso_async::resolve_for_bind(pso as usize); f(this, bound as *mut c_void); if !pso.is_null() { @@ -8161,14 +8219,14 @@ unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { unsafe extern "system" fn cl_draw_instanced(this: *mut c_void, vcount: u32, icount: u32, sv: u32, si: u32) { super::list_x::prepare_draw(this); type F = unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "DrawInstanced"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "DrawInstanced"))); f(this, vcount, icount, sv, si); } unsafe extern "system" fn cl_draw_indexed_instanced(this: *mut c_void, icount: u32, inst: u32, si: u32, bv: i32, sinst: u32) { super::list_x::prepare_draw(this); type F = unsafe extern "system" fn(*mut c_void, u32, u32, u32, i32, u32); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "DrawIndexedInstanced"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "DrawIndexedInstanced"))); f(this, icount, inst, si, bv, sinst); } @@ -8184,7 +8242,7 @@ unsafe extern "system" fn cl_execute_indirect( ) { super::list_x::prepare_draw(this); type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut c_void, u64, *mut c_void, u64); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteIndirect"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ExecuteIndirect"))); f(this, sig, max_count, arg_buf, arg_off, cnt_buf, cnt_off); } @@ -8259,7 +8317,7 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { /// Reset the (adopted) PC allocator `raw` itself. pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void) -> HRESULT; - let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "Reset"))); + let f: F = std::mem::transmute(orig_fn(raw, slot!(raw, "Reset"))); let hr = f(raw); if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } hr @@ -8504,7 +8562,7 @@ unsafe extern "system" fn fence_completed(this: *mut c_void) -> u64 { } unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT { - let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Signal"))); + let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot!(this, "Signal"))); let hr = f(this, value); super::fence_x::note_cpu_signal(this as usize); hr @@ -8512,7 +8570,7 @@ unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lists: *const *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteCommandLists"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ExecuteCommandLists"))); // Internal XCL submits (`sparse` uploads/readbacks, `title_textures` uploads, tile zeroing) // run inside `own_work()` — sometimes while holding internal locks (`sparse::STATE`, // `vram::PAGES`). Forwarding them through the native slot, in the queue's ordered turn, skips From 29aa585feb7a2ee05cdae30fd749a5eca0abb34a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:29:46 -0800 Subject: [PATCH 142/265] D3D12.X: shard pending pipeline lookups by stand-in After the single-lookup bind improvement, every recording thread still took one process-wide PENDING map lock. The #1708 bind benchmark measured about 102 ns per completed bind with four callers, versus about 21 ns with one, leaving unrelated command-list recorders serialized. Route exact stand-in addresses across 64 fixed shards. Insert, lookup, and release remain single-shard operations; the retained Pending owns the shared Build independently, and constant-time queued accounting needs no registry-wide snapshot. Tests cover parallel lifetimes, raw-address replacement, shard distribution, and lock independence. The Windows GNU library/test cross-check passed with the existing warnings. Windows MSVC runtime, GPU, benchmark, and smoke tests were not available here. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 90 ++++++++++++++++++++++++-- 1 file changed, 84 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 2c2d4d6540..8b3f9943c8 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -240,8 +240,42 @@ impl Pending { } } -/// stand-in handed to the title → its real pipeline -static PENDING: Mutex<Option<HashMap<usize, Arc<Pending>>>> = Mutex::new(None); +const PENDING_SHARDS: usize = 64; + +/// Title-visible stand-in address → its build. Bind resolution is called by every recording +/// thread, so unrelated pipelines must not queue on one process-wide map lock. +struct PendingRegistry<V> { + shards: [Mutex<Option<HashMap<usize, V>>>; PENDING_SHARDS], +} + +impl<V> PendingRegistry<V> { + const fn new() -> Self { + Self { shards: [const { Mutex::new(None) }; PENDING_SHARDS] } + } + + fn insert(&self, key: usize, value: V) -> Option<V> { + self.shards[pending_shard_index(key)].lock().unwrap().get_or_insert_with(HashMap::new).insert(key, value) + } + + fn remove(&self, key: usize) -> Option<V> { + self.shards[pending_shard_index(key)].lock().unwrap().as_mut().and_then(|map| map.remove(&key)) + } +} + +impl<V: Clone> PendingRegistry<V> { + fn get(&self, key: usize) -> Option<V> { + self.shards[pending_shard_index(key)].lock().unwrap().as_ref()?.get(&key).cloned() + } +} + +#[inline] +fn pending_shard_index(key: usize) -> usize { + let mut mixed = (key >> 4).wrapping_mul(0x9E37_79B1); + mixed ^= mixed >> 16; + mixed & (PENDING_SHARDS - 1) +} + +static PENDING: PendingRegistry<Arc<Pending>> = PendingRegistry::new(); /// Equal compute requests share only while their build is in flight. Weak values neither retain /// completed builds nor turn this into another PSO cache. @@ -337,7 +371,7 @@ fn complete(build: &Arc<Build>, real: usize) { build.cv.notify_all(); orphan }; - // outside `done`: the Release override takes PENDING (`counts` takes PENDING, then `done`) + // outside `done`: the Release override can re-enter pipeline bookkeeping if orphan { release(real); } @@ -800,7 +834,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, comp spared: Default::default(), }); build.tracked.store(true, Ordering::Release); - PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); + PENDING.insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); @@ -926,6 +960,50 @@ fn preload_enabled() -> bool { mod used_tests { use super::*; + #[test] + fn pending_registry_routes_exact_lifetimes_across_independent_shards() { + let registry = Arc::new(PendingRegistry::new()); + let keys: Vec<_> = (0..256).map(|i| 0x7E00_0000usize + i * 0x10).collect(); + let used: std::collections::HashSet<_> = keys.iter().map(|&key| pending_shard_index(key)).collect(); + assert!(used.len() >= PENDING_SHARDS / 2, "sequential aligned handles reached only {} shards", used.len()); + + std::thread::scope(|scope| { + for chunk in keys.chunks(32) { + let registry = registry.clone(); + scope.spawn(move || { + for &key in chunk { + assert_eq!(registry.insert(key, key ^ 0x55AA), None); + assert_eq!(registry.get(key), Some(key ^ 0x55AA)); + assert_eq!(registry.remove(key), Some(key ^ 0x55AA)); + assert_eq!(registry.get(key), None); + } + }); + } + }); + + let reused = 0x7E57_F000usize; + assert_eq!(registry.insert(reused, 1), None); + assert_eq!(registry.insert(reused, 2), Some(1), "replacement did not return the exact old address entry"); + assert_eq!(registry.remove(reused), Some(2)); + assert_eq!(registry.remove(reused), None); + } + + #[test] + fn a_busy_pending_shard_does_not_hold_an_unrelated_lookup() { + let registry = Arc::new(PendingRegistry::new()); + let first = 0x7E10_0000usize; + let second = (first + 0x10..).step_by(0x10).find(|&key| pending_shard_index(key) != pending_shard_index(first)).unwrap(); + registry.insert(second, 7usize); + + let held = registry.shards[pending_shard_index(first)].lock().unwrap(); + let (tx, rx) = mpsc::channel(); + let other = registry.clone(); + let thread = std::thread::spawn(move || tx.send(other.get(second)).unwrap()); + assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(2)), Ok(Some(7))); + drop(held); + thread.join().unwrap(); + } + #[test] fn queued_count_state_is_once_only_and_completion_wins_races() { let state = AtomicU8::new(QUEUE_IDLE); @@ -1824,7 +1902,7 @@ mod used_tests { } fn entry(pso: usize) -> Option<Arc<Pending>> { - PENDING.lock().unwrap().as_ref()?.get(&pso).cloned() + PENDING.get(pso) } impl Pending { @@ -2032,7 +2110,7 @@ pub fn resolve_for_bind(pso: usize) -> usize { /// (0: another `Pending` owns the build, none, or still being built – the worker's result is /// then released when its last owner is gone). pub fn released(pso: usize) -> usize { - let Some(p) = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)) else { return 0 }; + let Some(p) = PENDING.remove(pso) else { return 0 }; let mut orphaned = false; { let done = p.build.done.lock().unwrap(); From faea307a3144d21b26d116892f245d151f196a44 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:32:49 -0800 Subject: [PATCH 143/265] D3D12.X: stop stalled sparse ring reclaim cleanly The sparse upload ring retried a five-second fence wait forever while holding global sparse state. A stalled upload queue therefore blocked activity reporting and every later title submission permanently.\n\nAdapt #1277's bounded exit, but preserve correctness beyond the source patch: mark exactly the unsubmitted 64-byte chunk suffix for retry instead of leaving its sent hashes stale or invalidating already-submitted chunks in the same page. A synchronous readback aborts when its prerequisite upload did not complete, so it cannot overwrite CPU memory with stale GPU data.\n\nThe Windows GNU library/test cross-check passed with the existing warnings. Windows MSVC runtime, GPU execution, and smoke tests were not available here.\n\nSource diagnosis and timeout test: #1277 by ExoCalibra, assisted by Antigravity (Gemini 4 Neon).\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 141 +++++++++++++++++++++++++--- 1 file changed, 128 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 70d9dee22b..d8949ccd2a 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -908,17 +908,23 @@ impl State { } #[inline] - unsafe fn wait_for(&self, target: u64) { + unsafe fn wait_for(&self, target: u64) -> bool { + self.wait_for_ms(target, 5000) + } + + unsafe fn wait_for_ms(&self, target: u64, timeout_ms: u32) -> bool { if target == 0 || self.fence.GetCompletedValue() >= target { - return; + return true; } let _ = self.fence.SetEventOnCompletion(target, self.event); let wait_stall = crate::stall::span(crate::stall::StallKind::GpuWait); - windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); + windows::Win32::System::Threading::WaitForSingleObject(self.event, timeout_ms); drop(wait_stall); if self.fence.GetCompletedValue() < target { - crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {})", self.fence.GetCompletedValue()); + crate::xlog_warn!("sparse: the queue has not reached fence value {target} after {timeout_ms} ms (at {})", self.fence.GetCompletedValue()); + return false; } + true } #[inline] @@ -1067,6 +1073,32 @@ impl State { } } + /// Make only the chunks overlapping `[a, a + n)` differ from their recorded hashes, so a + /// partial upload failure does not also resend earlier chunks in the same CPU page. + unsafe fn retry_sent_range(&mut self, a: usize, n: usize) { + let end = a + n; + let mut at = a; + while at < end { + let page = at & !(PAGE - 1); + let tile = page & !(TILE - 1); + let page_end = (page + PAGE).min(end); + if let Some(entry) = self.mapped.get_mut(&tile) { + let index = (page - tile) / PAGE; + let Some(sent) = entry.sent[index].as_mut() else { + at = page_end; + continue; + }; + let first = (at - page) / CHUNK; + let last = (page_end - page).div_ceil(CHUNK); + let bytes = std::slice::from_raw_parts(page as *const u8, PAGE); + for chunk in first..last { + sent[chunk] = chunk_hash(&bytes[chunk * CHUNK..(chunk + 1) * CHUNK]) ^ 1; + } + } + at = page_end; + } + } + /// Update `sent` hashes for all 64-byte chunks overlapping `[va, va + len)` so the CPU /// copy-back we just wrote to `va` is not re-uploaded by the next `before_execute`. unsafe fn sync_sent_range(&mut self, va: usize, len: usize) { @@ -1214,14 +1246,25 @@ impl State { /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via /// the 64 MiB ring staging buffer (zero CPU stall on the common path). - unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) { + unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) -> bool { + self.upload_dirty_with_timeout(runs, 5000) + } + + fn retry_dirty_from(&mut self, runs: &[(usize, usize)], index: usize, done: usize) { + visit_unsubmitted_dirty(runs, index, done, |a, n| unsafe { self.retry_sent_range(a, n) }); + } + + unsafe fn upload_dirty_with_timeout(&mut self, runs: &[(usize, usize)], wait_ms: u32) -> bool { if runs.is_empty() { - return; + return true; } - let Some(p) = self.staging_ptr() else { return }; + let Some(p) = self.staging_ptr() else { + self.retry_dirty_from(runs, 0, 0); + return false; + }; let mut open_slot: Option<usize> = None; let mut last_wi: Option<usize> = None; - for &(a, n) in runs { + for (run_index, &(a, n)) in runs.iter().enumerate() { let mut done = 0usize; while done < n { let cur = a + done; @@ -1232,7 +1275,10 @@ impl State { last_wi = Some(i); i } - None => break, + None => { + self.retry_dirty_from(runs, run_index, done); + return false; + } }, }; let b = self.windows[wi].0; @@ -1246,9 +1292,22 @@ impl State { self.reclaim_ring(); } while (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { - let Some(&(fv, _)) = self.inflight.front() else { break }; - self.wait_for(fv); + let Some(&(fv, _)) = self.inflight.front() else { + self.retry_dirty_from(runs, run_index, done); + crate::xlog_warn!("sparse: the staging ring is full without a retirement fence; the unsubmitted CPU writes will be retried"); + return false; + }; + let reached = self.wait_for_ms(fv, wait_ms); self.reclaim_ring(); + if !reached { + self.retry_dirty_from(runs, run_index, done); + static RING_STALLS: AtomicU64 = AtomicU64::new(0); + let stalls = RING_STALLS.fetch_add(1, Ordering::Relaxed) + 1; + if stalls <= 4 || stalls.is_power_of_two() { + crate::xlog_warn!("sparse: staging ring reclaim timed out at fence {fv}; the unsubmitted CPU writes will be retried ({stalls} stalls)"); + } + return false; + } } } } @@ -1271,6 +1330,7 @@ impl State { if let Some(slot_idx) = open_slot { self.submit_slot(slot_idx); } + true } } @@ -1395,7 +1455,9 @@ pub unsafe fn readback_now(va: usize, len: usize) { pg = tile_end; } if !dirty_runs.is_empty() { - s.upload_dirty(&dirty_runs); + if !s.upload_dirty(&dirty_runs) { + return; + } } s.readback_ranges(&[(va, len)]); } @@ -1659,6 +1721,16 @@ fn observed_completion<F>(observed: &[(F, u64)], fence: &F, same: impl Fn(&F, &F observed.iter().find_map(|(known, value)| same(known, fence).then_some(*value)).unwrap_or(0) } +fn visit_unsubmitted_dirty(runs: &[(usize, usize)], index: usize, done: usize, mut visit: impl FnMut(usize, usize)) { + let (a, n) = runs[index]; + if done < n { + visit(a + done, n - done); + } + for &(a, n) in &runs[index + 1..] { + visit(a, n); + } +} + fn reserve_queue_wait(waited: &mut FxHashMap<usize, u64>, queue: usize, value: u64) -> bool { if value == 0 || waited.get(&queue).copied().unwrap_or(0) >= value { return false; @@ -1745,7 +1817,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: s.upload_zeros(&zero_runs); } if !dirty_runs.is_empty() { - s.upload_dirty(&dirty_runs); + let _ = s.upload_dirty(&dirty_runs); } PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Ordering::Relaxed); { @@ -2011,6 +2083,18 @@ mod tests { assert_eq!(waited, FxHashMap::from_iter([(1, 5), (2, 3)])); } + #[test] + fn a_stalled_ring_retries_only_the_unsubmitted_dirty_suffix() { + let runs = [(0x1000, 0x180), (0x3000, 0x80), (0x5000, 0x40)]; + let mut retry = Vec::new(); + visit_unsubmitted_dirty(&runs, 0, 0x100, |a, n| retry.push((a, n))); + assert_eq!(retry, [(0x1100, 0x80), (0x3000, 0x80), (0x5000, 0x40)]); + + retry.clear(); + visit_unsubmitted_dirty(&runs, 1, 0x80, |a, n| retry.push((a, n))); + assert_eq!(retry, [(0x5000, 0x40)], "a fully submitted run is not made stale again"); + } + #[test] fn quarantine_uses_installed_retirement_marks_and_fails_closed_without_one() { use std::sync::Arc; @@ -2605,6 +2689,37 @@ mod tests { (base, s) } + #[test] + fn a_stalled_upload_ring_returns_and_retries_exact_chunks() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + assert_eq!(VirtualAlloc(base as *mut c_void, TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); + std::ptr::write_bytes(base as *mut u8, 0x5a, PAGE); + s.commit_range(base, TILE); + s.wait_for(s.value); + s.sync_sent_range(base, PAGE); + let before = *s.mapped[&base].sent[0].as_ref().unwrap().clone(); + + s.ring_write = STAGING as u64; + s.ring_submitted = STAGING as u64; + s.ring_free = 0; + s.inflight.push_back((s.value + 1, STAGING as u64)); + let started = std::time::Instant::now(); + assert!(!s.upload_dirty_with_timeout(&[(base + CHUNK, 2 * CHUNK)], 20)); + assert!(started.elapsed() < std::time::Duration::from_secs(2), "a stalled fence kept upload_dirty in its ring loop"); + let after = s.mapped[&base].sent[0].as_ref().unwrap(); + assert_eq!(after[0], before[0], "an already submitted chunk was made dirty again"); + assert_ne!(after[1], before[1]); + assert_ne!(after[2], before[2]); + assert_eq!(after[3], before[3]); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + #[test] fn placement_create_is_unlocked_drains_releases_and_rejects_a_new_generation() { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; From b81ac2ebfbce5d90955833c168ab16d2a879bd0f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:33:03 -0800 Subject: [PATCH 144/265] D3D12.X: process 2D texture tiling in contiguous block runs The existing row-factorized detiler still visited swizzled textures one element at a time and recalculated block placement for every element. Large CPU-written textures therefore consumed milliseconds on the submit path even after persistent detile workers. Adapt raylitebull's 032c661a block-slab algorithm: cache the largest provably contiguous horizontal run for each immutable GFX10 layout, keep one 4 KiB/64 KiB block hot at a time, bulk-copy complete runs, and retain element-wise bounds checks for a truncated source. Low-bit base swizzles shorten runs safely; thick 3D single-slice helpers retain their former path. On this AMD EPYC 7R13 Linux host, an isolated release benchmark against 032c661a's parent reduced 1920x1080 R8 mode-5 detile from 8.8-10.3 ms to 0.76-0.87 ms and tile from 28-31 ms to 0.64-0.78 ms. A 2048x2048 RGBA8 mode-10 detile fell from 28-31 ms to 9.7-11.8 ms and tile from 59-67 ms to 5.8-6.9 ms. All 17 isolated pure tiling tests passed. The Windows GNU library/test cross-check passed with the existing warnings; Windows MSVC, GPU, and smoke tests were unavailable. Source algorithm: 032c661a by raylitebull, assisted by Antigravity (Gemini 4 Neon High). Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/tiling.rs | 383 +++++++++++++++++++++++++++++------ 1 file changed, 321 insertions(+), 62 deletions(-) diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index b9fa1abdd3..9515bd44c2 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -66,6 +66,9 @@ pub struct Layout { /// XORed into every in-block byte offset: the pipe / bank swizzle a T# base address carries /// in its low bits (`base & (block_bytes - 1)`), 0 otherwise pub base_xor: usize, + /// largest power-of-two horizontal element run inside a block whose byte offsets advance + /// contiguously by `+e` with zero interference from `oy`/`oz`/`hx`/`hy`/`hz` + run_elems: usize, ox: &'static [u32], oy: &'static [u32], oz: &'static [u32], @@ -108,7 +111,7 @@ impl Layout { if mode == 0 { let bw = 256 >> elem_log2; let ox: &'static [u32] = (0..bw as u32).map(|x| x << elem_log2).collect::<Vec<_>>().leak(); - return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, ox, oy: &[0], oz: &[0], hx: &[0], hy: &[0], hz: &[0] }); + return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, run_elems: bw, ox, oy: &[0], oz: &[0], hx: &[0], hy: &[0], hz: &[0] }); } let blk = block_log2(mode)?; let bits = pattern_bits(PATTERNS, mode, elem_log2, cfg)?; @@ -161,6 +164,29 @@ impl Layout { let used = bits[..blk as usize].iter().fold(0u32, |m, &b| m | ((b >> shift) & 0xFFFF) as u32) >> l.min(16); table(1 << (32 - used.leading_zeros()), shift, l) }; + let ox = table(bw, 0, 0); + let oy = table(bh, 16, 0); + let oz = table(bd, 32, 0); + let hx = high(wl, 0); + let hy = high(hl, 16); + let hz = high(dl, 32); + let other_bits = oy.iter().chain(oz).chain(hx).chain(hy).chain(hz).fold(0u32, |a, &b| a | b); + let mut run_elems = 1usize; + while run_elems * 2 <= bw { + let next = run_elems * 2; + let mask = ((next << elem_log2) - 1) as u32; + if (other_bits & mask) != 0 { + break; + } + let ok = (0..bw).all(|x| { + let base = ox[x & !(next - 1)]; + (base & mask) == 0 && ox[x] == base + (((x & (next - 1)) << elem_log2) as u32) + }); + if !ok { + break; + } + run_elems = next; + } Layout { mode, elem_log2, @@ -169,12 +195,13 @@ impl Layout { block_d: bd, block_bytes: 1 << blk, base_xor: 0, - ox: table(bw, 0, 0), - oy: table(bh, 16, 0), - oz: table(bd, 32, 0), - hx: high(wl, 0), - hy: high(hl, 16), - hz: high(dl, 32), + run_elems, + ox, + oy, + oz, + hx, + hy, + hz, } } @@ -204,34 +231,215 @@ impl Layout { block * self.block_bytes + (xor as usize ^ self.base_xor) } + /// Effective horizontal contiguous run width in elements, respecting any `base_xor` low bits. + #[inline] + fn effective_run(&self) -> usize { + if self.base_xor == 0 { + self.run_elems + } else { + let lim = (1usize << self.base_xor.trailing_zeros()) >> self.elem_log2; + self.run_elems.min(lim).max(1) + } + } + /// tiled → linear rows (`w << elem_log2` bytes each); bytes past the end of `src` read as 0 pub fn detile(&self, src: &[u8], w: usize, h: usize) -> Vec<u8> { let e = 1usize << self.elem_log2; let mut out = vec![0u8; w * h * e]; - for y in 0..h { - for x in 0..w { - let o = self.offset(x, y, w); - if let Some(s) = src.get(o..o + e) { - let d = (y * w + x) * e; - out[d..d + e].copy_from_slice(s); - } - } - } + self.detile_2d(src, &mut out, 0, w, h, w, (0, 0), 0); out } /// linear rows → tiled (the inverse of `detile`) pub fn tile(&self, linear: &[u8], w: usize, h: usize) -> Vec<u8> { - let e = 1usize << self.elem_log2; let mut out = vec![0u8; self.size(w, h)]; - for y in 0..h { - for x in 0..w { - let o = self.offset(x, y, w); - let s = (y * w + x) * e; - out[o..o + e].copy_from_slice(&linear[s..s + e]); + self.tile_2d(&mut out, linear, 0, w, h, w, (0, 0), 0); + out + } + + /// Block-slab 2D detile with contiguous horizontal run copies (`src` tiled -> `out` linear). + /// Iterating one tiled block `(by, bx)` at a time keeps each 4 KiB / 64 KiB block hot in L1 + /// cache and eliminates per-element block arithmetic and bounds checks on complete blocks. + #[allow(clippy::too_many_arguments)] + fn detile_2d(&self, src: &[u8], out: &mut [u8], base_off: usize, w: usize, h: usize, pitch: usize, origin: (usize, usize), slice: usize) { + if w == 0 || h == 0 { + return; + } + let e = 1usize << self.elem_log2; + if self.mode == 0 && self.base_xor == 0 && origin == (0, 0) { + let row = w * e; + let pitch_blocks = pitch.div_ceil(self.block_w); + for y in 0..h { + let o = base_off + (y / self.block_h) * pitch_blocks * self.block_bytes + self.oy[y % self.block_h] as usize; + let n = src.len().saturating_sub(o).min(row) / e * e; + if n > 0 { + out[y * row..][..n].copy_from_slice(&src[o..o + n]); + } + } + return; + } + let pitch_blocks = pitch.div_ceil(self.block_w); + let z = self.oz[slice % self.block_d] ^ self.hz[(slice / self.block_d) % self.hz.len()]; + let run = self.effective_run(); + let run_bytes = run * e; + let row_bytes = w * e; + let (ox0, oy0) = origin; + let bx_start = ox0 / self.block_w; + let bx_end = (ox0 + w - 1) / self.block_w; + let by_start = oy0 / self.block_h; + let by_end = (oy0 + h - 1) / self.block_h; + + for by in by_start..=by_end { + let y_lo = (by * self.block_h).max(oy0) - oy0; + let y_hi = ((by + 1) * self.block_h).min(oy0 + h) - oy0; + let hy = self.hy[by % self.hy.len()] ^ z; + let row_blocks = by * pitch_blocks; + for bx in bx_start..=bx_end { + let x_lo = (bx * self.block_w).max(ox0) - ox0; + let x_hi = ((bx + 1) * self.block_w).min(ox0 + w) - ox0; + let block_base = base_off + (row_blocks + bx) * self.block_bytes; + let b_xor = self.hx[bx % self.hx.len()] ^ hy ^ self.base_xor as u32; + let xi_lo = x_lo + ox0 - bx * self.block_w; + let xi_hi = x_hi + ox0 - bx * self.block_w; + if block_base.checked_add(self.block_bytes).is_some_and(|end| end <= src.len()) { + let blk = &src[block_base..block_base + self.block_bytes]; + if run > 1 { + let aligned_lo = (xi_lo + run - 1) & !(run - 1); + let aligned_hi = xi_hi & !(run - 1); + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + let mut xi = xi_lo; + let mut x = x_lo; + let pre = aligned_lo.min(xi_hi); + while xi < pre { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + e].copy_from_slice(&blk[o..o + e]); + xi += 1; + x += 1; + } + while xi < aligned_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + run_bytes].copy_from_slice(&blk[o..o + run_bytes]); + xi += run; + x += run; + } + while xi < xi_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + e].copy_from_slice(&blk[o..o + e]); + xi += 1; + x += 1; + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = (x_off ^ y_xor) as usize; + let d = (x_lo + dx) * e; + dst_row[d..d + e].copy_from_slice(&blk[o..o + e]); + } + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = block_base + (x_off ^ y_xor) as usize; + if let Some(s) = src.get(o..o + e) { + let d = (x_lo + dx) * e; + dst_row[d..d + e].copy_from_slice(s); + } + } + } + } + } + } + } + + /// Block-slab 2D tile with contiguous horizontal run copies (`linear` -> `dst` tiled). + #[allow(clippy::too_many_arguments)] + fn tile_2d(&self, dst: &mut [u8], linear: &[u8], base_off: usize, w: usize, h: usize, pitch: usize, origin: (usize, usize), slice: usize) { + if w == 0 || h == 0 { + return; + } + let e = 1usize << self.elem_log2; + if self.mode == 0 && self.base_xor == 0 && origin == (0, 0) { + let row = w * e; + let pitch_blocks = pitch.div_ceil(self.block_w); + for y in 0..h { + let o = base_off + (y / self.block_h) * pitch_blocks * self.block_bytes + self.oy[y % self.block_h] as usize; + dst[o..o + row].copy_from_slice(&linear[y * row..][..row]); + } + return; + } + let pitch_blocks = pitch.div_ceil(self.block_w); + let z = self.oz[slice % self.block_d] ^ self.hz[(slice / self.block_d) % self.hz.len()]; + let run = self.effective_run(); + let run_bytes = run * e; + let row_bytes = w * e; + let (ox0, oy0) = origin; + let bx_start = ox0 / self.block_w; + let bx_end = (ox0 + w - 1) / self.block_w; + let by_start = oy0 / self.block_h; + let by_end = (oy0 + h - 1) / self.block_h; + + for by in by_start..=by_end { + let y_lo = (by * self.block_h).max(oy0) - oy0; + let y_hi = ((by + 1) * self.block_h).min(oy0 + h) - oy0; + let hy = self.hy[by % self.hy.len()] ^ z; + let row_blocks = by * pitch_blocks; + for bx in bx_start..=bx_end { + let x_lo = (bx * self.block_w).max(ox0) - ox0; + let x_hi = ((bx + 1) * self.block_w).min(ox0 + w) - ox0; + let block_base = base_off + (row_blocks + bx) * self.block_bytes; + let b_xor = self.hx[bx % self.hx.len()] ^ hy ^ self.base_xor as u32; + let xi_lo = x_lo + ox0 - bx * self.block_w; + let xi_hi = x_hi + ox0 - bx * self.block_w; + let blk = &mut dst[block_base..block_base + self.block_bytes]; + if run > 1 { + let aligned_lo = (xi_lo + run - 1) & !(run - 1); + let aligned_hi = xi_hi & !(run - 1); + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let src_row = &linear[y * row_bytes..(y + 1) * row_bytes]; + let mut xi = xi_lo; + let mut x = x_lo; + let pre = aligned_lo.min(xi_hi); + while xi < pre { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + e].copy_from_slice(&src_row[x * e..x * e + e]); + xi += 1; + x += 1; + } + while xi < aligned_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + run_bytes].copy_from_slice(&src_row[x * e..x * e + run_bytes]); + xi += run; + x += run; + } + while xi < xi_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + e].copy_from_slice(&src_row[x * e..x * e + e]); + xi += 1; + x += 1; + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let src_row = &linear[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = (x_off ^ y_xor) as usize; + let s = (x_lo + dx) * e; + blk[o..o + e].copy_from_slice(&src_row[s..s + e]); + } + } + } } } - out } } @@ -378,6 +586,7 @@ impl Chain { /// element (x, y) of level `l` in array slice `slice` (from the slice's start): the slice /// is z of the 2D patterns – the XOR modes take pipe bits from it + #[cfg(test)] fn element_at(&self, l: &MipLevel, x: usize, y: usize, slice: usize) -> usize { l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch) } @@ -425,59 +634,37 @@ impl Chain { /// bytes past the end of `src` read as 0 pub fn detile_level(&self, src: &[u8], i: usize, slice: usize) -> Vec<u8> { let l = self.levels[i]; - let t = &self.layout; - let e = 1usize << t.elem_log2; + let e = 1usize << self.layout.elem_log2; let mut out = vec![0u8; l.width * l.height * e]; - if t.mode == 0 && t.base_xor == 0 && l.origin == (0, 0) { - // linear: a row's elements are contiguous, so it is copied whole (the elements that - // are all in `src`, as below) – a video plane of 3840×2160 is 2160 copies, not 8 M - let row = l.width * e; + if self.layout.block_d != 1 { for y in 0..l.height { - let o = self.element_at(&l, 0, y, slice); - let n = src.len().saturating_sub(o).min(row) / e * e; - if n > 0 { - out[y * row..][..n].copy_from_slice(&src[o..o + n]); + for x in 0..l.width { + let offset = l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch); + if let Some(bytes) = src.get(offset..offset + e) { + out[(y * l.width + x) * e..][..e].copy_from_slice(bytes); + } } } return out; } - // `element_at` (`Layout::offset_z`) split: what depends on x alone once per level, what - // depends on y (and the slice) once per row – per element only two lookups and an XOR. - // Element by element it was most of a retail game's render thread while it streamed - // textures the CPU writes. - let hi = |tab: &[u32], c: usize, b: usize| tab[(c / b) % tab.len()]; - let pitch_blocks = l.pitch.div_ceil(t.block_w); - let columns: Vec<(usize, u32)> = (0..l.width) - .map(|x| { - let x = x + l.origin.0; - (x / t.block_w, t.ox[x % t.block_w] ^ hi(&t.hx, x, t.block_w)) - }) - .collect(); - let z = t.oz[slice % t.block_d] ^ hi(&t.hz, slice, t.block_d); - for (y, row) in out.chunks_exact_mut(l.width * e).enumerate() { - let y = y + l.origin.1; - let row_blocks = (y / t.block_h) * pitch_blocks; - let yz = t.oy[y % t.block_h] ^ hi(&t.hy, y, t.block_h) ^ z; - for (&(block_x, x), dst) in columns.iter().zip(row.chunks_exact_mut(e)) { - let o = l.offset + (row_blocks + block_x) * t.block_bytes + ((x ^ yz) as usize ^ t.base_xor); - if let Some(s) = src.get(o..o + e) { - dst.copy_from_slice(s); - } - } - } + self.layout.detile_2d(src, &mut out, l.offset, l.width, l.height, l.pitch, l.origin, slice); out } /// linear rows of level `i` → its place in array slice `slice` (`dst`, `slice_bytes` long) pub fn tile_level(&self, dst: &mut [u8], i: usize, slice: usize, linear: &[u8]) { let l = self.levels[i]; - let e = 1usize << self.layout.elem_log2; - for y in 0..l.height { - for x in 0..l.width { - let o = self.element_at(&l, x, y, slice); - dst[o..o + e].copy_from_slice(&linear[(y * l.width + x) * e..][..e]); + if self.layout.block_d != 1 { + let e = 1usize << self.layout.elem_log2; + for y in 0..l.height { + for x in 0..l.width { + let offset = l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch); + dst[offset..offset + e].copy_from_slice(&linear[(y * l.width + x) * e..][..e]); + } } + return; } + self.layout.tile_2d(dst, linear, l.offset, l.width, l.height, l.pitch, l.origin, slice); } } @@ -705,6 +892,15 @@ mod tests { let cfg = PipeConfig { pipes_log2: 0, pkrs_log2: 0 }; assert_eq!(Layout::new_3d(24, 2, cfg).unwrap().block_d, 1); assert!(Layout::new_3d(10, 2, cfg).is_none() && Layout::new_3d(1, 2, cfg).is_none()); + + // The 2D block-slab fast path must not change the legacy single-slice helpers on a + // thick layout (volume callers normally use `tile_volume` / `detile_volume`). + let chain = Chain::new_3d(Layout::new_3d(5, 2, cfg).unwrap(), 19, 13, 4, 1, 1); + let level = chain.levels[0]; + let linear: Vec<u8> = (0..level.width * level.height * 4).map(|i| (i * 37) as u8).collect(); + let mut tiled = vec![0u8; chain.slice_bytes]; + chain.tile_level(&mut tiled, 0, 1, &linear); + assert_eq!(chain.detile_level(&tiled, 0, 1), linear); } /// The three volume textures of the retail TTPF archive (4 KB tiles, thick): the space each @@ -872,5 +1068,68 @@ mod tests { assert!(!g.contains_key(&(false, 9, 5, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }))); assert!(!g.contains_key(&(true, 10, 2, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }))); } + + #[test] + fn tile_level_matches_element_by_element_and_exploits_contiguous_runs() { + // Standard 2D modes with 1..4B elements must detect multi-element contiguous runs. + assert!(Layout::new(5, 0, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }).unwrap().run_elems >= 4); + assert!(Layout::new(10, 2, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }).unwrap().run_elems >= 2); + for mode in MODES { + for e in 0..5u32 { + for cfg in configs() { + let mut lay = Layout::new(mode, e, cfg).unwrap(); + lay.base_xor = (lay.block_bytes / 2) & !((1 << e) - 1); + let c = Chain::new(lay, 77, 45, 1, 7); + let es = 1usize << e; + for (k, l) in c.levels.iter().enumerate() { + let lin: Vec<u8> = (0..l.width * l.height * es).map(|i| ((i * 53 + k * 17) % 251) as u8 | 1).collect(); + for slice in [0usize, 3] { + let mut got = vec![0u8; c.slice_bytes]; + let mut want = vec![0u8; c.slice_bytes]; + c.tile_level(&mut got, k, slice, &lin); + for y in 0..l.height { + for x in 0..l.width { + let o = c.element_at(l, x, y, slice); + want[o..o + es].copy_from_slice(&lin[(y * l.width + x) * es..][..es]); + } + } + assert!(got == want, "tile_level mismatch: mode {mode} e {e} {cfg:?} level {k} slice {slice}"); + } + } + } + } + } + } + + #[test] + fn low_base_xor_bits_bound_runs_without_changing_bytes() { + for (mode, e) in [(5, 0u32), (10, 2)] { + let es = 1usize << e; + for cfg in configs() { + let plain = Layout::new(mode, e, cfg).unwrap(); + for xor in [es, 3 * es, plain.block_bytes / 2] { + let mut layout = plain; + layout.base_xor = xor; + if xor == es { + assert_eq!(layout.effective_run(), 1, "mode {mode} e {e} {cfg:?}"); + } + let chain = Chain::new(layout, 77, 45, 1, 1); + let level = chain.levels[0]; + let linear: Vec<u8> = (0..level.width * level.height * es).map(|i| (i * 53 % 251) as u8).collect(); + let mut tiled = vec![0u8; chain.slice_bytes]; + chain.tile_level(&mut tiled, 0, 0, &linear); + let mut want = vec![0u8; chain.slice_bytes]; + for y in 0..level.height { + for x in 0..level.width { + let offset = chain.element_at(&level, x, y, 0); + want[offset..offset + es].copy_from_slice(&linear[(y * level.width + x) * es..][..es]); + } + } + assert_eq!(tiled, want, "mode {mode} e {e} {cfg:?} xor {xor:#x}"); + assert_eq!(chain.detile_level(&tiled, 0, 0), linear, "mode {mode} e {e} {cfg:?} xor {xor:#x}"); + } + } + } + } } From 0eaef7e66b06e1f532c38371b1ecfbb800c7b671 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:34:45 -0800 Subject: [PATCH 145/265] D3D12.X: complete failed pipeline worker jobs Integrated XCL already keeps cold title-visible builds on workers, superseding #2615's title-thread compile fix without adopting its correctness-losing default skip policy. Worker failure still had terminal holes: a panicking job was caught only outside the Build and never woke its waiters, a panicking parallel piece omitted a result, and zero workers or a refused queue left accepted work with no executor. Catch pipeline and piece panics as failed results, restore worker-local/preload state before publishing completion, and fail exact jobs when no normal worker can start or the queue refuses them. Failed speculative-preload startup leaves the build dormant so a later title demand can schedule it normally. The Windows GNU library/test cross-check passed with the existing 11 library warnings and 2 test warnings (1 duplicate). Windows MSVC runtime, GPU, and smoke tests were not available here. Panic-recovery source: #2053 by RandomGithub12309, written with Antigravity (Gemini 4 Neon). Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 130 +++++++++++++++++++++---- 1 file changed, 110 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 8b3f9943c8..9b4fe25d95 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -132,6 +132,27 @@ impl Drop for RestoreBuilding { } } +fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str { + if let Some(message) = payload.downcast_ref::<&str>() { + message + } else if let Some(message) = payload.downcast_ref::<String>() { + message.as_str() + } else { + "unknown panic" + } +} + +/// Run a pipeline job without letting one bad shader strand every waiter on its shared build. +fn run_job(job: Job) -> usize { + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)) { + Ok(real) => real, + Err(payload) => { + crate::xlog_error!("D3D12.X: panic while building pipeline: {}", panic_message(payload.as_ref())); + 0 + } + } +} + /// A worker's pipeline build (`preload`: by one of the lowest-priority workers). fn run_build(build: &Arc<Build>, job: Job) { use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_NORMAL}; @@ -144,8 +165,11 @@ fn run_build(build: &Arc<Build>, job: Job) { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } - let _running = RunningBuild { build, preload }; - complete(build, job()); + let real = { + let _running = RunningBuild { build, preload }; + run_job(job) + }; + complete(build, real); } impl Build { @@ -206,7 +230,7 @@ impl Build { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_PRIORITY_NORMAL, THREAD_SET_LIMITED_INFORMATION}; let newly_wanted = !self.wanted.swap(true, Ordering::AcqRel); - start_normal_workers(); + let _ = start_normal_workers(); self.promote(Priority::Foreground); if newly_wanted { let d = self.demand.lock().unwrap(); @@ -536,20 +560,24 @@ pub fn ranked_preload_stats() -> RankedPreloadStats { } } -fn start_normal_workers() { - static STARTED: std::sync::Once = std::sync::Once::new(); - STARTED.call_once(|| { +fn start_normal_workers() -> bool { + static STARTED: OnceLock<bool> = OnceLock::new(); + *STARTED.get_or_init(|| { let q = queue(); // translation recurses deeply on big programs; DXC itself runs on its own pool let n = crate::gpu::recomp::dxc::compile_threads(); + let mut started = 0; for k in 0..n { let worker = q.worker_between(Priority::BoundSoon, Priority::Foreground); - let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || { + if std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || { NORMAL_WORKER.set(true); worker.run(); - }); + }).is_ok() { + started += 1; + } } - }); + started != 0 + }) } /// Normal workers waiting for a huge driver-compile slot, and bounded replacements serving their @@ -623,23 +651,27 @@ fn retire_normal_helper() -> bool { false } -fn start_preload_workers() { - static STARTED: std::sync::Once = std::sync::Once::new(); - STARTED.call_once(|| { +fn start_preload_workers() -> bool { + static STARTED: OnceLock<bool> = OnceLock::new(); + *STARTED.get_or_init(|| { let q = queue(); let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); + let mut started = 0; for k in 0..n { let worker = q.worker_between(Priority::Speculative, Priority::Preload); - let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { + if std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { unsafe { use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); } PRELOAD_WORKER.set(true); worker.run(); - }); + }).is_ok() { + started += 1; + } } - }); + started != 0 + }) } fn submit_job(q: &BuildQueue, build: &Arc<Build>, priority: Priority, preload: bool, preload_rank: Option<usize>) -> Option<JobHandle> { @@ -665,11 +697,15 @@ fn enqueue_on(q: &BuildQueue, build: &Arc<Build>, priority: Priority, preload: b fn schedule(build: &Arc<Build>, priority: Priority, preload: bool, preload_rank: Option<usize>) { if preload { - start_preload_workers(); - } else { - start_normal_workers(); + if !start_preload_workers() { + return; + } + } else if !start_normal_workers() { + fail_unrunnable_build(build); + return; } let mut queued = build.queued.lock().unwrap(); + let mut refused = false; if !build.sent.swap(true, Ordering::AcqRel) { let priority = if build.wanted.load(Ordering::Acquire) || build.demand.lock().unwrap().by_submit { Priority::Foreground @@ -679,8 +715,25 @@ fn schedule(build: &Arc<Build>, priority: Priority, preload: bool, preload_rank: *queued = submit_job(queue(), build, priority, preload, preload_rank); if queued.is_some() { build.note_queued(); + } else { + refused = true; } } + drop(queued); + if refused { + fail_unrunnable_build(build); + } +} + +/// No normal worker can run this job, or its queue refused it. Fail instead of leaving title +/// waiters asleep on work which cannot make progress. +fn fail_unrunnable_build(build: &Arc<Build>) { + build.cancel_queued(); + let job = build.job.lock().unwrap().take(); + if let Some(job) = job { + drop(job); + complete(build, 0); + } } fn build_queued(build: &Arc<Build>) -> bool { @@ -708,11 +761,11 @@ pub(super) fn build_pieces(jobs: Vec<Job>) -> Vec<usize> { let drain = move || loop { let job = jobs.lock().unwrap().pop(); let Some((i, job)) = job else { return }; - let _ = send.send((i, job())); + let _ = send.send((i, run_job(job))); }; // the helpers build for this worker's pipeline: the title waiting for it waits for them too let parent = BUILDING.with(|b| b.borrow().clone()); - start_normal_workers(); + let _ = start_normal_workers(); for _ in 1..count.min(crate::gpu::recomp::dxc::compile_threads()) { let (drain, parent) = (drain.clone(), parent.clone()); let _ = queue().submit(Priority::BoundSoon, Box::new(move || { @@ -960,6 +1013,43 @@ fn preload_enabled() -> bool { mod used_tests { use super::*; + #[test] + fn a_panicking_pipeline_job_completes_failed_and_wakes_its_waiter() { + let build = Arc::new(Build::new(Box::new(|| panic!("simulated pipeline panic")), false)); + let waiting = build.clone(); + let (tx, rx) = mpsc::channel(); + let waiter = std::thread::spawn(move || { + let (done, _) = waiting + .cv + .wait_timeout_while(waiting.done.lock().unwrap(), std::time::Duration::from_secs(5), |done| !*done) + .unwrap(); + tx.send((*done, waiting.real.load(Ordering::Acquire))).unwrap(); + }); + + let job = build.job.lock().unwrap().take().unwrap(); + run_build(&build, job); + assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(5)), Ok((true, 0))); + waiter.join().unwrap(); + assert!(BUILDING.with(|building| building.borrow().is_none()), "panicking build left worker-local demand installed"); + + let next = Arc::new(Build::new(Box::new(|| 0x5151), false)); + let job = next.job.lock().unwrap().take().unwrap(); + run_build(&next, job); + assert_eq!(next.real.load(Ordering::Acquire), 0x5151, "the worker path did not survive a prior panic"); + + let refused = Arc::new(Build::new(Box::new(|| 0x6161), false)); + fail_unrunnable_build(&refused); + assert!(*refused.done.lock().unwrap(), "worker-start/submission failure did not complete the build"); + assert!(refused.job.lock().unwrap().is_none()); + assert_eq!(refused.real.load(Ordering::Acquire), 0); + + assert_eq!( + build_pieces(vec![Box::new(|| 0x11), Box::new(|| panic!("simulated piece panic")), Box::new(|| 0x33)]), + [0x11, 0, 0x33], + "one failed split piece stranded or discarded its sibling results" + ); + } + #[test] fn pending_registry_routes_exact_lifetimes_across_independent_shards() { let registry = Arc::new(PendingRegistry::new()); From 8540311ed6a0249a1eaa20eee3312042f454d41a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:34:34 -0800 Subject: [PATCH 146/265] Memory: avoid VirtualQuery walks in sparse windows DirectStorage destinations and emulated CLZERO checked sparse-window pages with VirtualQuery. The measured source PR #501 found those walks averaged 6.7 ms, reached 138 ms, and serialized GetWriteWatch on a retail title. Adapt its affirmative commit/protection cache to the integrated sparse lifecycle. The state lock checks one mask per 64 KiB tile and is released before batched working-set queries. Non-writable changes publish conservatively before the OS call, commits publish protection atomically, current-process *Ex handles are tracked by process ID, and probed-but-untracked pages remain in the fallback path. All uncertain cases still use VirtualQuery. The Windows GNU library/test cross-check passed with the existing warnings. Windows MSVC runtime, GPU, and smoke tests were not available here; #501's timing and title results were not independently reproduced. Source implementation and measurements: #501 by mrp1no with Claude Code (Claude Opus 5.5). Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/eh.rs | 3 + crates/xcl/src/hle/d3d12x/sparse.rs | 279 ++++++++++++++++++++++++++-- crates/xcl/src/hle/dstorage.rs | 3 + crates/xcl/src/hle/kernelx.rs | 50 ++++- 4 files changed, 315 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 06277d4a41..727fda141d 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -254,6 +254,9 @@ fn is_writable(va: usize, bytes: usize) -> bool { if bytes > 0 && crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { return true; } + if crate::hle::d3d12x::sparse::known_writable(va, bytes) { + return true; + } let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const std::ffi::c_void, &mut m, std::mem::size_of_val(&m)) } != 0; found diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 70d9dee22b..02007b4de6 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -92,13 +92,15 @@ struct TileEntry { pool: (u32, u32), /// bit `i` set => 4 KiB page `i` of this 64 KiB tile is uncommitted (a hole) holes: u16, + /// bit `i` set => the title gave page `i` a protection other than writable + not_rw: u16, /// per-4 KiB-page hashes of the 64-byte chunks last sent to the GPU (`None` = all zero) sent: [Option<Box<[u64; CHUNKS]>>; PAGES_PER_TILE], } impl TileEntry { fn with_holes(pool: (u32, u32), holes: u16) -> Self { - Self { pool, holes, sent: std::array::from_fn(|_| None) } + Self { pool, holes, not_rw: 0, sent: std::array::from_fn(|_| None) } } } @@ -500,6 +502,18 @@ fn memory_byte_counts( /// every page committed so far. Like `committed` / `decommitted` with a state, a range counts /// every page it touches; `init` commits them once the windows exist. static EARLY: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); +/// Before the sparse device exists: pages the title protected other than writable. Commits clear +/// these ranges, and `init` replays what remains after the early commits. +static EARLY_NOT_RW: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); + +fn early_protection(early: &mut BTreeMap<usize, usize>, a: usize, n: usize, writable: bool) { + let (start, end) = page_span(a, n); + if writable { + early_remove(early, start, end); + } else { + early_add(early, start, end); + } +} /// The pages `[a, a + n)` touches, as `[start, end)`. fn page_span(a: usize, n: usize) -> (usize, usize) { @@ -658,12 +672,18 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { // (the queue first: `queue()` never answers with one older than the state's) let _placement = PLACEMENT.lock().unwrap(); let old_queue = QUEUE.lock().unwrap().replace(s.queue.clone()); - let old = STATE.lock().unwrap().replace(s); - drop(old); - drop(old_queue); + let mut state = STATE.lock().unwrap(); + let old = state.replace(s); + let s = state.as_mut().unwrap(); for (a, b) in std::mem::take(&mut *EARLY.lock().unwrap()) { - committed(a, b - a); + s.commit_range(a, b - a); } + for (a, b) in std::mem::take(&mut *EARLY_NOT_RW.lock().unwrap()) { + mark_protection(&mut s.mapped, a, b - a, false); + } + drop(state); + drop(old); + drop(old_queue); out } Err(e) => { @@ -846,9 +866,9 @@ impl State { ); } - /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_holes` supplies - /// the initial 16-bit hole mask for each newly mapped 64 KiB tile. - unsafe fn ensure_mapped(&mut self, a: usize, n: usize, mut initial_holes: impl FnMut(usize) -> u16) { + /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_state` supplies + /// the initial `(holes, untrusted protection)` masks for each newly mapped 64 KiB tile. + unsafe fn ensure_mapped(&mut self, a: usize, n: usize, mut initial_state: impl FnMut(usize) -> (u16, u16)) { if n == 0 { return; } @@ -861,13 +881,19 @@ impl State { if !self.mapped.contains_key(&t) && self.window_index(t).is_some() { // still mapped there: no new mapping, what it held is cleared if let Some(tile) = self.parked.remove(&t) { - self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); + let (holes, not_rw) = initial_state(t); + let mut entry = TileEntry::with_holes(tile, holes); + entry.not_rw = not_rw; + self.mapped.insert(t, entry); self.runs = None; self.to_zero.push((t, TILE)); unparked = true; } else { let Some((tile, reused)) = self.take_tile() else { break }; - self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); + let (holes, not_rw) = initial_state(t); + let mut entry = TileEntry::with_holes(tile, holes); + entry.not_rw = not_rw; + self.mapped.insert(t, entry); self.runs = None; if reused { self.to_zero.push((t, TILE)); @@ -1403,6 +1429,12 @@ pub unsafe fn readback_now(va: usize, len: usize) { /// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that /// lie outside the range are not committed (holes); the range's pages are. pub unsafe fn committed(a: usize, n: usize) { + committed_with_protection(a, n, true); +} + +/// `committed`, recording the protection established by the same successful commit without an +/// interval in which an affirmative writability query can observe the new page incorrectly. +pub unsafe fn committed_with_protection(a: usize, n: usize, writable: bool) { if n == 0 { return; } @@ -1410,9 +1442,14 @@ pub unsafe fn committed(a: usize, n: usize) { let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); early_add(&mut EARLY.lock().unwrap(), start, end); + if writable { + early_remove(&mut EARLY_NOT_RW.lock().unwrap(), start, end); + } else { + early_add(&mut EARLY_NOT_RW.lock().unwrap(), start, end); + } return; }; - s.commit_range(a, n); + s.commit_range_with_protection(a, n, writable); } /// The title decommitted `[a, a + n)`: tiles whose pages are all uncommitted (whether in one @@ -1434,7 +1471,11 @@ pub unsafe fn decommitted(a: usize, n: usize) { impl State { /// `committed` with the state locked unsafe fn commit_range(&mut self, a: usize, n: usize) { - self.ensure_mapped(a, n, |_| 0xFFFF); + self.commit_range_with_protection(a, n, true); + } + + unsafe fn commit_range_with_protection(&mut self, a: usize, n: usize, writable: bool) { + self.ensure_mapped(a, n, |_| (0xFFFF, 0)); let mut pg = a & !(PAGE - 1); let end = a.saturating_add(n); while pg < end { @@ -1443,7 +1484,13 @@ impl State { if let Some(entry) = self.mapped.get_mut(&t) { let mut p = pg; while p < tile_end { - entry.holes &= !(1u16 << ((p - t) / PAGE)); + let bit = 1u16 << ((p - t) / PAGE); + entry.holes &= !bit; + if writable { + entry.not_rw &= !bit; + } else { + entry.not_rw |= bit; + } p += PAGE; } } @@ -1616,6 +1663,128 @@ impl State { } } +/// Whether `[p, p + n)` lies in a sparse window and every page is recorded as committed and +/// writable. False means the caller must ask Windows; this cache only supplies affirmative +/// answers, avoiding `VirtualQuery` walking a multi-gigabyte sparse reservation. +pub fn known_writable(p: usize, n: usize) -> bool { + let Some(end) = p.checked_add(n) else { return false }; + if n == 0 || !crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p) && u.is_sparse(end - 1)) { + return false; + } + { + let state = STATE.lock().unwrap(); + let Some(state) = state.as_ref() else { return false }; + if !recorded_committed(&state.mapped, p, end) { + return false; + } + } + resident_pages_writable(p, end) +} + +/// Every page touched by `[p, end)` has video-memory backing, is committed, and has not been +/// given a non-writable protection. Check one 64 KiB tile at a time while holding `STATE`. +fn recorded_committed(mapped: &FxHashMap<usize, TileEntry>, p: usize, end: usize) -> bool { + let mut tile = p & !(TILE - 1); + while tile < end { + let first = (p.max(tile) - tile) / PAGE; + let tile_end = tile.saturating_add(TILE).min(end); + let last = (tile_end - 1 - tile) / PAGE; + let pages = last - first + 1; + let mask = ((((1u32 << pages) - 1) << first) & u16::MAX as u32) as u16; + if !mapped.get(&tile).is_some_and(|entry| (entry.holes | entry.not_rw) & mask == 0) { + return false; + } + if tile_end <= tile { + return false; + } + tile = tile_end; + } + true +} + +/// Record a successful protection change in a sparse window. `writable` means a writable +/// protection without PAGE_GUARD. Before device creation, retain page ranges for `init` replay. +pub fn protection_changed(a: usize, n: usize, writable: bool) { + let Some(end) = a.checked_add(n) else { return }; + let Some(uma) = crate::gpu::uma::get() else { return }; + let mut state = STATE.lock().unwrap(); + for k in 0..uma.shader_windows() { + if !uma.is_sparse_window(k) { + continue; + } + let (base, size) = uma.window(k); + let (start, stop) = (a.max(base), end.min(base.saturating_add(size))); + if start >= stop { + continue; + } + match state.as_mut() { + Some(state) => mark_protection(&mut state.mapped, start, stop - start, writable), + None => early_protection(&mut EARLY_NOT_RW.lock().unwrap(), start, stop - start, writable), + } + } +} + +fn mark_protection(mapped: &mut FxHashMap<usize, TileEntry>, a: usize, n: usize, writable: bool) { + let end = a.saturating_add(n); + let mut tile = a & !(TILE - 1); + while tile < end { + let first = (a.max(tile) - tile) / PAGE; + let tile_end = tile.saturating_add(TILE).min(end); + let last = (tile_end - 1 - tile) / PAGE; + let pages = last - first + 1; + let mask = ((((1u32 << pages) - 1) << first) & u16::MAX as u32) as u16; + if let Some(entry) = mapped.get_mut(&tile) { + if writable { + entry.not_rw &= !mask; + } else { + entry.not_rw |= mask; + } + } + if tile_end <= tile { + break; + } + tile = tile_end; + } +} + +/// No resident page in `[p, end)` has a non-writable or guard protection. Nonresident pages are +/// judged by the protection record above; this query inspects metadata without touching pages. +fn resident_pages_writable(p: usize, end: usize) -> bool { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + const BATCH: usize = 64; + const WRITABLE: usize = 0x04 | 0x08 | 0x40 | 0x80; + let (first, last) = (p >> 12, (end - 1) >> 12); + let mut entries: [PSAPI_WORKING_SET_EX_INFORMATION; BATCH] = unsafe { std::mem::zeroed() }; + let mut page = first; + while page <= last { + let count = (last - page + 1).min(BATCH); + for (i, entry) in entries[..count].iter_mut().enumerate() { + *entry = unsafe { std::mem::zeroed() }; + entry.VirtualAddress = ((page + i) << 12) as *mut c_void; + } + let bytes = (count * std::mem::size_of::<PSAPI_WORKING_SET_EX_INFORMATION>()) as u32; + if unsafe { + K32QueryWorkingSetEx( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + entries.as_mut_ptr() as *mut c_void, + bytes, + ) + } == 0 + { + return false; + } + if entries[..count].iter().any(|entry| { + let flags = unsafe { entry.VirtualAttributes.Flags }; + let protection = (flags >> 4) & 0x7FF; + flags & 1 != 0 && (protection & WRITABLE == 0 || protection & PAGE_GUARD as usize != 0) + }) { + return false; + } + page += count; + } + true +} + /// The sparse windows' tiles with video memory as sorted (start, end) runs: where a CPU write /// has to reach the GPU. pub fn mapped_ranges() -> Vec<(usize, usize)> { @@ -1854,7 +2023,10 @@ unsafe fn place_buffer_in( let s = g.as_mut().unwrap(); // its tiles: the window's video memory at the same addresses; probe actual OS commitment // so uncommitted pages (e.g. [start, va) or reserved tails) stay marked as holes - s.ensure_mapped(start, delta + bytes, |t| query_tile_holes(t)); + s.ensure_mapped(start, delta + bytes, |t| { + let holes = query_tile_holes(t); + (holes, !holes) + }); let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|e| (t, e.pool))).collect(); s.map_tiles(&res, start, &tiles); if s.buffers.contains_key(&(raw as usize)) { @@ -1929,6 +2101,69 @@ fn forget_in(s: &mut State, res: usize) { mod tests { use super::*; + #[test] + fn writable_record_requires_every_touched_page_and_tracks_protection() { + let mut mapped = FxHashMap::default(); + let (t0, t1) = (0x10_0000usize, 0x11_0000usize); + mapped.insert(t0, TileEntry::with_holes((0, 1), 0)); + mapped.insert(t1, TileEntry::with_holes((0, 2), 1 << 2)); + + assert!(recorded_committed(&mapped, t0, t0 + TILE)); + assert!(recorded_committed(&mapped, t0 + 0x800, t1 + 2 * PAGE)); + assert!(!recorded_committed(&mapped, t1 + 2 * PAGE, t1 + 2 * PAGE + 1)); + assert!(!recorded_committed(&mapped, t1 + TILE - 8, t1 + TILE + 8)); + + mark_protection(&mut mapped, t0 + 5 * PAGE + 16, 8, false); + assert!(!recorded_committed(&mapped, t0 + 5 * PAGE, t0 + 5 * PAGE + 1)); + assert!(recorded_committed(&mapped, t0 + 6 * PAGE, t0 + TILE)); + mark_protection(&mut mapped, t0 + 5 * PAGE, PAGE, true); + assert!(recorded_committed(&mapped, t0, t0 + TILE)); + } + + #[test] + fn early_protection_ranges_merge_split_and_commit_clears_them() { + let base = 0x20_0000usize; + let mut protected = BTreeMap::new(); + early_protection(&mut protected, base + PAGE + 16, 8, false); + early_protection(&mut protected, base + 3 * PAGE, 3 * PAGE, false); + early_protection(&mut protected, base + 5 * PAGE, PAGE, true); + assert_eq!(protected.into_iter().collect::<Vec<_>>(), [(base + PAGE, base + 2 * PAGE), (base + 3 * PAGE, base + 5 * PAGE)]); + + let mut protected = BTreeMap::from([(base, base + 4 * PAGE)]); + early_remove(&mut protected, base + PAGE, base + 3 * PAGE); + assert_eq!(protected.into_iter().collect::<Vec<_>>(), [(base, base + PAGE), (base + 3 * PAGE, base + 4 * PAGE)]); + } + + #[test] + fn working_set_check_rejects_resident_read_only_pages_without_touching_cold_pages() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE, PAGE_READONLY}; + unsafe { + let base = VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert_ne!(base, 0); + assert!(!VirtualAlloc(base as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert!(!VirtualAlloc((base + PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READONLY).is_null()); + assert!(!VirtualAlloc((base + 2 * PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + std::ptr::write_volatile(base as *mut u8, 1); + assert_eq!(std::ptr::read_volatile((base + PAGE) as *const u8), 0); + assert!(resident_pages_writable(base, base + PAGE)); + assert!(!resident_pages_writable(base + PAGE, base + 2 * PAGE)); + assert!(resident_pages_writable(base + 2 * PAGE, base + 3 * PAGE)); + + let mut cold: windows_sys::Win32::System::ProcessStatus::PSAPI_WORKING_SET_EX_INFORMATION = std::mem::zeroed(); + cold.VirtualAddress = (base + 2 * PAGE) as *mut c_void; + assert_ne!( + windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + &mut cold as *mut _ as *mut c_void, + std::mem::size_of_val(&cold) as u32, + ), + 0 + ); + assert_eq!(cold.VirtualAttributes.Flags & 1, 0, "the metadata query paged memory in"); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + #[test] fn memory_counts_committed_pages_and_separates_devices_and_retired_pools() { let holes = [0xFFFE, 0xFFF0].into_iter(); // one committed page, then four @@ -2382,7 +2617,10 @@ mod tests { }; // Mirrors `place_buffer`: map both tiles probing real OS page commitment. - s.ensure_mapped(base, 2 * TILE, |t| query_tile_holes(t)); + s.ensure_mapped(base, 2 * TILE, |t| { + let holes = query_tile_holes(t); + (holes, !holes) + }); assert_eq!(s.mapped[&base].holes, 0xFF0F, "uncommitted prefix and suffix pages must stay holes"); assert_eq!(s.mapped[&(base + TILE)].holes, 0xFFFF, "fully reserved tile must have all 16 holes set"); @@ -2482,6 +2720,8 @@ mod tests { let tile = s.mapped[&base].pool; let v = s.value; assert!(v > 0, "a new tile is mapped"); + mark_protection(&mut s.mapped, base + PAGE, PAGE, false); + assert_eq!(s.mapped[&base].not_rw, 1 << 1); // decommitted: parked, still mapped, nothing sent to the GPU s.decommit_range(base, TILE); @@ -2498,10 +2738,19 @@ mod tests { s.commit_range(base, TILE); assert_eq!(s.mapped[&base].pool, tile); assert_eq!(s.mapped[&base].holes, 0); + assert_eq!(s.mapped[&base].not_rw, 0, "recommitted pages use their commit protection"); assert!(s.parked.is_empty()); assert_eq!(s.to_zero, vec![(base, TILE)]); assert_eq!(s.value, v, "no tile mapping changed"); assert!(mapped_gen() > gen, "readers of `mapped` see it changed"); + mark_protection(&mut s.mapped, base + 2 * PAGE, PAGE, false); + s.decommit_range(base + 2 * PAGE, PAGE); + s.commit_range(base + 2 * PAGE, PAGE); + assert_eq!(s.mapped[&base].not_rw, 0, "a partially recommitted page is writable again"); + s.decommit_range(base + 3 * PAGE, PAGE); + s.commit_range_with_protection(base + 3 * PAGE, PAGE, false); + assert_eq!(s.mapped[&base].not_rw, 1 << 3, "commit and protection publish as one record update"); + s.commit_range(base + 3 * PAGE, PAGE); // decommitted and flushed (as before a submit): unmapped and free once unmap fence completes s.decommit_range(base, TILE); diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 7a416ddfe5..3c48e6fedf 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -819,6 +819,9 @@ fn writable(p: usize, n: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, n)) { return true; } + if crate::hle::d3d12x::sparse::known_writable(p, n) { + return true; + } let mut at = p; while at < end { let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 4144a1144e..f752450bad 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -244,13 +244,31 @@ const MEM_64K_PAGES: u32 = 0x2040_0000; /// Commit `[a, a + n)` of a sparse window (the title's reservations there) and give it video /// memory (`d3d12x::sparse`). unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void { - let q = mem::VirtualAlloc(a as *const c_void, n, mem::MEM_COMMIT, sanitize_protect(p)); + let protection = sanitize_protect(p); + let q = mem::VirtualAlloc(a as *const c_void, n, mem::MEM_COMMIT, protection); if !q.is_null() { - crate::hle::d3d12x::sparse::committed(q as usize, n); + crate::hle::d3d12x::sparse::committed_with_protection(q as usize, n, read_write(protection)); } q } +/// A writable protection without PAGE_GUARD. +fn read_write(protection: u32) -> bool { + matches!(protection & 0xFF, 0x04 | 0x08 | 0x40 | 0x80) && protection & 0x100 == 0 +} + +fn own_process(process: HANDLE) -> bool { + if process == unsafe { thr::GetCurrentProcess() } { + return true; + } + let id = unsafe { thr::GetProcessId(process) }; + id != 0 && id == unsafe { thr::GetCurrentProcessId() } +} + +unsafe fn note_protection(addr: *const c_void, size: usize, protection: u32) { + crate::hle::d3d12x::sparse::protection_changed(addr as usize, size, read_write(protection)); +} + pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void { if let Some(q) = placeholders::alloc(addr, size, t, sanitize_protect(p)) { trace_mem("VirtualAlloc (placeholder)", addr as usize, size, t as u64, p, q as usize); @@ -477,7 +495,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 } pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, size: usize, t: u32) -> BOOL { - if proc_ == thr::GetCurrentProcess() { + if own_process(proc_) { let a = addr as usize; if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a)) || (t & 0x8000 != 0 && in_graphics_reservation(a)) @@ -489,15 +507,37 @@ pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, si } pub unsafe extern "system" fn VirtualAllocEx(proc_: HANDLE, addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void { + if own_process(proc_) { + return VirtualAlloc(addr, size, t, p); + } mem::VirtualAllocEx(proc_, addr, size, sanitize_alloc_type(t), sanitize_protect(p)) } pub unsafe extern "system" fn VirtualProtect(addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL { - mem::VirtualProtect(addr, size, sanitize_protect(p), old) + let protection = sanitize_protect(p); + let writable = read_write(protection); + if !writable { + note_protection(addr, size, protection); + } + let ok = mem::VirtualProtect(addr, size, protection, old); + if ok != 0 && writable { + note_protection(addr, size, protection); + } + ok } pub unsafe extern "system" fn VirtualProtectEx(proc_: HANDLE, addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL { - mem::VirtualProtectEx(proc_, addr, size, sanitize_protect(p), old) + let protection = sanitize_protect(p); + let own = own_process(proc_); + let writable = read_write(protection); + if own && !writable { + note_protection(addr, size, protection); + } + let ok = mem::VirtualProtectEx(proc_, addr, size, protection, old); + if ok != 0 && own && writable { + note_protection(addr, size, protection); + } + ok } /// XALLOC_ATTRIBUTES bit fields. From 37271a3c0e27cc520a22939d700c421724eebc12 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:36:01 -0800 Subject: [PATCH 147/265] D3D12.X: abort sparse allocator reuse after wait failure Sparse upload and readback paths continued after a five-second fence timeout, resetting command allocators which the GPU could still be using and publishing readback staging bytes whose copy had not completed. Reset and Close failures were ignored as well.\n\nMake upload-slot acquisition fail closed, retry exact dirty or zero work, and abort readback before allocator reuse or CPU publication whenever its wait or command-list transition fails. The healthy asynchronous path is unchanged.\n\nThe Windows GNU library/test cross-check passed with the existing warnings. Windows MSVC runtime, GPU execution, and smoke tests were not available here.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 82 ++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 26 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index d8949ccd2a..41cf984f18 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -945,18 +945,24 @@ impl State { /// Acquire the next upload command slot, waiting only if that slot's previous submission is /// still executing on the GPU, then reset its allocator and list. - unsafe fn begin_slot(&mut self) -> usize { + unsafe fn begin_slot(&mut self) -> Option<usize> { + self.begin_slot_with_timeout(5000) + } + + unsafe fn begin_slot_with_timeout(&mut self, timeout_ms: u32) -> Option<usize> { let idx = self.next_slot; self.next_slot = (self.next_slot + 1) % self.slots.len(); let fv = self.slots[idx].fence_val; if fv > 0 && self.fence.GetCompletedValue() < fv { - self.wait_for(fv); + if !self.wait_for_ms(fv, timeout_ms) { + return None; + } self.reclaim_ring(); } let slot = &self.slots[idx]; - let _ = slot.alloc.Reset(); - let _ = slot.list.Reset(&slot.alloc, None); - idx + slot.alloc.Reset().ok()?; + slot.list.Reset(&slot.alloc, None).ok()?; + Some(idx) } /// Close and submit upload slot `idx` asynchronously (NO CPU wait — callers order GPU work @@ -1137,19 +1143,21 @@ impl State { let mut pending: Vec<(usize, usize, usize)> = Vec::new(); // (va, rb_off, chunk) let mut used = 0usize; let mut open = false; - let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| { + let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| -> bool { if *open { *open = false; - if s.rb_list.Close().is_ok() { - if let Ok(l) = s.rb_list.cast::<ID3D12CommandList>() { - super::title_textures::own_work(|| { - super::real::native_queue_execute(&s.queue, &l); - }); - } - } + let Ok(()) = s.rb_list.Close() else { return false }; + let Ok(l) = s.rb_list.cast::<ID3D12CommandList>() else { return false }; + super::title_textures::own_work(|| { + super::real::native_queue_execute(&s.queue, &l); + }); s.signal(); s.rb_last_fence = s.value; - s.wait_for(s.value); + if !s.wait_for(s.value) { + pending.clear(); + *used = 0; + return false; + } s.reclaim_ring(); } for &(dst, off, len) in pending.iter() { @@ -1172,6 +1180,7 @@ impl State { } pending.clear(); *used = 0; + true }; for &(a, n) in ranges { if n == 0 { @@ -1189,14 +1198,16 @@ impl State { continue; } if used == READBACK_STAGING { - flush_and_copy(self, &mut open, &mut pending, &mut used, p); + if !flush_and_copy(self, &mut open, &mut pending, &mut used, p) { + return; + } } let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); if !open { - self.wait_for(self.rb_last_fence); - let _ = self.rb_alloc.Reset(); - let _ = self.rb_list.Reset(&self.rb_alloc, None); + if !self.wait_for(self.rb_last_fence) || self.rb_alloc.Reset().is_err() || self.rb_list.Reset(&self.rb_alloc, None).is_err() { + return; + } open = true; } self.rb_list.CopyBufferRegion(&rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); @@ -1206,17 +1217,20 @@ impl State { } } if open { - flush_and_copy(self, &mut open, &mut pending, &mut used, p); + let _ = flush_and_copy(self, &mut open, &mut pending, &mut used, p); } } /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` /// (zero staging ring bytes consumed, zero CPU stall). - unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) { - if runs.is_empty() || !self.ensure_zero_buf() { - return; + unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) -> bool { + if runs.is_empty() { + return true; + } + if !self.ensure_zero_buf() { + return false; } - let slot_idx = self.begin_slot(); + let Some(slot_idx) = self.begin_slot() else { return false }; let mut last_wi: Option<usize> = None; let zero_buf = self.zero_buf.as_ref().unwrap(); let list = &self.slots[slot_idx].list; @@ -1242,6 +1256,7 @@ impl State { } } self.submit_slot(slot_idx); + true } /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via @@ -1314,7 +1329,10 @@ impl State { let slot_idx = match open_slot { Some(idx) => idx, None => { - let idx = self.begin_slot(); + let Some(idx) = self.begin_slot() else { + self.retry_dirty_from(runs, run_index, done); + return false; + }; open_slot = Some(idx); idx } @@ -1432,7 +1450,10 @@ pub unsafe fn readback_now(va: usize, len: usize) { for &(a, n) in &zeroed { s.clear_sent_range(a, n); } - s.upload_zeros(&zeroed); + if !s.upload_zeros(&zeroed) { + s.to_zero.extend(zeroed); + return; + } } // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); @@ -1814,7 +1835,9 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. if !zero_runs.is_empty() { - s.upload_zeros(&zero_runs); + if !s.upload_zeros(&zero_runs) { + s.to_zero.extend(zero_runs.iter().copied()); + } } if !dirty_runs.is_empty() { let _ = s.upload_dirty(&dirty_runs); @@ -2715,6 +2738,13 @@ mod tests { assert_ne!(after[2], before[2]); assert_eq!(after[3], before[3]); + let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.Close().unwrap(); + s.slots.push(UploadSlot { alloc, list, fence_val: s.value + 1 }); + s.next_slot = 0; + assert_eq!(s.begin_slot_with_timeout(20), None, "a timed-out slot must not reset its in-flight allocator"); + drop(s); assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); } From 651ec166aa9dd60255ed63aacebb1590023ff4ba Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:39:35 -0800 Subject: [PATCH 148/265] D3D12.X: enqueue texture page waits outside global state Texture page preparation called the native title-queue Wait while holding the device-wide PAGES registry. A driver call on one queue therefore serialized streaming, bookkeeping, and unrelated queues behind a global state lock.\n\nGive each title queue a lifecycle-scoped preparation gate, reserve its monotonic mapping fence value under PAGES, and enqueue the native wait after releasing PAGES. The gate prevents same-queue submissions from overtaking a reserved wait while different queues remain independent; exact queue retirement removes both waited state and its gate.\n\nThe Windows GNU library/test cross-check passed with the existing warnings. Windows MSVC runtime, GPU, and smoke tests were not available here.\n\nAssisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/vram.rs | 48 +++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index ccd6d674f7..5b203b202b 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -23,9 +23,9 @@ //! driver does not make reserved: D32S8, MSAA): heaps of the placement's size, shared by //! placements inside them, let go 2 s after their last resource (256 MiB ones: 2.8 GB of D32S8). -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::ffi::c_void; -use std::sync::Mutex; +use std::sync::{Arc, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -622,6 +622,19 @@ unsafe impl Send for Pages {} /// device raw pointer → its pages (None inside: tiled tier < 2 on this device) static PAGES: Mutex<std::collections::BTreeMap<usize, Option<Pages>>> = Mutex::new(std::collections::BTreeMap::new()); +fn wait_gates() -> &'static Mutex<HashMap<usize, Arc<Mutex<()>>>> { + static GATES: OnceLock<Mutex<HashMap<usize, Arc<Mutex<()>>>>> = OnceLock::new(); + GATES.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn reserve_page_wait(waited: &mut HashMap<usize, u64>, queue: usize, value: u64) -> bool { + if value == 0 || waited.get(&queue).copied().unwrap_or(0) >= value { + return false; + } + waited.insert(queue, value); + true +} + impl Pages { unsafe fn new(dev: &ID3D12Device) -> Option<Pages> { let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); @@ -1201,12 +1214,13 @@ pub(super) fn forget_queue(id: super::present::QueueId) { pages.waited.remove(&queue); } } + let wait_gate = wait_gates().lock().unwrap().remove(&queue); let states: Vec<_> = RETIRE.lock().unwrap().as_ref().into_iter().flat_map(|devices| devices.values().cloned()).collect(); let gone: Vec<_> = states .iter() .filter_map(|state| state.lock().unwrap().forget_queue(queue)) .collect(); - drop(gone); + drop((gone, wait_gate)); } /// Collect all known live command queues belonging to `dev_key` (deduplicated by raw ptr). @@ -1270,6 +1284,9 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla /// per second per device) retire completely empty 64 MiB VRAM pool heaps and idle arenas behind /// per-queue GPU fence signals across all live queues on the device. pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { + let queue_key = queue.as_raw() as usize; + let wait_gate = wait_gates().lock().unwrap().entry(queue_key).or_default().clone(); + let _queue_serial = wait_gate.lock().unwrap(); let mut dev: Option<ID3D12Device> = None; if queue.GetDevice(&mut dev).is_err() { return; @@ -1280,14 +1297,13 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let mut newly_reclaimed = Vec::new(); let mut do_reclaim = false; let mut unmap_mark: Option<(ID3D12Fence, u64)> = None; + let mut wait = None; { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { - let key = queue.as_raw() as usize; - if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { - let _ = super::real::native_queue_wait(queue, &pages.fence, pages.value); - super::list_x::note_internal_wait(key, "texture page mappings", &pages.fence, pages.value); - pages.waited.insert(key, pages.value); + let value = pages.value; + if reserve_page_wait(&mut pages.waited, queue_key, value) { + wait = Some((pages.fence.clone(), value)); } if now.duration_since(pages.last_reclaim) >= std::time::Duration::from_secs(1) { pages.last_reclaim = now; @@ -1299,6 +1315,10 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { } } } + if let Some((fence, value)) = wait { + let _ = super::real::native_queue_wait(queue, &fence, value); + super::list_x::note_internal_wait(queue_key, "texture page mappings", &fence, value); + } if do_reclaim { newly_reclaimed.extend(ARENAS.lock().unwrap().sweep_dropped_for(dev_key, now)); } @@ -1517,6 +1537,18 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st #[cfg(test)] mod tests { use super::*; + + #[test] + fn title_queue_mapping_wait_reservation_is_monotonic_and_per_queue() { + let mut waited = HashMap::new(); + assert!(!reserve_page_wait(&mut waited, 1, 0)); + assert!(reserve_page_wait(&mut waited, 1, 4)); + assert!(!reserve_page_wait(&mut waited, 1, 4)); + assert!(!reserve_page_wait(&mut waited, 1, 3)); + assert!(reserve_page_wait(&mut waited, 2, 3)); + assert!(reserve_page_wait(&mut waited, 1, 5)); + assert_eq!(waited, HashMap::from([(1, 5), (2, 3)])); + } use std::time::{Duration, Instant}; const MIB: usize = 1 << 20; From e5d2e5ee8743074a3a4dbc09455d325d502d583a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:41:33 -0800 Subject: [PATCH 149/265] D3D12.X: separate compute blobs by node mask Driver cached pipeline blobs can be node-specific on linked-adapter devices. Include NodeMask in the in-memory compute blob identity so a compile for one node cannot be offered to another. Checked with the Windows GNU cross-target cargo check; Windows runtime and GPU tests were not available. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 62deef1117..3d227a7099 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4867,7 +4867,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); // A program built again gets the driver's own result of its first build: a retail title // made 14 big compute pipelines twice while loading, 13 - 30 s each the second time. - let key = compute_blob_key(dxil, rs as usize, copy.Flags.0); + let key = compute_blob_key_for(dxil, rs as usize, copy.Flags.0, copy.NodeMask); let mut cached = compute_blob(key); // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) let disk = driver_cache::path_for_root(dxil, copy.Flags.0, mode == ComputeBuild::Chain, samplers); @@ -5600,9 +5600,14 @@ const COMPUTE_BLOBS_MAX: usize = 512 << 20; const COMPUTE_BLOB_MIN_DXIL: usize = 16 << 10; fn compute_blob_key(dxil: &[u8], rs: usize, flags: i32) -> (u64, usize, i32) { + compute_blob_key_for(dxil, rs, flags, 0) +} + +fn compute_blob_key_for(dxil: &[u8], rs: usize, flags: i32, node_mask: u32) -> (u64, usize, i32) { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); dxil.hash(&mut h); + node_mask.hash(&mut h); (h.finish(), rs, flags) } @@ -5669,6 +5674,8 @@ mod compute_blob_tests { let dxil = vec![7u8; 1000]; let key = super::compute_blob_key(&dxil, 0x1000, 0); assert_eq!(key, super::compute_blob_key(&dxil.clone(), 0x1000, 0)); + assert_eq!(key, super::compute_blob_key_for(&dxil, 0x1000, 0, 0)); + assert_ne!(key, super::compute_blob_key_for(&dxil, 0x1000, 0, 2)); assert_ne!(key, super::compute_blob_key(&dxil, 0x2000, 0)); assert_ne!(key, super::compute_blob_key(&dxil, 0x1000, 1)); let mut other = dxil.clone(); From 5dc2833e2aa0aab5f0c42f45d02622556badd46f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:43:22 -0800 Subject: [PATCH 150/265] D3D12.X: isolate ABI roots by device D3D12 root signatures belong to the device that created them. Cache both plain and static-sampler ABI signatures by device so secondary devices cannot receive a foreign COM object. A synthetic cache test covers identical sampler layouts on distinct devices. Checked with the Windows GNU cross-target cargo check; native Windows GPU tests were unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 62 +++++++++++++++++++------------ 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3d227a7099..3ba993b013 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -177,15 +177,19 @@ static FAILED_PSO: AtomicU64 = AtomicU64::new(0); static FALLBACK_RS: AtomicU64 = AtomicU64::new(0); static TRANSLATED_PSO: AtomicU64 = AtomicU64::new(0); static TRANSLATE_ERRORS: Mutex<Vec<String>> = Mutex::new(Vec::new()); -/// XCL shader ABI root signature on the backend device (raw, kept for the process lifetime) +/// XCL shader ABI root signature on the primary backend device (raw, kept for the process lifetime) static ABI_RS: AtomicUsize = AtomicUsize::new(0); +static ABI_RS_DEV: AtomicUsize = AtomicUsize::new(0); +static ABI_RS_BY_DEV: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None); /// XCL's shader ABI root signature, once a translated pipeline created it. pub fn abi_rs_cached() -> Option<*mut c_void> { - match ABI_RS.load(Ordering::Acquire) { - 0 => None, - p => Some(p as *mut c_void), + let dev = device_raw() as usize; + let primary = ABI_RS.load(Ordering::Acquire); + if primary != 0 && (dev == 0 || ABI_RS_DEV.load(Ordering::Acquire) == dev) { + return Some(primary as *mut c_void); } + ABI_RS_BY_DEV.lock().unwrap().as_ref()?.get(&dev).map(|&p| p as *mut c_void) } thread_local! { @@ -198,10 +202,7 @@ thread_local! { /// Root signature of the pipelines built from translated console shaders (bind it, then the /// XCL ABI root UAVs io / res / mem, to draw with them). pub fn abi_root_signature() -> Option<ID3D12RootSignature> { - let raw = ABI_RS.load(Ordering::Acquire) as *mut c_void; - if raw.is_null() { - return None; - } + let raw = abi_rs_cached()?; unsafe { ID3D12RootSignature::from_raw_borrowed(&raw).cloned() } } /// Each UMA window as one D3D12 buffer (placed in a heap opened over the process memory): @@ -4209,15 +4210,15 @@ pub fn pso_root_signature(pso: usize) -> Option<usize> { PSO_RS.lock().unwrap().as_ref()?.get(&pso).copied() } -/// ABI root signatures with static samplers, by sampler set (owned here, never released). -static ABI_RS_SAMPLERS: Mutex<Option<HashMap<Vec<u32>, usize>>> = Mutex::new(None); +/// ABI root signatures with static samplers, by device and sampler set (owned here, never released). +static ABI_RS_SAMPLERS: Mutex<Option<HashMap<(usize, Vec<u32>), usize>>> = Mutex::new(None); /// The XCL ABI root signature with a pipeline's static samplers (the plain one without). unsafe fn abi_rs_for(this: *mut c_void, samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> Option<*mut c_void> { if samplers.is_empty() { return abi_rs_raw(this); } - let key: Vec<u32> = samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect(); + let key = (this as usize, samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect::<Vec<_>>()); let mut g = ABI_RS_SAMPLERS.lock().unwrap(); let map = g.get_or_insert_with(HashMap::new); if let Some(&rs) = map.get(&key) { @@ -4237,23 +4238,28 @@ unsafe fn abi_rs_for(this: *mut c_void, samplers: &[crate::gpu::recomp::pso::Sta } } -/// XCL ABI root signature, created once on the backend device. +/// XCL ABI root signature, created once per backend device. unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { + let dev_raw = this as usize; let cur = ABI_RS.load(Ordering::Acquire); - if cur != 0 { + if cur != 0 && ABI_RS_DEV.load(Ordering::Acquire) == dev_raw { return Some(cur as *mut c_void); } + let mut roots = ABI_RS_BY_DEV.lock().unwrap(); + if let Some(&cached) = roots.as_ref().and_then(|m| m.get(&dev_raw)) { + return Some(cached as *mut c_void); + } let dev = ID3D12Device::from_raw_borrowed(&this)?; match crate::gpu::recomp::pso::abi_root_signature(dev, true) { Ok(rs) => { let raw = rs.into_raw(); - match ABI_RS.compare_exchange(0, raw as usize, Ordering::AcqRel, Ordering::Acquire) { - Ok(_) => Some(raw), - Err(other) => { - drop(ID3D12RootSignature::from_raw(raw)); - Some(other as *mut c_void) - } + if ABI_RS.load(Ordering::Acquire) == 0 { + ABI_RS_DEV.store(dev_raw, Ordering::Release); + ABI_RS.store(raw as usize, Ordering::Release); + } else { + roots.get_or_insert_with(HashMap::new).insert(dev_raw, raw as usize); } + Some(raw) } Err(e) => { note_translation_error(format!("XCL ABI root signature: {e}")); @@ -10111,17 +10117,18 @@ mod mesh_stream_tests { // Unique synthetic sampler key so we never touch global ABI_RS or real sampler caches. let sampler: crate::gpu::recomp::pso::StaticSampler = ([0x55AA_1968, 0xCAFE_1968, 0xBEEF_1968, 0x0001_1968], true); - let key: Vec<u32> = sampler.0.iter().copied().chain([1u32]).collect(); + let key = (this as usize, sampler.0.iter().copied().chain([1u32]).collect::<Vec<_>>()); + let other_key = (0x0D15_71C7usize, key.1.clone()); struct Cleanup { ext: usize, - key: Vec<u32>, + keys: Vec<(usize, Vec<u32>)>, } impl Drop for Cleanup { fn drop(&mut self) { CLASSES.lock().unwrap().retain(|c| c.ext != self.ext); if let Some(m) = ABI_RS_SAMPLERS.lock().unwrap().as_mut() { - m.remove(&self.key); + for key in &self.keys { m.remove(key); } } } } @@ -10133,8 +10140,15 @@ mod mesh_stream_tests { public: iface.methods.len(), scanned: iface.methods.len(), }); - ABI_RS_SAMPLERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(key.clone(), 0x1234_5678); - let _cleanup = Cleanup { ext: ext_vtbl, key }; + { + let mut roots = ABI_RS_SAMPLERS.lock().unwrap(); + let roots = roots.get_or_insert_with(HashMap::new); + roots.insert(key.clone(), 0x1234_5678); + roots.insert(other_key.clone(), 0x8765_4321); + } + assert_eq!(unsafe { abi_rs_for(this, &[sampler]) }, Some(0x1234_5678 as *mut c_void)); + assert_eq!(unsafe { abi_rs_for(other_key.0 as *mut c_void, &[sampler]) }, Some(0x8765_4321 as *mut c_void)); + let _cleanup = Cleanup { ext: ext_vtbl, keys: vec![key, other_key] }; let make_tp = || crate::gpu::recomp::pso::TwoPass { cs: vec![0; 16], From 10072ce35d2e6c6dcc045ef41eaba0986e8b3302 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:44:03 -0800 Subject: [PATCH 151/265] D3D12.X: share split compute root signatures A fresh dispatch-chain root signature made the in-memory compute blob key unique for every split program, preventing programs with common pieces from sharing their driver-compiled blobs. Cache signatures by device and exact static-sampler layout. PR #2723 measured shared-piece reuse on Windows; the integrated stage passed the Windows GNU cross-target cargo check, but native GPU execution was unavailable here. Assisted-by: Codex (GPT-5.6-sol) --- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 6c5235c9ec..6708d3203a 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -105,13 +105,34 @@ impl Chain { } static CHAINS: LazyLock<Mutex<HashMap<usize, Arc<Chain>>>> = LazyLock::new(Default::default); +/// Shared for the process lifetime so chains with a common piece also share its driver blob. +static SIGNATURES: LazyLock<Mutex<HashMap<(usize, Vec<u32>), ID3D12RootSignature>>> = LazyLock::new(Default::default); + +fn sampler_key(samplers: &[pso::StaticSampler]) -> Vec<u32> { + samplers.iter().flat_map(|(words, comparison)| words.iter().copied().chain([*comparison as u32])).collect() +} + +unsafe fn signature_for(dev: &ID3D12Device, samplers: &[pso::StaticSampler]) -> Option<ID3D12RootSignature> { + let key = (dev.as_raw() as usize, sampler_key(samplers)); + if let Some(signature) = SIGNATURES.lock().unwrap().get(&key).cloned() { + return Some(signature); + } + let created = match pso::dispatch_chain_root_signature(dev, samplers) { + Ok(signature) => signature, + Err(e) => { + note_translation_error(format!("dispatch-chain root signature: {e}")); + return None; + } + }; + Some(SIGNATURES.lock().unwrap().entry(key).or_insert(created).clone()) +} pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, iid: *const GUID, result: *mut *mut c_void, record: u64, whole: &[u8], samplers: &[pso::StaticSampler], plan: Arc<DispatchChain>) -> Option<usize> { if result.is_null() || iid.is_null() || plan.pieces.len() < 2 { return None; } let dev = ID3D12Device::from_raw_borrowed(&this)?; - let signature = pso::dispatch_chain_root_signature(dev, samplers).ok()?; + let signature = signature_for(dev, samplers)?; let rs = signature.as_raw() as usize; let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, samplers: samplers.to_vec(), flags: desc.Flags, node: desc.NodeMask, record }); @@ -303,6 +324,15 @@ mod tests { const MB: u64 = 1 << 20; + #[test] + fn signature_identity_includes_sampler_words_order_and_comparison() { + let a = ([1, 2, 3, 4], false); + let b = ([5, 6, 7, 8], true); + assert_eq!(sampler_key(&[a, b]), sampler_key(&[a, b])); + assert_ne!(sampler_key(&[a, b]), sampler_key(&[b, a])); + assert_ne!(sampler_key(&[a]), sampler_key(&[([1, 2, 3, 4], true)])); + } + #[test] fn remapped_grid_scales_only_its_dimension_and_refuses_overflow() { assert_eq!(remapped_grid([3, 5, 7], Some((4, 1))), Some([3, 20, 7])); From d8d0dc657e957dc0484570201822fbc2b45793a8 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:43:28 -0800 Subject: [PATCH 152/265] Recompiler: flatten direct-DXIL compute heap reads Heap-window reads in the direct DXIL compute path placed a branch and PHI set around every access. Add an opt-in one-path form whose cache identity is shared by runtime and offline precompile, while the HLSL path strips the flag and stays byte-identical. Graphics stages remain guarded because their performance has not been established across vendors. Adapted from #2427 by Kalmarv and Claude Code (Claude Opus 5.5). Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/core_tests.rs | 11 ++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 24 +++++++++++++++- crates/xcl/src/gpu/dxil/lower.rs | 2 ++ crates/xcl/src/gpu/dxil/lower_mem.rs | 18 ++++++++++++ crates/xcl/src/gpu/recomp/mod.rs | 7 ++++- crates/xcl/src/gpu/recomp/pso.rs | 16 +++++++++-- crates/xcl/src/gpu/recomp/tests.rs | 8 ++++++ crates/xcl/src/shaders.rs | 40 +++++++++++++++++++++------ 8 files changed, 114 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 7492f54b9c..ae8b956d49 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -659,6 +659,17 @@ fn raw_loads_in_root_windows_are_branchless() { let heap_dxil = translate(&loads, KernelOptions { wave64: false, split: false, mem_windows: 4 | crate::gpu::recomp::HEAP_WINDOWS, sampler_base: 0 }) .expect("heap windows translate"); super::validate::validate(&heap_dxil).expect("heap windows validate"); + let flat_dxil = translate(&loads, KernelOptions { + wave64: false, + split: false, + mem_windows: 4 | crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT, + sampler_base: 0, + }).expect("flat heap windows translate"); + super::validate::validate(&flat_dxil).expect("flat heap windows validate"); + if let (Ok(heap), Ok(flat)) = (super::validate::disassemble(&heap_dxil), super::validate::disassemble(&flat_dxil)) { + let branches = |s: &str| s.lines().filter(|line| line.trim_start().starts_with("br i1 ")).count(); + assert!(branches(&flat) < branches(&heap), "flat heap reads must remove guarded-read branches: guarded {}, flat {}", branches(&heap), branches(&flat)); + } let writes = prog(&[ ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 2), ("SADDR", 0x7D), ("OFFSET", 0)], None), diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index f05561086b..b03c024799 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -126,6 +126,27 @@ pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Res translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0) } +/// Whether `entry` uses the measured, one-path heap-window read form. Graphics, mesh and +/// geometry stages retain the guarded form until they have stage-specific measurements. +fn reads_heap_flat(entry: &Entry, heap: bool, mem_windows: u32) -> bool { + heap && matches!(entry, Entry::Kernel | Entry::Compute(_)) && mem_windows & crate::gpu::recomp::HEAP_FLAT != 0 +} + +#[cfg(test)] +#[test] +fn only_compute_programs_read_heap_windows_flat() { + use crate::gpu::recomp::{GsInterface, MsInterface, HEAP_FLAT, HEAP_WINDOWS}; + let flat = 4 | HEAP_WINDOWS | HEAP_FLAT; + assert!(reads_heap_flat(&Entry::Kernel, true, flat)); + assert!(reads_heap_flat(&Entry::Compute(CsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Mesh(MsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Geometry(GsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Vertex(VsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Pixel(PsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), true, 4 | HEAP_WINDOWS)); + assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), false, flat)); +} + /// The entry ABI. #[derive(Clone)] pub enum Entry { @@ -184,7 +205,7 @@ fn translate_entry( fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec<RawUav>, Option<bool>) { let heap = mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0; let max = if heap { crate::gpu::uma::MAX_HEAP_WINDOWS as u32 } else { crate::gpu::uma::MAX_WINDOWS as u32 }; - let n = (mem_windows & !crate::gpu::recomp::HEAP_WINDOWS).clamp(1, max); + let n = (mem_windows & !(crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT)).clamp(1, max); if heap && n > 1 { let z = s.m.i32c(0); return (vec![RawUav { handle: z, binding: None }; n as usize], Some(coherent)); @@ -523,6 +544,7 @@ impl Lw { half: z, mems, heap_mem, + heap_flat: reads_heap_flat(entry, heap_mem.is_some(), o.mem_windows), res, fmt_table: None, fmt_desc_cache: HashMap::new(), diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 31d70ab897..14754f7aa7 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -187,6 +187,8 @@ pub struct Lw { /// the windows come from the descriptor heap (`lower_window`; `mems` only counts them): /// Some(globallycoherent) pub heap_mem: Option<bool>, + /// Heap windows read without a branch (`recomp::HEAP_FLAT`; compute programs only). + pub heap_flat: bool, pub res: Option<RawUav>, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option<Value>, diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index cc7cd0116a..c0ee9b6398 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -407,6 +407,24 @@ impl Lw { n: usize, f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec<Value>, ) -> Vec<Value> { + if let (Some(coherent), true) = (self.heap_mem, self.heap_flat) { + let z = self.c(0); + if guard.is_some_and(|g| self.s.m.const_u64(g) == Some(0)) { + return vec![z; n]; + } + let w = self.rd(super::lower::VAR_WIN); + let inside = self.cmpc(Pred::ULt, w, self.mems.len() as u32); + let ok = match guard { + Some(g) if self.s.m.const_u64(g) != Some(1) => self.and(g, inside), + _ => inside, + }; + let w = self.sel(ok, w, z); + let i = self.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); + let m = self.s.heap_raw_buffer_uav(i, coherent); + let vals = f(self, m); + debug_assert_eq!(vals.len(), n); + return vals.into_iter().map(|v| self.sel(ok, v, z)).collect(); + } let i32 = self.s.m.i32(); let tys = vec![i32; n]; self.with_mem_many_tys(guard, &tys, f) diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index b888923bd0..a8ffdc7a10 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -90,6 +90,11 @@ pub const MEM_NULL_STORE: u32 = MEM_NULL_LOAD + 1; /// `Options::heap_windows`. `translate` takes it out of `mem_windows`. pub const HEAP_WINDOWS: u32 = 0x100; +/// Flag in a memory-windows count next to `HEAP_WINDOWS` (`pso::mem_windows`, the caches' keys): +/// the direct DXIL translator reads the heap windows of compute stages without a branch +/// (`Lw::with_mem_i32s`). The HLSL path ignores it. +pub const HEAP_FLAT: u32 = 0x200; + pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool { windows <= crate::gpu::uma::MAX_WINDOWS || (heap && windows.is_power_of_two() && windows <= crate::gpu::uma::MAX_HEAP_WINDOWS) @@ -1521,7 +1526,7 @@ fn translate_inner(code: &[u8], opt: &Options) -> Result<Translation, String> { let program = code; let normalized; let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { - normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() }; + normalized = Options { mem_windows: opt.mem_windows & !(HEAP_WINDOWS | HEAP_FLAT), heap_windows: true, ..opt.clone() }; &normalized } else { opt diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 8084d5cdb4..9ca022da4c 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -122,9 +122,14 @@ pub fn fspx(blob: &[u8]) -> Option<Fspx<'_>> { /// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when /// shaders take them from the descriptor heap (`heap_windows`). pub fn mem_windows() -> u32 { - let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); + windows_for(crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32)) +} + +/// `n` windows as this run's programs take them (`mem_windows`; also the keys +/// `xcl shaders --precompile` makes, so they are the ones the runtime looks up). +pub fn windows_for(n: u32) -> u32 { if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) { - n | super::HEAP_WINDOWS + n | super::HEAP_WINDOWS | if heap_flat() { super::HEAP_FLAT } else { 0 } } else { n } @@ -160,6 +165,13 @@ pub fn heap_windows() -> bool { *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() } +/// `XCL_HEAP_FLAT=1` (with heap windows): the direct DXIL translator reads a compute stage's heap +/// windows without a branch per access (`HEAP_FLAT`). Opt-in while it is measured. +pub fn heap_flat() -> bool { + static ENV: OnceLock<bool> = OnceLock::new(); + *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "1")) +} + /// A static sampler of a translated program: (S#, comparison) – see `Translation`. pub type StaticSampler = ([u32; 4], bool); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 8c264943f0..79a95df537 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4069,6 +4069,14 @@ fn gpu_memory_windows_from_the_heap() { memory_windows_above_4_gib(true); } +#[test] +fn heap_flat_cache_flag_does_not_change_hlsl_translation() { + let p = prog(&[("S_ENDPGM", "ENC_SOPP", &[], None)]); + let guarded = translate(&p, &Options { mem_windows: 4 | super::HEAP_WINDOWS, ..Default::default() }).unwrap(); + let flat = translate(&p, &Options { mem_windows: 4 | super::HEAP_WINDOWS | super::HEAP_FLAT, ..Default::default() }).unwrap(); + assert_eq!(flat.hlsl, guarded.hlsl, "HEAP_FLAT distinguishes direct-DXIL cache entries but is ignored by HLSL"); +} + fn memory_windows_above_4_gib(heap: bool) { if !gpu_ready() { return; diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 5cd63f8780..02db0dee79 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -914,12 +914,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { return 2; } }; - // the runtime's memory windows: from the descriptor heap with `XCL_HEAP_WINDOWS=1` - // (`pso::mem_windows`), as `--precompile` - let runtime_windows = || { - let windows = opts.windows; - if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows } - }; + let runtime_windows = || runtime_windows(opts.windows); let top = opts.top; let json = opts.json; let compile = opts.compile; @@ -991,6 +986,11 @@ pub fn run(path: &Path, args: &[String]) -> i32 { print(path, &what, agg, top, json, t0, compile) } +/// The runtime's memory windows, as the offline commands key and translate programs. +fn runtime_windows(windows: u32) -> u32 { + recomp::pso::windows_for(windows) +} + #[cfg(test)] fn parse_record_hash(s: &str) -> Result<u64, String> { crate::cli::parse_hex_u64_str(s) @@ -1092,7 +1092,7 @@ fn export_hlsl(input: &Input, dir: &Path, min_kb: usize, count: usize, windows: println!( "{written} program(s) written to {} (split wave64: {split}, {} windows{}, {failures} failure(s))", dir.display(), - windows & !recomp::HEAP_WINDOWS, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" } ); if written == wanted { 0 } else { @@ -1640,7 +1640,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), recomp::dxc::compile_threads(), - windows & !recomp::HEAP_WINDOWS, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }, if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } ); @@ -2098,6 +2098,30 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim #[cfg(test)] mod tests { + /// Offline commands and the runtime must use the same cache identity. Environment switches + /// are process-global (`OnceLock`), so exercise each setting in a fresh test process. + #[test] + fn precompile_windows_are_the_runtimes() { + use crate::gpu::recomp::{pso, HEAP_FLAT, HEAP_WINDOWS}; + const RUN: &str = "XCL_TEST_PRECOMPILE_WINDOWS"; + if let Ok(want) = std::env::var(RUN) { + assert_eq!(super::runtime_windows(4), pso::windows_for(4)); + assert_eq!(super::runtime_windows(4), want.parse::<u32>().unwrap()); + return; + } + for (flat, want) in [("1", 4 | HEAP_WINDOWS | HEAP_FLAT), ("0", 4 | HEAP_WINDOWS)] { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "shaders::tests::precompile_windows_are_the_runtimes", "--nocapture"]) + .env(RUN, want.to_string()) + .env("XCL_HEAP_WINDOWS", "1") + .env("XCL_HEAP_FLAT", flat) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && stdout.contains("1 passed"), "XCL_HEAP_FLAT={flat}: {stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + } + } + /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the /// key of a pipeline of that one shader, as `real::shaders_key` makes it. #[test] From e59178a09c79da66989c9eba40de0673fa2ce4f5 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:44:47 -0800 Subject: [PATCH 153/265] D3D12.X: defer superseded texture unmaps Keep superseded reserved textures and their tiles alive until completion markers on every relevant title and upload queue have passed. Use the guarded queue-retirement snapshot and CPU polling so the mapping queue never waits back on title work. Fail closed when a trustworthy marker cannot be made. Adapted from PR #2270 by Joey Percia, incorporating the queue-cycle finding from PR #594 by Abdellah Khanani. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/vram.rs | 291 +++++++++++++++++++++++++++--- 1 file changed, 267 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 5b203b202b..dde45a78ee 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -586,6 +586,20 @@ fn keep_spare_pools() -> usize { }) } +/// A superseded texture whose NULL mapping is held until work submitted before it has finished. +struct HeldUnmap { + res: ID3D12Resource, + total: u32, + used: Vec<usize>, + used_extra: Vec<(usize, usize)>, + /// Completion marks for every relevant title or upload queue. + marks: Vec<(ID3D12Fence, u64)>, +} + +fn all_marks_complete<F>(marks: &[(F, u64)], mut completed: impl FnMut(&F) -> u64) -> bool { + marks.iter().all(|(fence, value)| completed(fence) >= *value) +} + /// The title's pages of video memory for tiled textures (see the module's comment). struct Pages { queue: ID3D12CommandQueue, @@ -607,6 +621,10 @@ struct Pages { targets: std::collections::HashMap<usize, Target>, /// queue → the fence value it last waited for waited: std::collections::HashMap<usize, u64>, + /// queue → reusable completion fence and its last signalled value + unmap_fences: std::collections::HashMap<usize, (ID3D12Fence, u64)>, + /// Superseded mappings waiting for all pre-existing queue work to finish. + held_unmaps: Vec<HeldUnmap>, /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device reservable_cache: std::collections::HashMap<(i32, u32), bool>, /// reusable scratch buffers for `map()` @@ -660,6 +678,8 @@ impl Pages { idle: std::collections::VecDeque::new(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), + unmap_fences: std::collections::HashMap::new(), + held_unmaps: Vec::new(), reservable_cache: std::collections::HashMap::new(), scratch_heaps: Vec::new(), scratch_flags: Vec::new(), @@ -767,6 +787,80 @@ impl Pages { let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); } + /// Mark work submitted so far on every active queue. Retirement marks cover queues which + /// stopped accepting signals before this snapshot. Failure is closed: the mapping stays live. + unsafe fn mark_unmap( + &mut self, + dev: &ID3D12Device, + queues: &[ID3D12CommandQueue], + retiring: &[(ID3D12Fence, u64)], + blocked: bool, + ) -> Option<Vec<(ID3D12Fence, u64)>> { + if blocked { + return None; + } + let mut marks = Vec::with_capacity(retiring.len() + queues.len()); + for (fence, value) in retiring { + let mut fence_dev: Option<ID3D12Device> = None; + fence.GetDevice(&mut fence_dev).ok()?; + if fence_dev.as_ref().is_some_and(|owner| owner.as_raw() == dev.as_raw()) { + marks.push((fence.clone(), *value)); + } + } + let mut seen = HashSet::new(); + for queue in queues { + let key = queue.as_raw() as usize; + if !seen.insert(key) { + continue; + } + let mut queue_dev: Option<ID3D12Device> = None; + if queue.GetDevice(&mut queue_dev).is_err() || queue_dev.as_ref().is_none_or(|d| d.as_raw() != dev.as_raw()) { + continue; + } + let entry = match self.unmap_fences.entry(key) { + std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::hash_map::Entry::Vacant(entry) => { + let fence = dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok()?; + entry.insert((fence, 0)) + } + }; + let next = entry.1 + 1; + super::real::native_queue_signal(queue, &entry.0, next).ok()?; + entry.1 = next; + marks.push((entry.0.clone(), next)); + } + Some(marks) + } + + /// Strong fence owners to poll without holding `PAGES`. + fn held_unmap_fences(&self) -> Vec<ID3D12Fence> { + self.held_unmaps.iter().flat_map(|held| held.marks.iter().map(|(fence, _)| fence.clone())).collect() + } + + /// Submit completed NULL mappings and return their resource owners for release after unlock. + unsafe fn release_held_unmaps( + &mut self, + now: std::time::Instant, + mut completed: impl FnMut(&ID3D12Fence) -> u64, + ) -> Vec<ID3D12Resource> { + let mut done = Vec::new(); + for held in std::mem::take(&mut self.held_unmaps) { + if all_marks_complete(&held.marks, &mut completed) { + let key = held.res.as_raw() as usize; + if let Some(levels) = self.targets.get_mut(&key).and_then(|target| target.levels.as_mut()) { + LEVEL_STATS[2].fetch_sub(levels.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); + levels.groups.iter_mut().for_each(|group| group.3 = false); + } + self.unmap(&held.res, held.total); + self.release_tiles(held.used, held.used_extra, now, true); + done.push(held.res); + } else { + self.held_unmaps.push(held); + } + } + done + } + fn release_tiles(&mut self, used: Vec<usize>, used_extra: Vec<(usize, usize)>, now: std::time::Instant, immediate_cool: bool) { for a in used { if let Some(p) = self.pages.get_mut(&a) { @@ -879,6 +973,20 @@ impl Pages { } } +/// Poll a snapshot without `PAGES`; a held unmap added meanwhile has no observation and stays held. +unsafe fn held_unmap_completions(dev_key: usize) -> Vec<(ID3D12Fence, u64)> { + let mut fences = { + let pages = PAGES.lock().unwrap(); + pages.get(&dev_key).and_then(Option::as_ref).map(Pages::held_unmap_fences).unwrap_or_default() + }; + fences.sort_unstable_by_key(|fence| fence.as_raw() as usize); + fences.dedup_by_key(|fence| fence.as_raw() as usize); + fences.into_iter().map(|fence| { + let value = fence.GetCompletedValue(); + (fence, value) + }).collect() +} + /// The ranges of one UpdateTileMappings call for pool heap `heap` over a resource whose overall /// tile i goes to `tiles[i]`: (mapped, tile offset in the heap, count) – runs of consecutive /// tiles of the heap, and skipped runs for tiles of other heaps. @@ -1051,29 +1159,45 @@ unsafe fn place_on_pages( Some(hr) } -/// Unmap a placed texture superseded by a placement with a different address range, returning its -/// unshared tiles (`extra_pages` and unshared tail pages) to the cooling pool immediately. +/// Hold a superseded texture's mapping until work submitted before this call has finished. +/// Polling completion on the CPU avoids a dependency from the mapping queue back to a title queue, +/// which may itself already be waiting for later mapping work. pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { + let mut dev: Option<ID3D12Device> = None; + if res.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let dev_key = dev.as_raw() as usize; + let observed = held_unmap_completions(dev_key); + let mut completion = super::present::queue_completion_snapshot(); + completion.active.extend(super::title_textures::upload_queues()); let key = res.as_raw() as usize; - let mut g = PAGES.lock().unwrap(); - let now = std::time::Instant::now(); - for pages in g.values_mut().flatten() { - let Some(t) = pages.targets.get_mut(&key) else { continue }; - if !t.mapped { + let done = { + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&dev_key) else { return }; + if !pages.targets.get(&key).is_some_and(|target| target.mapped) { return; } - let total = t.total; - let used = std::mem::take(&mut t.used); - let used_extra = std::mem::take(&mut t.used_extra); - t.mapped = false; - if let Some(l) = t.levels.as_mut() { - LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); - l.groups.iter_mut().for_each(|g| g.3 = false); - } - pages.unmap(res, total); - pages.release_tiles(used, used_extra, now, true); - return; - } + let Some(marks) = pages.mark_unmap(&dev, &completion.active, &completion.retiring, completion.blocked) else { + crate::xlog_warn!("D3D12.X: could not guard a superseded texture unmap; keeping its mapping"); + return; + }; + let Some(target) = pages.targets.get_mut(&key) else { return }; + let held = HeldUnmap { + res: res.clone(), + total: target.total, + used: std::mem::take(&mut target.used), + used_extra: std::mem::take(&mut target.used_extra), + marks, + }; + target.mapped = false; + pages.held_unmaps.push(held); + pages.release_held_unmaps(std::time::Instant::now(), |fence| { + observed_completion(&observed, fence, |known, current| known.as_raw() == current.as_raw()) + }) + }; + drop(done); } /// Re-map a previously unmapped placed texture when the newer placement shadowing it is released. @@ -1092,6 +1216,18 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { if mapped { return true; } + // A deferred unmap never changed the resource's tiles. Cancel it and restore their ownership. + if let Some(index) = pages.held_unmaps.iter().position(|held| held.res.as_raw() as usize == key) { + let held = pages.held_unmaps.swap_remove(index); + if let Some(target) = pages.targets.get_mut(&key) { + target.used = held.used; + target.used_extra = held.used_extra; + target.mapped = true; + } + drop(g); + drop(held.res); + return true; + } // (lazy levels: they get their pages again with their next texels) if let Some(t) = pages.targets.get_mut(&key).filter(|t| t.levels.is_some()) { t.mapped = true; @@ -1208,19 +1344,20 @@ fn device_retire_state(dev_key: usize) -> DeviceRetire { /// objects are extracted from both locks and dropped afterward; retirement batches keep clones. pub(super) fn forget_queue(id: super::present::QueueId) { let queue = id.raw(); - { + let page_fences = { let mut pages = PAGES.lock().unwrap(); - for pages in pages.values_mut().flatten() { + pages.values_mut().flatten().filter_map(|pages| { pages.waited.remove(&queue); - } - } + pages.unmap_fences.remove(&queue) + }).collect::<Vec<_>>() + }; let wait_gate = wait_gates().lock().unwrap().remove(&queue); let states: Vec<_> = RETIRE.lock().unwrap().as_ref().into_iter().flat_map(|devices| devices.values().cloned()).collect(); let gone: Vec<_> = states .iter() .filter_map(|state| state.lock().unwrap().forget_queue(queue)) .collect(); - drop((gone, wait_gate)); + drop((page_fences, gone, wait_gate)); } /// Collect all known live command queues belonging to `dev_key` (deduplicated by raw ptr). @@ -1294,13 +1431,18 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let Some(dev) = dev else { return }; let dev_key = dev.as_raw() as usize; let now = std::time::Instant::now(); + let unmap_completions = held_unmap_completions(dev_key); let mut newly_reclaimed = Vec::new(); let mut do_reclaim = false; let mut unmap_mark: Option<(ID3D12Fence, u64)> = None; + let mut completed_unmaps = Vec::new(); let mut wait = None; { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { + completed_unmaps = pages.release_held_unmaps(now, |fence| { + observed_completion(&unmap_completions, fence, |known, current| known.as_raw() == current.as_raw()) + }); let value = pages.value; if reserve_page_wait(&mut pages.waited, queue_key, value) { wait = Some((pages.fence.clone(), value)); @@ -1325,6 +1467,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { if do_reclaim || !newly_reclaimed.is_empty() || RETIRING_BATCHES.load(std::sync::atomic::Ordering::Acquire) > 0 { retire_heaps_and_sweep(&dev, dev_key, newly_reclaimed, unmap_mark, Some(queue)); } + drop(completed_unmaps); } #[cfg(test)] @@ -1372,6 +1515,12 @@ pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { (pages, pools) } +#[cfg(test)] +fn held_unmaps_for(device: usize) -> usize { + let g = PAGES.lock().unwrap(); + g.get(&device).and_then(Option::as_ref).map_or(0, |pages| pages.held_unmaps.len()) +} + /// Pool/tile identities used by one mapped resource: title pages, then extra pages. /// Unlike device-wide byte counts, these cannot shrink when unrelated idle targets expire. #[cfg(test)] @@ -1824,6 +1973,19 @@ mod tests { assert_eq!(rq.retire_with(vec![303], None, &[] as &[(usize, usize)], mk, |_, _, _| true), vec![303]); } + #[test] + fn deferred_unmap_requires_every_queue_mark() { + use std::sync::{atomic::{AtomicU64, Ordering}, Arc}; + let first = Arc::new(AtomicU64::new(0)); + let second = Arc::new(AtomicU64::new(0)); + let marks = [(first.clone(), 2), (second.clone(), 1)]; + assert!(!all_marks_complete(&marks, |fence| fence.load(Ordering::SeqCst))); + first.store(2, Ordering::SeqCst); + assert!(!all_marks_complete(&marks, |fence| fence.load(Ordering::SeqCst)), "one completed queue must not release the mapping"); + second.store(1, Ordering::SeqCst); + assert!(all_marks_complete(&marks, |fence| fence.load(Ordering::SeqCst))); + } + #[test] fn retirement_completion_poll_is_unlocked_and_new_marks_fail_closed() { use std::sync::{atomic::{AtomicU64, Ordering}, Arc}; @@ -1941,6 +2103,87 @@ mod tests { } } + #[test] + fn superseded_texture_waits_for_every_title_queue() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::core::Interface; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + unsafe { + 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"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let first: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let second: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let polling: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + super::super::present::note_execute(first.as_raw(), &[]); + super::super::present::note_execute(second.as_raw(), &[]); + let gate_first: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let gate_second: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + first.Wait(&gate_first, 1).unwrap(); + second.Wait(&gate_second, 1).unwrap(); + + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 512, + Height: 512, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let mut raw = std::ptr::null_mut(); + let hr = place_pages(dev.as_raw(), 0x7_1000_0000, &desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), None, riid, &mut raw); + if hr.is_none_or(|hr| hr < 0) || raw.is_null() { + return crate::gpu::recomp::runner::skip_test("reserved texture unavailable"); + } + let resource = ID3D12Resource::from_raw(raw); + let dev_key = dev.as_raw() as usize; + let bytes = page_bytes_for(dev_key).0; + assert!(bytes >= 16 * PAGE); + + unmap_superseded(&resource); + before_execute(&polling); + assert_eq!(held_unmaps_for(dev_key), 1); + assert_eq!(page_bytes_for(dev_key).0, bytes, "blocked queues must keep the physical tiles live"); + + gate_first.Signal(1).unwrap(); + let first_done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + first.Signal(&first_done, 1).unwrap(); + first_done.SetEventOnCompletion(1, windows::Win32::Foundation::HANDLE::default()).unwrap(); + before_execute(&polling); + assert_eq!(held_unmaps_for(dev_key), 1, "the second queue still owns prior work"); + + gate_second.Signal(1).unwrap(); + let second_done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + second.Signal(&second_done, 1).unwrap(); + second_done.SetEventOnCompletion(1, windows::Win32::Foundation::HANDLE::default()).unwrap(); + before_execute(&polling); + assert_eq!(held_unmaps_for(dev_key), 0); + assert!(page_bytes_for(dev_key).0 < bytes, "tiles return only after every queue completes"); + + let mut remap_raw = std::ptr::null_mut(); + let remap_hr = place_pages(dev.as_raw(), 0x7_2000_0000, &desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), None, riid, &mut remap_raw); + assert!(remap_hr.is_some_and(|hr| hr >= 0) && !remap_raw.is_null()); + let remapped = ID3D12Resource::from_raw(remap_raw); + let remap_bytes = page_bytes_for(dev_key).0; + first.Wait(&gate_first, 2).unwrap(); + second.Wait(&gate_second, 2).unwrap(); + unmap_superseded(&remapped); + assert_eq!(held_unmaps_for(dev_key), 1); + assert!(remap_if_unmapped(&remapped)); + assert_eq!(held_unmaps_for(dev_key), 0, "remapping cancels the deferred unmap"); + assert_eq!(page_bytes_for(dev_key).0, remap_bytes, "cancellation preserves the original tiles"); + gate_first.Signal(2).unwrap(); + gate_second.Signal(2).unwrap(); + drop(remapped); + drop(resource); + } + } + #[test] fn canonical_va_aliases_unmapped_gpu_view_but_preserves_committed_override() { use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; From 4cd1b772ca4af0106fc6cf9fef70ffa83cb0a70e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:50:58 -0800 Subject: [PATCH 154/265] D3D12.X: separate persisted compute blobs by node The in-memory driver-blob key already includes NodeMask, but the disk filename did not. Persist nonzero linked-adapter node masks in the name so later processes cannot offer node-specific cached state to another node; node zero keeps cache compatibility. Checked with the Windows GNU cross-target cargo check; native linked-adapter execution was unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3ba993b013..9ea3dae409 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4752,7 +4752,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const crate::xlog_warn!( "D3D12.X: the driver refused the compute PSO of record {record:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver: its dispatches are skipped", dxil.len(), - driver_cache::name_for_root(&dxil, d.Flags.0, false, &compiled.samplers), + driver_cache::name_for_root_node(&dxil, d.Flags.0, false, &compiled.samplers, d.NodeMask), in_driver.as_millis() ); } @@ -4876,7 +4876,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL let key = compute_blob_key_for(dxil, rs as usize, copy.Flags.0, copy.NodeMask); let mut cached = compute_blob(key); // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) - let disk = driver_cache::path_for_root(dxil, copy.Flags.0, mode == ComputeBuild::Chain, samplers); + let disk = driver_cache::path_for_root_node(dxil, copy.Flags.0, mode == ComputeBuild::Chain, samplers, copy.NodeMask); let from_disk = cached.is_none(); let mut loaded = None; if from_disk { @@ -4987,8 +4987,16 @@ pub(crate) mod driver_cache { /// The cache file for a pipeline whose fixed ABI root-signature layout has these ordered /// static samplers. Empty samplers retain the existing name and cache compatibility. pub fn name_for_root(dxil: &[u8], flags: i32, chained: bool, samplers: &[StaticSampler]) -> String { + name_for_root_node(dxil, flags, chained, samplers, 0) + } + + /// Include the linked-adapter node in persisted driver state. Node zero keeps legacy names. + pub fn name_for_root_node(dxil: &[u8], flags: i32, chained: bool, samplers: &[StaticSampler], node_mask: u32) -> String { let ext = if chained { "chain.pso" } else { "pso" }; - let base = format!("{:016x}-{:x}-{:x}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags); + let mut base = format!("{:016x}-{:x}-{:x}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags); + if node_mask != 0 { + base += &format!("-n{node_mask:x}"); + } if samplers.is_empty() { return format!("{base}.{ext}"); } @@ -5036,6 +5044,10 @@ pub(crate) mod driver_cache { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for_root(dxil, flags, chained, samplers))) } + pub fn path_for_root_node(dxil: &[u8], flags: i32, chained: bool, samplers: &[StaticSampler], node_mask: u32) -> Option<PathBuf> { + enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for_root_node(dxil, flags, chained, samplers, node_mask))) + } + pub fn graphics_path(hash: u64, bytes: usize) -> Option<PathBuf> { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(graphics_name(hash, bytes))) } @@ -5375,6 +5387,17 @@ pub(crate) mod driver_cache { assert_ne!(file(false, &[wrap]), file(true, &[wrap])); } + #[test] + fn linked_adapter_nodes_have_distinct_compatible_names() { + let legacy = name_for_root(b"same dxil", 3, false, &[]); + assert_eq!(legacy, name_for_root_node(b"same dxil", 3, false, &[], 0)); + assert_ne!(legacy, name_for_root_node(b"same dxil", 3, false, &[], 2)); + assert_ne!( + name_for_root_node(b"same dxil", 3, false, &[], 1), + name_for_root_node(b"same dxil", 3, false, &[], 2) + ); + } + #[test] fn disk_blobs_default_off_only_for_amd_and_can_be_overridden() { assert!(reference_blob_vendor(0x1002)); From 87c5c52cdf3594a970bc644295b14c43fd064dc7 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:50:38 -0800 Subject: [PATCH 155/265] XAudio2: bulk-copy decoded PCM output The Windows Opus decoder converted PCM16 output one sample at a time. Copy complete little-endian samples into the reserved output buffer in one operation while preserving scalar float conversion and partial-sample handling. Adapted from PR #2696 by Decodere and Google Antigravity (Gemini 4 Neon), which measured the 3840-byte PCM16 append at 1024.4 ns before and 31.5 ns after. The Windows GNU cross-target library/test check passes; native Windows audio execution was unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/opus.rs | 75 ++++++++++++++++++++++++++++++-------- 1 file changed, 60 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/opus.rs b/crates/xcl/src/hle/opus.rs index 70d49e338a..be83ecd301 100644 --- a/crates/xcl/src/hle/opus.rs +++ b/crates/xcl/src/hle/opus.rs @@ -1329,21 +1329,8 @@ impl MftDecoder { if cur_len > 0 && !ptr.is_null() { let bytes = std::slice::from_raw_parts(ptr, cur_len as usize); match self.output_fmt { - OutputSampleFormat::Pcm16 => { - let n = bytes.len() / 2; - out.reserve(n); - for chunk in bytes.chunks_exact(2) { - out.push(i16::from_le_bytes([chunk[0], chunk[1]])); - } - } - OutputSampleFormat::Float32 => { - let n = bytes.len() / 4; - out.reserve(n); - for chunk in bytes.chunks_exact(4) { - let f = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); - out.push(f32_to_i16(f)); - } - } + OutputSampleFormat::Pcm16 => append_pcm16_le(bytes, out), + OutputSampleFormat::Float32 => append_f32_le(bytes, out), } } let _ = buf.Unlock(); @@ -1351,6 +1338,33 @@ impl MftDecoder { } } +const _: () = assert!(cfg!(target_endian = "little")); + +/// Bulk-append little-endian signed 16-bit PCM bytes, ignoring a trailing odd byte. +fn append_pcm16_le(bytes: &[u8], out: &mut Vec<i16>) { + let n = bytes.len() / 2; + if n == 0 { + return; + } + let old = out.len(); + out.reserve(n); + // SAFETY: XCL targets little-endian x64, `reserve` provides `n` writable elements, the byte + // copy needs no source alignment, and safe borrowing keeps the input separate from `out`. + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), out.as_mut_ptr().add(old).cast::<u8>(), n * 2); + out.set_len(old + n); + } +} + +/// Append little-endian float PCM as clamped i16, ignoring a trailing partial sample. +fn append_f32_le(bytes: &[u8], out: &mut Vec<i16>) { + let chunks = bytes.as_chunks::<4>().0; + out.reserve(chunks.len()); + for &chunk in chunks { + out.push(f32_to_i16(f32::from_le_bytes(chunk))); + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum ChannelSrc { Silence, @@ -2209,6 +2223,37 @@ pub(crate) mod tests { assert!(split_multistream_into(&mismatched_duration, 2, &mut one_sub).is_none(), "all sub-streams must describe the same duration"); } + #[test] + fn pcm_output_append_matches_scalar_for_unaligned_and_partial_input() { + let samples = [i16::MIN, -32767, -1, 0, 1, 12345, i16::MAX]; + let mut raw = vec![0xEEu8]; + for sample in samples { + raw.extend_from_slice(&sample.to_le_bytes()); + } + raw.push(0xAA); + for bytes in [&[][..], &[0x7F], &raw[1..1 + samples.len() * 2], &raw[1..], &raw[..raw.len() - 1]] { + let mut got = vec![1234, -5678]; + append_pcm16_le(bytes, &mut got); + let mut want = vec![1234, -5678]; + want.extend(bytes.as_chunks::<2>().0.iter().copied().map(i16::from_le_bytes)); + assert_eq!(got, want); + } + + let floats = [0.0f32, 0.5, -0.5, 1.0, -1.0, 2.5, -2.5, f32::NAN, f32::INFINITY, f32::NEG_INFINITY]; + let mut float_bytes = vec![0xDDu8]; + for sample in floats { + float_bytes.extend_from_slice(&sample.to_le_bytes()); + } + float_bytes.extend_from_slice(&[0x11, 0x22]); + for bytes in [&[][..], &[1, 2, 3], &float_bytes[1..]] { + let mut got = vec![42]; + append_f32_le(bytes, &mut got); + let mut want = vec![42]; + want.extend(bytes.as_chunks::<4>().0.iter().copied().map(|b| f32_to_i16(f32::from_le_bytes(b)))); + assert_eq!(got, want); + } + } + #[test] fn interleave_channel_map_clamps_short_stream_without_panic() { let map = build_channel_map(&[0, 4, 1, 2, 3, 5, 255, 99], 4, 2); From bbd12224f6f08b4e254229d2f8c6ca692fb65aeb Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:52:16 -0800 Subject: [PATCH 156/265] D3D12.X: signal deferred unmaps outside page state Reserve fail-closed completion values while updating the held mapping, then call the driver queue Signal methods after releasing PAGES. Concurrent completion polling sees unsignalled values and keeps the mapping, and a Signal failure remains safely incomplete. Checked with the Windows GNU cross-target cargo check; native multi-queue GPU tests were unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/vram.rs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index dde45a78ee..20739ea7a2 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -795,11 +795,12 @@ impl Pages { queues: &[ID3D12CommandQueue], retiring: &[(ID3D12Fence, u64)], blocked: bool, - ) -> Option<Vec<(ID3D12Fence, u64)>> { + ) -> Option<(Vec<(ID3D12Fence, u64)>, Vec<(ID3D12CommandQueue, ID3D12Fence, u64)>)> { if blocked { return None; } let mut marks = Vec::with_capacity(retiring.len() + queues.len()); + let mut signals = Vec::with_capacity(queues.len()); for (fence, value) in retiring { let mut fence_dev: Option<ID3D12Device> = None; fence.GetDevice(&mut fence_dev).ok()?; @@ -825,11 +826,11 @@ impl Pages { } }; let next = entry.1 + 1; - super::real::native_queue_signal(queue, &entry.0, next).ok()?; entry.1 = next; marks.push((entry.0.clone(), next)); + signals.push((queue.clone(), entry.0.clone(), next)); } - Some(marks) + Some((marks, signals)) } /// Strong fence owners to poll without holding `PAGES`. @@ -1173,13 +1174,13 @@ pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { let mut completion = super::present::queue_completion_snapshot(); completion.active.extend(super::title_textures::upload_queues()); let key = res.as_raw() as usize; - let done = { + let (done, signals) = { let mut g = PAGES.lock().unwrap(); let Some(Some(pages)) = g.get_mut(&dev_key) else { return }; if !pages.targets.get(&key).is_some_and(|target| target.mapped) { return; } - let Some(marks) = pages.mark_unmap(&dev, &completion.active, &completion.retiring, completion.blocked) else { + let Some((marks, signals)) = pages.mark_unmap(&dev, &completion.active, &completion.retiring, completion.blocked) else { crate::xlog_warn!("D3D12.X: could not guard a superseded texture unmap; keeping its mapping"); return; }; @@ -1193,10 +1194,16 @@ pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { }; target.mapped = false; pages.held_unmaps.push(held); - pages.release_held_unmaps(std::time::Instant::now(), |fence| { + let done = pages.release_held_unmaps(std::time::Instant::now(), |fence| { observed_completion(&observed, fence, |known, current| known.as_raw() == current.as_raw()) - }) + }); + (done, signals) }; + for (queue, fence, value) in signals { + if super::real::native_queue_signal(&queue, &fence, value).is_err() { + crate::xlog_warn!("D3D12.X: could not signal a superseded texture unmap marker; keeping its mapping"); + } + } drop(done); } From d2f1651534de080225dbc36ec6edcb8dcd662422 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:53:51 -0800 Subject: [PATCH 157/265] Recompiler: keep graphics cache identity under heap-flat HEAP_FLAT changes only compute-stage direct DXIL. Remove the flag from vertex, pixel, mesh, and geometry translation inputs so opting into the compute fast path does not invalidate byte-identical graphics cache entries. Checked with the Windows GNU cross-target cargo check; native GPU execution was unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/pso.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 9ca022da4c..ceb5aad9cc 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -135,6 +135,11 @@ pub fn windows_for(n: u32) -> u32 { } } +/// `HEAP_FLAT` changes only compute translation; other stages keep their existing cache identity. +fn windows_for_stage(windows: u32, stage: Stage) -> u32 { + if stage == Stage::Compute { windows } else { windows & !super::HEAP_FLAT } +} + thread_local! { /// this thread translates in the switch form (`in_switch_form`) static SWITCH_FORM: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; @@ -208,6 +213,7 @@ fn shader_cache() -> &'static Mutex<ShaderCache> { /// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result<Compiled, String> { + let windows = windows_for_stage(windows, stage); let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { return compile_one().map(|(c, _)| c); @@ -1293,7 +1299,7 @@ fn console_mesh_with( /// The mesh-shader (NGG) program of a console MS container; the pass-through carries what /// the pixel shader `ps` (its container: console or PC) reads. pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result<TwoPass, String> { - let windows = mem_windows(); + let windows = windows_for_stage(mem_windows(), Stage::Mesh); let dir = dxc::cache_dir(); console_mesh_with(blob, ps, split_wave64, windows, &dir, shader_cache(), |code, ms, wave64| { compile_console_mesh(blob, code, ms, wave64, windows, split_wave64) @@ -1349,8 +1355,9 @@ pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: b let (code, g) = super::geometry_program(vs, gs)?; let record = g.record(); // `XCL_DIRECT_DXIL=1`: the compute pass through the direct DXIL translator (HLSL fallback) + let windows = windows_for_stage(mem_windows(), Stage::Mesh); if crate::gpu::dxil::kernel::enabled() { - let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: split_wave64, mem_windows: mem_windows(), sampler_base: 0 }; + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: split_wave64, mem_windows: windows, sampler_base: 0 }; match crate::gpu::dxil::kernel::translate_geometry(&code, o, &g) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("GS"); @@ -1362,7 +1369,7 @@ pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: b Err(e) => direct_fallback("GS", &e), } } - let translation = super::translate_geometry(&code, g, split_wave64, mem_windows())?; + let translation = super::translate_geometry(&code, g, split_wave64, windows)?; finish_two_pass(translation, record, ps) } @@ -1544,6 +1551,15 @@ mod slab_tests { mod shader_cache_tests { use super::*; + #[test] + fn heap_flat_partitions_only_compute_cache_keys() { + let windows = 4 | super::super::HEAP_WINDOWS | super::super::HEAP_FLAT; + assert_eq!(windows_for_stage(windows, Stage::Compute), windows); + for stage in [Stage::Vertex, Stage::Pixel, Stage::Mesh] { + assert_eq!(windows_for_stage(windows, stage), windows & !super::super::HEAP_FLAT); + } + } + #[test] fn translated_identity_tracks_sources_and_dxc() { let built_source = env!("XCL_TRANSLATOR_SOURCE_ID"); From 4893eb6cb433f4a068420402346e8dd327cfae47 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:53:34 -0800 Subject: [PATCH 158/265] Shaders: claim driver-cache builds across processes Concurrent preparation processes could hand the same missing or stale compute pipeline to the driver at once. Coordinate each exact driver-cache path with an exclusive Windows delete-on-close handle, which also releases ownership immediately when a worker is terminated. Filesystem failures remain fail-open so preparation still works without a writable shared cache. Adapted as the first separable stage of PR #2712 by ZekkJJ. Checked with the Windows GNU cross-target cargo check; native Windows claim tests and GPU execution were unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/shaders.rs | 201 +++++++++++++++++++++++++++++++++++++- 1 file changed, 200 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 02db0dee79..1e1b045503 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1207,6 +1207,8 @@ struct Pipelines { made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, + /// pipelines an OS-backed claim proves another process is already building + elsewhere: AtomicUsize, split_programs: AtomicUsize, split_pieces: AtomicUsize, /// programs over `max_dxil` with no blob yet, and their DXIL bytes @@ -1222,6 +1224,166 @@ struct Pipelines { cache_dir: Option<PathBuf>, } +enum ClaimAcquire { + Acquired(Claim), + HeldElsewhere, + Unavailable(std::io::Error), +} + +/// Exclusive cross-process ownership of one driver-cache build (`<blob>.claim`). The kernel +/// deletes the file when the handle closes, including after forced process termination. +struct Claim { + _file: std::fs::File, +} + +fn claim_path_for(blob: &Path) -> PathBuf { + let mut name = blob.as_os_str().to_owned(); + name.push(".claim"); + PathBuf::from(name) +} + +impl Claim { + fn acquire(blob: &Path) -> ClaimAcquire { + use std::os::windows::fs::OpenOptionsExt; + use windows_sys::Win32::Foundation::{ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION, GENERIC_READ, GENERIC_WRITE}; + use windows_sys::Win32::Storage::FileSystem::{DELETE, FILE_ATTRIBUTE_TEMPORARY, FILE_FLAG_DELETE_ON_CLOSE}; + + let path = claim_path_for(blob); + if let Some(dir) = path.parent().filter(|dir| !dir.as_os_str().is_empty()) { + if let Err(e) = std::fs::create_dir_all(dir) { + return ClaimAcquire::Unavailable(e); + } + } + // OPEN_ALWAYS adopts an unlocked orphan from the old create/delete protocol. DELETE is + // required to apply FILE_FLAG_DELETE_ON_CLOSE to that existing file. + let open = || { + std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .access_mode(GENERIC_READ | GENERIC_WRITE | DELETE) + .share_mode(0) + .attributes(FILE_ATTRIBUTE_TEMPORARY) + .custom_flags(FILE_FLAG_DELETE_ON_CLOSE) + .open(&path) + }; + for attempt in 0..4 { + match open() { + Ok(file) => return ClaimAcquire::Acquired(Claim { _file: file }), + Err(e) if e.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32) => return ClaimAcquire::HeldElsewhere, + // A just-closed delete-on-close handle can leave a brief delete-pending window. + Err(e) if e.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) && attempt < 3 => { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + Err(e) => return ClaimAcquire::Unavailable(e), + } + } + unreachable!("claim acquisition loop always returns") + } +} + +#[cfg(test)] +mod pipeline_claim_tests { + use super::{claim_path_for, Claim, ClaimAcquire}; + use std::io::{BufRead, BufReader, Write}; + use std::path::PathBuf; + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + struct TempDir(PathBuf); + impl TempDir { + fn new(prefix: &str) -> Self { + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let path = std::env::temp_dir().join(format!("{prefix}-{}-{nonce}", std::process::id())); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + } + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + struct ChildGuard(std::process::Child); + impl Drop for ChildGuard { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + + #[test] + fn claim_child_role_entrypoint() { + if std::env::var("XCL_CLAIM_TEST_ROLE").as_deref() != Ok("hold") { + return; + } + let blob = PathBuf::from(std::env::var("XCL_CLAIM_TEST_BLOB").expect("blob path")); + let _claim = match Claim::acquire(&blob) { + ClaimAcquire::Acquired(claim) => claim, + ClaimAcquire::HeldElsewhere => panic!("unexpected contention in child"), + ClaimAcquire::Unavailable(e) => panic!("claim unavailable in child: {e}"), + }; + println!("LOCKED"); + std::io::stdout().flush().unwrap(); + std::thread::sleep(Duration::from_secs(60)); + } + + #[test] + fn claims_are_exclusive_adopt_orphans_and_report_filesystem_errors() { + let dir = TempDir::new("xcl-claim"); + let blob = dir.0.join("nested").join("one.pso"); + let first = match Claim::acquire(&blob) { + ClaimAcquire::Acquired(claim) => claim, + _ => panic!("first claim must succeed"), + }; + assert!(claim_path_for(&blob).is_file()); + assert!(matches!(Claim::acquire(&blob), ClaimAcquire::HeldElsewhere)); + assert!(matches!(Claim::acquire(&dir.0.join("two.pso")), ClaimAcquire::Acquired(_))); + drop(first); + assert!(!claim_path_for(&blob).exists()); + + std::fs::write(claim_path_for(&blob), b"orphan from old protocol").unwrap(); + let adopted = match Claim::acquire(&blob) { + ClaimAcquire::Acquired(claim) => claim, + _ => panic!("unlocked orphan must be adopted"), + }; + drop(adopted); + assert!(!claim_path_for(&blob).exists()); + + let file = dir.0.join("not-a-directory"); + std::fs::write(&file, b"x").unwrap(); + assert!(matches!(Claim::acquire(&file.join("bad.pso")), ClaimAcquire::Unavailable(_))); + } + + #[test] + fn forced_process_termination_releases_a_claim_immediately() { + let dir = TempDir::new("xcl-claim-kill"); + let blob = dir.0.join("driver").join("killed.pso"); + let mut child = ChildGuard(std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "shaders::pipeline_claim_tests::claim_child_role_entrypoint", "--nocapture"]) + .env("XCL_CLAIM_TEST_ROLE", "hold") + .env("XCL_CLAIM_TEST_BLOB", &blob) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap()); + let mut lines = BufReader::new(child.0.stdout.take().unwrap()).lines(); + let ready = lines.by_ref().any(|line| line.is_ok_and(|line| line.trim() == "LOCKED")); + assert!(ready, "child did not acquire claim"); + assert!(matches!(Claim::acquire(&blob), ClaimAcquire::HeldElsewhere)); + + child.0.kill().unwrap(); + let _ = child.0.wait(); + assert!(!claim_path_for(&blob).exists()); + let recovered = match Claim::acquire(&blob) { + ClaimAcquire::Acquired(claim) => claim, + _ => panic!("terminated owner's claim must be free"), + }; + drop(recovered); + assert!(!claim_path_for(&blob).exists()); + } +} + /// `XCL_PIPELINE_MAX_KB`: the KiB of DXIL `--pipelines` still compiles (default 8 MiB; 0: no /// cap). Above it sit the programs whose driver compile takes tens of minutes and gigabytes — /// the > 8 MB HLSL programs DXC compiles at `-O0` (#1269) — and they hang the pass. @@ -1428,6 +1590,7 @@ impl Pipelines { made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), + elsewhere: AtomicUsize::new(0), split_programs: AtomicUsize::new(0), split_pieces: AtomicUsize::new(0), capped: AtomicUsize::new(0), @@ -1517,7 +1680,7 @@ impl Pipelines { driver_cache::path_for_root(dxil, desc.Flags.0, chained, samplers) }); let mut loaded = path.as_deref().and_then(driver_cache::load); - let cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); + let mut cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes // tens of minutes and gigabytes; the pass finishes without it, and the runtime builds it @@ -1528,6 +1691,38 @@ impl Pipelines { drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); return; } + // A valid blob may be used by many processes, but validation itself can fall through to + // a full driver compile when the blob is stale. Claim before either path so only one + // process can validate/rebuild/remove this exact cache entry at a time. + let _claim = match path.as_deref() { + Some(path) => match Claim::acquire(path) { + ClaimAcquire::Acquired(claim) => Some(claim), + ClaimAcquire::HeldElsewhere => { + self.elsewhere.fetch_add(1, Ordering::Relaxed); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return; + } + ClaimAcquire::Unavailable(e) => { + static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + crate::xlog_warn!("Shader preparation: cannot coordinate claim for {}: {e}; building locally", path.display()); + } + None + } + }, + None => None, + }; + if _claim.is_some() { + // The previous owner can publish and close between our first lookup and OPEN_ALWAYS. + loaded = path.as_deref().and_then(driver_cache::load); + cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); + if cached.is_none() && over_cap { + self.capped.fetch_add(1, Ordering::Relaxed); + self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return; + } + } { let mut n = self.running.0.lock().unwrap(); while *n >= self.most { @@ -1756,6 +1951,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on if let Some(p) = pipelines { println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); println!("pipelines loaded from the driver cache {}", p.reused.load(Ordering::Relaxed)); + let elsewhere = p.elsewhere.load(Ordering::Relaxed); + if elsewhere != 0 { + println!("pipelines left to another preparation process {elsewhere}"); + } let split_programs = p.split_programs.load(Ordering::Relaxed); if split_programs != 0 { println!("split compute programs: {} ({} pieces)", split_programs, p.split_pieces.load(Ordering::Relaxed)); From 5afb11adfd8fed1fa390bef8b47caf93534594f7 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:57:29 -0800 Subject: [PATCH 159/265] D3D12.X: keep two-pass compute on the pipeline node Two-pass mesh and geometry streams preserved NodeMask for their visible mesh PSO but built the hidden compute pass on node zero. Carry the same node into its descriptor and both in-memory and persisted driver-blob identities. A stream test covers NodeMask extraction. Checked with the Windows GNU cross-target cargo check; native linked-adapter execution was unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 32 ++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9ea3dae409..0608092274 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5628,6 +5628,7 @@ const COMPUTE_BLOBS_MAX: usize = 512 << 20; /// smaller programs compile in milliseconds: not kept const COMPUTE_BLOB_MIN_DXIL: usize = 16 << 10; +#[cfg_attr(not(test), allow(dead_code))] fn compute_blob_key(dxil: &[u8], rs: usize, flags: i32) -> (u64, usize, i32) { compute_blob_key_for(dxil, rs, flags, 0) } @@ -6964,6 +6965,13 @@ fn known_subobjects(buf: &[u8]) -> Vec<(u32, &[u8])> { known_subobjects_checked(buf).0 } +fn stream_node_mask(subobjects: &[(u32, &[u8])]) -> u32 { + subobjects + .iter() + .find(|(ty, payload)| *ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK.0 as u32 && payload.len() >= 4) + .map_or(0, |(_, payload)| u32::from_le_bytes(payload[..4].try_into().unwrap())) +} + unsafe fn payload_shader<'a>(p: &[u8]) -> Option<&'a [u8]> { let b = D3D12_SHADER_BYTECODE { pShaderBytecode: u64::from_le_bytes(p[0..8].try_into().ok()?) as usize as *const c_void, BytecodeLength: u64::from_le_bytes(p[8..16].try_into().ok()?) as usize }; shader_bytes(&b) @@ -7051,7 +7059,7 @@ fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option<Vec<u8>> /// Create the mesh pipeline (`stream`, RS and shaders already in it) and the compute pass; /// the title gets the mesh pipeline state. #[allow(clippy::too_many_arguments)] -unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { +unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, node_mask: u32, kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let Some(rs) = abi_rs_for(this, &tp.samplers) else { return E_INVALIDARG }; let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let desc: [usize; 2] = [stream.0.len(), stream.0.as_ptr() as usize]; @@ -7073,13 +7081,14 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let mesh_pso = *ppv; let fc: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + cdesc.NodeMask = node_mask; cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop<Option<ID3D12RootSignature>>>(rs); cdesc.CS = bytecode(&tp.cs); // Reuse the compiled driver blob of the compute pass across all `(MS/GS, PS)` pipelines that // share `tp.cs` (in memory and on disk), matching `translated_compute_pso_once`. - let ckey = compute_blob_key(&tp.cs, rs as usize, 0); + let ckey = compute_blob_key_for(&tp.cs, rs as usize, 0, node_mask); let mut ccached = compute_blob(ckey); - let cdisk = driver_cache::path_for_root(&tp.cs, 0, false, &tp.samplers); + let cdisk = driver_cache::path_for_root_node(&tp.cs, 0, false, &tp.samplers, node_mask); let cfrom_disk = ccached.is_none(); let mut cloaded = None; if cfrom_disk { @@ -7233,7 +7242,8 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri out.raw(*ty, payload, palign == 8); } } - let hr = finish_two_pass(this, &out, tp, rs, "MS", riid, ppv); + let node_mask = stream_node_mask(&subs); + let hr = finish_two_pass(this, &out, tp, rs, node_mask, "MS", riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("ms", Some(ms)), ("ps", console_ps)]); } @@ -7308,7 +7318,7 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE if d.Flags.0 != 0 { out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, &d.Flags); } - let hr = finish_two_pass(this, &out, tp, rs, "GS", riid, ppv); + let hr = finish_two_pass(this, &out, tp, rs, d.NodeMask, "GS", riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("gs", Some(gs)), ("ps", shader_bytes(&d.PS))]); } @@ -9796,6 +9806,14 @@ mod map_tests { assert!(!known_subobjects_checked(&truncated_payload).1); } + #[test] + fn pipeline_stream_node_mask_defaults_and_round_trips() { + assert_eq!(stream_node_mask(&[]), 0); + let mut stream = StreamOut::default(); + stream.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, &4u32); + assert_eq!(stream_node_mask(&stream_subobjects(&stream.0).unwrap()), 4); + } + #[test] fn stream_pipeline_projects_legacy_rasterizer_fields() { let console_vs = crate::gpu::xbox::tests::sample( @@ -10186,12 +10204,12 @@ mod mesh_stream_tests { unsafe { // Case 1: driver returns S_OK but leaves *ppv == null let mut out: *mut c_void = std::ptr::null_mut(); - let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &iid, &mut out); + let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, 0, "MS", &iid, &mut out); assert_eq!(hr, E_INVALIDARG); assert!(out.is_null()); // Case 2: caller passes ppv == null - let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &iid, std::ptr::null_mut()); + let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, 0, "MS", &iid, std::ptr::null_mut()); assert_eq!(hr, E_INVALIDARG); } } From acafdbd1b6e83b1544dbf9cb096820112bf88688 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:57:02 -0800 Subject: [PATCH 160/265] Shaders: release pipeline permits during unwind Manual running-count decrements covered normal returns but leaked a slot if driver pipeline creation panicked, potentially leaving every later preparation thread blocked on the concurrency cap. Use a narrow RAII permit for only the running counter and condition variable. A deterministic unwind test verifies the counter returns to zero and a waiting thread can acquire the slot. Adapted as an independent stage of PR #2712 by ZekkJJ. Checked with the Windows GNU cross-target cargo check; native Windows tests and GPU execution were unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/shaders.rs | 64 ++++++++++++++++++++++++++++++++------- 1 file changed, 53 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 1e1b045503..3028cf1a34 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1282,6 +1282,58 @@ impl Claim { } } +struct RunningPermit<'a> { + state: &'a (Mutex<usize>, std::sync::Condvar), +} + +impl<'a> RunningPermit<'a> { + fn enter(state: &'a (Mutex<usize>, std::sync::Condvar), most: usize) -> Self { + let mut running = state.0.lock().unwrap_or_else(|e| e.into_inner()); + while *running >= most { + running = state.1.wait(running).unwrap_or_else(|e| e.into_inner()); + } + *running += 1; + Self { state } + } +} + +impl Drop for RunningPermit<'_> { + fn drop(&mut self) { + let mut running = self.state.0.lock().unwrap_or_else(|e| e.into_inner()); + *running = running.saturating_sub(1); + self.state.1.notify_one(); + } +} + +#[cfg(test)] +mod running_permit_tests { + use super::RunningPermit; + use std::sync::{mpsc, Condvar, Mutex}; + use std::time::Duration; + + #[test] + fn unwind_releases_the_slot_and_wakes_a_waiter() { + let state = (Mutex::new(0usize), Condvar::new()); + let (started_tx, started_rx) = mpsc::channel(); + let (acquired_tx, acquired_rx) = mpsc::channel(); + std::thread::scope(|scope| { + let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _permit = RunningPermit::enter(&state, 1); + scope.spawn(|| { + started_tx.send(()).unwrap(); + let _waiting = RunningPermit::enter(&state, 1); + acquired_tx.send(()).unwrap(); + }); + started_rx.recv().unwrap(); + panic!("simulated driver panic"); + })); + assert!(panicked.is_err()); + acquired_rx.recv_timeout(Duration::from_secs(1)).expect("waiter stayed blocked after unwind"); + }); + assert_eq!(*state.0.lock().unwrap_or_else(|e| e.into_inner()), 0); + } +} + #[cfg(test)] mod pipeline_claim_tests { use super::{claim_path_for, Claim, ClaimAcquire}; @@ -1723,13 +1775,7 @@ impl Pipelines { return; } } - { - let mut n = self.running.0.lock().unwrap(); - while *n >= self.most { - n = self.running.1.wait(n).unwrap(); - } - *n += 1; - } + let _permit = RunningPermit::enter(&self.running, self.most); let from_cache = cached.as_ref().and_then(|bytes| { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len() }; // a driver that cannot use the blob may compile from the DXIL itself and still @@ -1746,8 +1792,6 @@ impl Pipelines { } } if cached.is_some() && from_cache.is_none() && over_cap { - *self.running.0.lock().unwrap() -= 1; - self.running.1.notify_one(); self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); @@ -1770,8 +1814,6 @@ impl Pipelines { } pso }; - *self.running.0.lock().unwrap() -= 1; - self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); let done = match r { Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, From bf157ece1f9d8330ad62ac05101e0208baddaedf Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:54:42 -0800 Subject: [PATCH 161/265] PE loader: rewrite console wait instructions after first fault Repeated monitorx and mwaitx emulation can raise tens of thousands of illegal-instruction exceptions per second on Intel CPUs. Replace each aligned site atomically with nops or pause plus nops after its first fault. Serialize page protection changes, retry word replacement after interference, preserve adjacent rewrites, restore RX protection, flush the instruction cache, and recognize exceptions already in flight at a newly rewritten site. Adapted from PR #2618 by Tarosul and Claude Code (Claude Opus 5.5). That PR measured a retail workload improving from 1.24 to 2-3.5 presents/s. The Windows GNU cross-target check passes; native Windows tests and smoke were unavailable here. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/eh.rs | 211 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 210 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 727fda141d..d2a7674fee 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -246,6 +246,97 @@ unsafe fn bounded_cstr(p: usize, max: usize) -> String { String::from_utf8_lossy(&bytes).into_owned() } +/// Code-page protection is page-wide. Serialize these rare first-fault rewrites so two sites on +/// one page cannot restore stale protection over each other. +static CODE_REWRITE: Mutex<()> = Mutex::new(()); +/// A second thread may have faulted at a wait site before the first thread replaced it, then enter +/// the handler after replacement. Recognize that stale exception and retry the now-native bytes. +static REWRITTEN_WAITS: Mutex<Vec<(usize, Vec<u8>)>> = Mutex::new(Vec::new()); + +fn rewritten_wait(at: usize, code: &[u8]) -> bool { + let _serial = CODE_REWRITE.lock().unwrap_or_else(|e| e.into_inner()); + let mut sites = REWRITTEN_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(index) = sites.iter().position(|(site, _)| *site == at) else { return false }; + if code.starts_with(&sites[index].1) { + true + } else { + sites.swap_remove(index); + false + } +} + +fn remember_rewritten_wait(at: usize, replacement: &[u8]) { + let mut sites = REWRITTEN_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, bytes)) = sites.iter_mut().find(|(site, _)| *site == at) { + bytes.clear(); + bytes.extend_from_slice(replacement); + } else { + sites.push((at, replacement.to_vec())); + } +} + +#[cfg(test)] +fn forget_rewritten_waits(start: usize, end: usize) { + let _serial = CODE_REWRITE.lock().unwrap_or_else(|e| e.into_inner()); + REWRITTEN_WAITS.lock().unwrap_or_else(|e| e.into_inner()).retain(|(site, _)| *site < start || *site >= end); +} + +/// Atomically replace `expected` at `off` in an aligned instruction word. A failed compare is +/// retried from the newly observed word so an adjacent rewrite is never overwritten or mistaken +/// for success. +fn replace_code_word(cell: &std::sync::atomic::AtomicU64, off: usize, expected: &[u8], new: &[u8]) -> bool { + replace_code_word_from(cell, off, expected, new, cell.load(Ordering::Acquire)) +} + +fn replace_code_word_from(cell: &std::sync::atomic::AtomicU64, off: usize, expected: &[u8], new: &[u8], mut was: u64) -> bool { + loop { + let mut bytes = was.to_le_bytes(); + if bytes[off..off + new.len()] == *new { + return true; + } + if bytes[off..off + expected.len()] != *expected { + return false; + } + bytes[off..off + new.len()].copy_from_slice(new); + match cell.compare_exchange(was, u64::from_le_bytes(bytes), Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return true, + Err(now) => was = now, + } + } +} + +/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word. Threads +/// executing it observe either the complete old instruction or the complete replacement. +fn rewrite_code(at: usize, expected: &[u8], new: &[u8]) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let word = at & !7; + let off = at - word; + if expected.is_empty() || expected.len() != new.len() || off + new.len() > 8 { + return false; + } + let _serial = CODE_REWRITE.lock().unwrap_or_else(|e| e.into_inner()); + let mut old = 0u32; + unsafe { + if VirtualProtect(word as *const c_void, 8, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + return false; + } + let cell = &*(word as *const std::sync::atomic::AtomicU64); + let replaced = replace_code_word(cell, off, expected, new); + // Publish while CODE_REWRITE is still held. A stale exception lookup takes the same lock + // first, so it cannot observe the replacement without its registry entry. The bytes have + // changed even if restoring protection or flushing the cache below reports failure. + if replaced { + remember_rewritten_wait(at, new); + } + let mut ignored = 0u32; + let restored = VirtualProtect(word as *const c_void, 8, old, &mut ignored) != 0; + let flushed = FlushInstructionCache(GetCurrentProcess(), word as *const c_void, 8) != 0; + replaced && restored && flushed + } +} + fn is_writable(va: usize, bytes: usize) -> bool { use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; // a committed window of unified memory is read-write as a whole and is not asked about, as in @@ -325,6 +416,9 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics let n = code_bytes_at(rip, 16); let code = std::slice::from_raw_parts(rip as *const u8, n); let Some((what, len)) = crate::insn::decode(code) else { + if rewritten_wait(rip, code) { + return -1; + } crate::xlog_error!("illegal instruction in {}: code bytes {}", modules::describe_address(rip), crate::insn::hex(code)); return 0; }; @@ -351,9 +445,19 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) }; } } - ConsoleOnly::Monitorx => {} + ConsoleOnly::Monitorx => { + let mut expected = [0u8; 16]; + expected[..len].copy_from_slice(&code[..len]); + let replacement = &[0x90; 16][..len]; + rewrite_code(rip, &expected[..len], replacement); + } ConsoleOnly::Mwaitx => { std::hint::spin_loop(); + let mut expected = [0u8; 16]; + expected[..len].copy_from_slice(&code[..len]); + let mut replacement = [0x90u8; 16]; + replacement[0] = 0xF3; + rewrite_code(rip, &expected[..len], &replacement[..len]); } ConsoleOnly::Clzero => { // with an address-size prefix (0x67, among the prefixes before 0F 01 FC) the line @@ -1005,6 +1109,111 @@ mod tests { assert_eq!(find_gs_check(&[0x48; 64]), None); } + #[test] + fn monitorx_and_mwaitx_are_rewritten_at_their_first_fault() { + use std::sync::{atomic::AtomicBool, Arc}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE}; + let code = unsafe { VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize }; + assert_ne!(code, 0); + modules::register_mapped(Arc::new(modules::MappedModule { + name: "wait_rewrite.exe".into(), path: "wait_rewrite.exe".into(), base: code, size: 0x1000, entry_rva: 0, is_dll: false, + exports: Default::default(), tls_callbacks: Mutex::new(Vec::new()), no_thread_calls: AtomicBool::new(false), + initialized: AtomicBool::new(true), stack_reserve: 0, + })); + for (offset, before, after) in [ + (0x10usize, [0x0F, 0x01, 0xFA], [0x90, 0x90, 0x90]), + (0x20usize, [0x0F, 0x01, 0xFB], [0xF3, 0x90, 0x90]), + ] { + unsafe { + std::ptr::copy_nonoverlapping(before.as_ptr(), (code + offset) as *mut u8, before.len()); + let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed(); + ctx.Rip = (code + offset) as u64; + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, (code + offset + before.len()) as u64); + assert_eq!(std::slice::from_raw_parts((code + offset) as *const u8, before.len()), &after); + // A second exception may already be in flight with RIP at the old instruction. + // Retry the replacement at the same RIP instead of treating its NOPs as unknown. + ctx.Rip = (code + offset) as u64; + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, (code + offset) as u64); + } + } + forget_rewritten_waits(code, code + 0x1000); + modules::unregister_mapped(code); + unsafe { VirtualFree(code as *mut c_void, 0, MEM_RELEASE) }; + } + + #[test] + fn a_lost_compare_reloads_and_preserves_an_adjacent_rewrite() { + use std::sync::atomic::AtomicU64; + let original = u64::from_le_bytes([0x0F, 0x01, 0xFA, 0xCC, 0x0F, 0x01, 0xFB, 0xCC]); + let cell = AtomicU64::new(original); + let stale = cell.load(Ordering::Acquire); + // The other site wins after our initial load, exactly the raw PR's lost-CAS window. + cell.store(u64::from_le_bytes([0x0F, 0x01, 0xFA, 0xCC, 0xF3, 0x90, 0x90, 0xCC]), Ordering::Release); + assert!(replace_code_word_from(&cell, 0, &[0x0F, 0x01, 0xFA], &[0x90; 3], stale)); + assert_eq!(cell.load(Ordering::Acquire).to_le_bytes(), [0x90, 0x90, 0x90, 0xCC, 0xF3, 0x90, 0x90, 0xCC]); + } + + #[test] + fn concurrent_adjacent_rewrites_preserve_bytes_and_page_protection() { + use std::sync::{Arc, Barrier}; + use windows_sys::Win32::System::Memory::{ + VirtualAlloc, VirtualFree, VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE, + }; + let page = unsafe { VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize }; + assert_ne!(page, 0); + let first = [0x0F, 0x01, 0xFA]; + let second = [0x0F, 0x01, 0xFB]; + unsafe { + std::ptr::copy_nonoverlapping(first.as_ptr(), page as *mut u8, first.len()); + std::ptr::copy_nonoverlapping(second.as_ptr(), (page + 4) as *mut u8, second.len()); + let mut old = 0u32; + assert_ne!(VirtualProtect(page as *const c_void, 0x1000, PAGE_EXECUTE_READ, &mut old), 0); + } + // Enough simultaneous callers to force the raw PR's word-CAS and page-protection windows + // to overlap. Serialization makes every caller observe the completed adjacent update. + const THREADS: usize = 32; + let start = Arc::new(Barrier::new(THREADS + 1)); + let mut workers = Vec::new(); + for n in 0..THREADS { + let start = start.clone(); + workers.push(std::thread::spawn(move || { + start.wait(); + if n & 1 == 0 { + rewrite_code(page, &first, &[0x90; 3]) + } else { + rewrite_code(page + 4, &second, &[0xF3, 0x90, 0x90]) + } + })); + } + start.wait(); + for worker in workers { + assert!(worker.join().unwrap()); + } + unsafe { + assert_eq!(std::slice::from_raw_parts(page as *const u8, 3), &[0x90; 3]); + assert_eq!(std::slice::from_raw_parts((page + 4) as *const u8, 3), &[0xF3, 0x90, 0x90]); + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(VirtualQuery(page as *const c_void, &mut info, std::mem::size_of_val(&info)), 0); + assert_eq!(info.Protect, PAGE_EXECUTE_READ, "concurrent rewrites must restore RX, not stale RWX"); + forget_rewritten_waits(page, page + 0x1000); + VirtualFree(page as *mut c_void, 0, MEM_RELEASE); + } + } + + #[test] + fn a_rewrite_crossing_an_atomic_word_stays_emulated() { + let mut buf = [0xCCu8; 24]; + let word = (buf.as_mut_ptr() as usize + 7) & !7; + let at = word + 6; + let before = [0x0F, 0x01, 0xFA]; + unsafe { std::ptr::copy_nonoverlapping(before.as_ptr(), at as *mut u8, before.len()) }; + assert!(!rewrite_code(at, &before, &[0x90; 3])); + assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 3) }, &before); + } + /// `67 0F 01 FC`: CLZERO at EAX. rax's upper half set, and memory mapped at both the 64- and /// the 32-bit address: only the 32-bit one's line is zeroed. #[test] From 2a577d7d6aa839dbaa9f69508ed36fc14ee4b146 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:57:51 -0800 Subject: [PATCH 162/265] XAudio2: preallocate decoded Opus output At a fresh decoder boundary, packet durations determine the complete PCM sample count before decoding. Reserve that bounded count once for mono, stereo, and duration-validated multistream buffers; skip speculation when an MFT may still hold output from an earlier call. Adapted from PR #2696 by Decodere and Google Antigravity (Gemini 4 Neon). The Windows GNU cross-target library/test check passes; native Windows audio execution was unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/opus.rs | 69 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/opus.rs b/crates/xcl/src/hle/opus.rs index be83ecd301..8ef3045ad7 100644 --- a/crates/xcl/src/hle/opus.rs +++ b/crates/xcl/src/hle/opus.rs @@ -1600,7 +1600,9 @@ impl Decoder { if packets.is_empty() { return Err("buffer contains no valid RFC 6716 Opus packets".to_string()); } - let mut out = Vec::new(); + // An MFT can defer output from an earlier call. Size only at a fresh decoder boundary; + // otherwise old output could make this buffer's packet-duration estimate an undercount. + let stream_boundary = self.streams.iter().all(|stream| stream.timestamp_100ns() == 0); let timing = timing.filter(|t| { // Reuse the voice's configured MFTs only at a decoder stream boundary // and when the Ogg headers describe the same channel layout and gain. @@ -1609,8 +1611,13 @@ impl Decoder { && t.head.coupled_count == self.coupled_count && t.head.mapping == self.mapping && gain_scale(t.head.output_gain) == self.output_gain_scale - && self.streams.iter().all(|s| s.timestamp_100ns() == 0) + && stream_boundary }); + let capacity = stream_boundary + .then(|| expected_buffer_samples(&packets, timing.as_ref(), self.output_rate, self.channels, self.multistream)) + .flatten() + .unwrap_or(0); + let mut out = Vec::with_capacity(capacity); if let Some(timing) = timing { for pkt in &packets { let start = out.len(); @@ -1634,6 +1641,30 @@ impl Decoder { } } +/// Bound speculative allocation even when a caller presents an enormous packet sequence. +const MAX_PREALLOC_SAMPLES: usize = 16 << 20; + +/// Exact decoded sample count for valid packets at the supported output rates. Multistream +/// decoding validates that every substream has this leading stream's duration before producing +/// output; Ogg timing already accumulated the same per-packet durations while parsing pages. +fn expected_buffer_samples( + packets: &[Cow<'_, [u8]>], + timing: Option<&OggTiming>, + output_rate: u32, + channels: u16, + multistream: bool, +) -> Option<usize> { + let samples_48k = match timing { + Some(timing) => timing.decoded_48k, + None => packets.iter().try_fold(0u64, |total, packet| { + let packet = parse_packet(packet, multistream)?; + Some(total.saturating_add(u64::from(packet.total_samples_48k))) + })?, + }; + let frames = u128::from(samples_48k).saturating_mul(u128::from(output_rate)) / 48_000; + Some(frames.saturating_mul(u128::from(channels)).min(MAX_PREALLOC_SAMPLES as u128) as usize) +} + fn gain_scale(gain: i16) -> f32 { 10.0f32.powf(f32::from(gain) / (20.0 * 256.0)) } @@ -2154,6 +2185,7 @@ pub(crate) mod tests { let mut dec = Decoder::new(1, 48_000, MONO_HYBRID_20MS_HEAD).unwrap(); let pcm = dec.decode_buffer(&block, 2048).unwrap(); assert_eq!(pcm.len(), 5 * 960 - 312); + assert_eq!(pcm.capacity(), 5 * 960, "decode_buffer reserves the full decoded timeline once"); // Flush resets pre-skip and decoder state cleanly dec.flush(); @@ -2171,6 +2203,39 @@ pub(crate) mod tests { assert_eq!(d24.decode_packet(MONO_HYBRID_20MS[1], &mut out24).unwrap(), 480); } + #[test] + fn decoded_output_preallocation_is_exact_and_bounded() { + let mono: Vec<Cow<'_, [u8]>> = MONO_HYBRID_20MS.iter().map(|&packet| Cow::Borrowed(packet)).collect(); + assert_eq!(expected_buffer_samples(&mono, None, 48_000, 1, false), Some(5 * 960)); + assert_eq!(expected_buffer_samples(&mono, None, 24_000, 1, false), Some(5 * 480)); + + let stereo = [Cow::Borrowed(STEREO_CELT_20MS[0])]; + assert_eq!(expected_buffer_samples(&stereo, None, 48_000, 2, false), Some(960 * 2)); + + // Six equal-duration substreams: sizing reads the leading self-delimited TOC, while + // split_multistream_into validates every substream has that duration before decoding. + let multistream: &[u8] = &[ + 0xFC, 0x02, 0x11, 0x22, + 0xF1, 0x02, 0x11, 0x22, 0x33, 0x44, + 0xF2, 0x02, 0x03, 0x11, 0x22, 0x33, 0x44, 0x55, + 0xF3, 0xC2, 0x02, 0x01, 0x02, 0xAA, 0xBB, 0xCC, 0x00, 0x00, + 0xF3, 0x02, 0x02, 0x11, 0x22, 0x33, 0x44, + 0xF8, 0x99, 0x88, + ]; + let packets = [Cow::Borrowed(multistream)]; + assert_eq!(expected_buffer_samples(&packets, None, 48_000, 6, true), Some(960 * 6)); + + let timing = OggTiming { + head: parse_opus_head(&build_opus_head(2, 48_000, 312, 0)).unwrap(), + decoded_48k: 1920, + end_48k: 1724, + }; + assert_eq!(expected_buffer_samples(&[], Some(&timing), 24_000, 2, false), Some(960 * 2)); + let huge = OggTiming { decoded_48k: u64::MAX, end_48k: u64::MAX, ..timing }; + assert_eq!(expected_buffer_samples(&[], Some(&huge), u32::MAX, u16::MAX, true), Some(MAX_PREALLOC_SAMPLES)); + assert_eq!(expected_buffer_samples(&[Cow::Borrowed(&[0xFB, 0])], None, 48_000, 1, false), None); + } + #[test] fn split_self_delimited_into_reuses_buffer_and_matches_owned_split() { // 6-stream packet exercising self-delimited codes 0, 1, 2, 3-VBR-padded, 3-CBR + standard tail. From d4f03aab28810d9fb67d2ec3761128355dd05371 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:01:49 -0800 Subject: [PATCH 163/265] D3D12.X: share idle command allocator spares A retail world run measured hundreds of free PC allocators stranded in separate title-allocator namespaces while non-local memory kept growing. Let an allocator without an idle spare take a same-type spare from another namespace before creating another native allocator. Fence probes run outside the pool lock. Exact backing snapshots and donor reset tokens reject concurrent use or an unlocked native Reset, then the candidate is transferred and claimed through the requester's normal reset generation. Adapted from PR #2725. The Windows GNU cross-target library/test check passes; native Windows tests and smoke were unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 103 +++++++++++++++++++++++- 1 file changed, 100 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 2649d631b5..263fe38469 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -1026,6 +1026,51 @@ fn commit_idle_resets( valid } +/// Free spares owned by another title allocator of the same type. The backing snapshot lets the +/// caller ask the driver fences outside STATE, then reject a candidate whose use changed meanwhile. +fn shared_aside_probes(s: &State, alloc: usize, ty: i32) -> Vec<(usize, usize, Option<BackingProbe>)> { + s.aside.iter().filter(|(owner, _)| { + **owner != alloc && s.types.get(owner) == Some(&ty) && !s.resetting.contains_key(owner) + }).flat_map(|(&owner, aside)| { + aside.iter().copied().filter(move |&raw| raw != owner).map(move |raw| { + (owner, raw, s.backings.get(&raw).map(|backing| BackingProbe::new(raw, backing))) + }) + }).collect() +} + +/// Transfer one still-free shared spare into `alloc`'s namespace. A donor with a reset in progress +/// is skipped: its unlocked driver call may already target the candidate. +fn take_shared_aside( + s: &mut State, + alloc: usize, + ty: i32, + candidates: &[(usize, usize, Option<BackingProbe>)], + free: &HashSet<usize>, +) -> bool { + for (owner, raw, observed) in candidates { + if !free.contains(raw) + || s.types.get(owner) != Some(&ty) + || s.resetting.contains_key(owner) + || s.aside.get(owner).is_none_or(|aside| !aside.contains(raw)) + { + continue; + } + let stable = match (observed, s.backings.get(raw)) { + (Some(probe), Some(backing)) => probe.matches(backing), + (None, None) => true, + _ => false, + }; + if !stable { + continue; + } + let aside = s.aside.get_mut(owner).unwrap(); + aside.remove(aside.iter().position(|candidate| candidate == raw).unwrap()); + s.aside.entry(alloc).or_default().push(*raw); + return true; + } + false +} + /// The title resets its allocator `alloc`. `None`: reset it as it is (nothing holds a /// recording on it, or this is off). `Some(hr)`: done here – the PC allocator in use was put /// aside with its recordings and another one took its place. @@ -1035,15 +1080,20 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option<HRESULT> { } let a = alloc as usize; let claim = loop { - let (mine, probes) = { + let (mine, probes, shared) = { let mut g = STATE.lock().unwrap(); let s = g.get_or_insert_with(State::default); if s.resetting.contains_key(&a) { return Some(crate::util::E_FAIL); } - namespace_probes(s, a) + let (mine, probes) = namespace_probes(s, a); + let shared = s.types.get(&a).map(|&ty| shared_aside_probes(s, a, ty)).unwrap_or_default(); + (mine, probes, shared) }; - let free: HashSet<_> = probes.iter().filter(|probe| unsafe { probe.free() }).map(|probe| probe.raw).collect(); + let mut free: HashSet<_> = probes.iter().filter(|probe| unsafe { probe.free() }).map(|probe| probe.raw).collect(); + free.extend(shared.iter().filter_map(|(_, raw, probe)| { + probe.as_ref().is_none_or(|probe| unsafe { probe.free() }).then_some(*raw) + })); let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return None }; if !namespace_matches(s, a, &mine, &probes) { @@ -1078,6 +1128,11 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option<HRESULT> { let needed = s.backings.get(&candidate).is_none_or(|backing| !backing.already_reset); break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: true, needed } }; } + if take_shared_aside(s, a, ty, &shared, &free) { + // Restart so the transferred candidate participates in this namespace's snapshot and + // reset token exactly like a spare it had always owned. + continue; + } let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&alloc).cloned() else { return Some(crate::util::E_FAIL) }; let token = reserve_reset(s, a).unwrap(); break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Create { owner, ty } }; @@ -1851,6 +1906,48 @@ mod tests { assert_eq!((s.made, s.swaps), (0, 1)); } + #[test] + fn a_free_spare_from_another_allocator_is_transferred_safely() { + let (requester, donor, busy_owner, other_owner) = (0x1100usize, 0x2200usize, 0x3300usize, 0x4400usize); + let (spare, busy, other, list) = (0x2210usize, 0x3310usize, 0x4410usize, 0x9900usize); + let mut s = State::default(); + for alloc in [requester, donor, busy_owner] { + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + } + s.types.insert(other_owner, D3D12_COMMAND_LIST_TYPE_COMPUTE.0); + s.aside.insert(donor, vec![donor, spare]); + s.aside.insert(busy_owner, vec![busy]); + s.aside.insert(other_owner, vec![other]); + backing_mut(&mut s, spare); + move_list(&mut s, list, busy); + + let candidates = shared_aside_probes(&s, requester, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + assert!(candidates.iter().any(|&(owner, raw, _)| owner == donor && raw == spare)); + assert!(!candidates.iter().any(|&(_, raw, _)| raw == donor || raw == other)); + let free = candidates.iter().filter_map(|(_, raw, probe)| { + probe.as_ref().is_none_or(|probe| unsafe { probe.free() }).then_some(*raw) + }).collect(); + assert!(take_shared_aside(&mut s, requester, D3D12_COMMAND_LIST_TYPE_DIRECT.0, &candidates, &free)); + assert_eq!(s.aside.get(&donor), Some(&vec![donor]), "the donor's own allocator stays in its namespace"); + assert_eq!(s.aside.get(&requester), Some(&vec![spare])); + + // A snapshot that was free cannot transfer a backing after a recording starts using it. + let raced = 0x2220usize; + s.aside.get_mut(&donor).unwrap().push(raced); + backing_mut(&mut s, raced); + let candidates = shared_aside_probes(&s, requester, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let free = HashSet::from([raced]); + move_list(&mut s, list + 1, raced); + assert!(!take_shared_aside(&mut s, requester, D3D12_COMMAND_LIST_TYPE_DIRECT.0, &candidates, &free)); + assert!(s.aside[&donor].contains(&raced)); + + // Nor can a candidate be taken while its donor may already be resetting it unlocked. + let token = reserve_reset(&mut s, donor).unwrap(); + assert!(shared_aside_probes(&s, requester, D3D12_COMMAND_LIST_TYPE_DIRECT.0) + .iter().all(|(owner, _, _)| *owner != donor)); + cancel_reset(&mut s, donor, token); + } + #[test] fn retired_recording_keeps_lifetime_and_submit_pin_until_exact_reuse() { let (list, old, next) = (0x7ffe_7601usize, 0x7ffe_7602usize, 0x7ffe_7603usize); From e526619c9a19a1493787f200652dfbe11e913e0d Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:04:01 -0800 Subject: [PATCH 164/265] Shaders: serialize identical in-process pipeline builds When the driver cache path or its cross-process claim is unavailable, identical preparation workers could enter the driver together and multiply its peak memory and compile contention. Key in-flight work by the complete pipeline cache identity and make later local workers wait for the active attempt. The RAII slot is released and waiters are notified on every return and panic; completed identities are not retained, so later cache-validation passes and retries after failures remain unchanged. Adapted from PR #2712 by Bloxive. Co-authored-by: Bloxive <ptmshu23@gmail.com> Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/shaders.rs | 137 +++++++++++++++++++++++++++++++++++++- 1 file changed, 136 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 3028cf1a34..07f45075d0 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1214,6 +1214,9 @@ struct Pipelines { /// programs over `max_dxil` with no blob yet, and their DXIL bytes capped: AtomicUsize, capped_bytes: AtomicUsize, + /// intra-process builds keyed by full pipeline cache identity, so duplicate threads wait + /// rather than entering the driver together when the disk claim is unavailable + inflight: (Mutex<InflightBuilds>, std::sync::Condvar), /// driver compiles running and the most at once (`XCL_PIPELINE_THREADS`, 4): each of the /// biggest takes ~1.5 GB in the driver – fifteen at once took 24 GB running: (Mutex<usize>, std::sync::Condvar), @@ -1224,6 +1227,131 @@ struct Pipelines { cache_dir: Option<PathBuf>, } +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct PipelineCacheIdentity { + dxil_len: usize, + dxil_hash_a: u64, + dxil_hash_b: u64, + flags: i32, + node_mask: u32, + chained: bool, + sampler_words: Vec<u32>, + cache_path: Option<PathBuf>, +} + +impl PipelineCacheIdentity { + fn new( + dxil: &[u8], + flags: i32, + node_mask: u32, + chained: bool, + sampler_words: Vec<u32>, + cache_path: Option<PathBuf>, + ) -> Self { + let mut alt = 0x9e37_79b9_7f4a_7c15u64; + for &byte in dxil { + alt ^= u64::from(byte); + alt = alt.wrapping_mul(0xbf58_476d_1ce4_e5b9); + } + Self { + dxil_len: dxil.len(), + dxil_hash_a: shader::fnv64(dxil), + dxil_hash_b: alt, + flags, + node_mask, + chained, + sampler_words, + cache_path, + } + } +} + +#[derive(Default)] +struct InflightBuilds { + active: HashSet<PipelineCacheIdentity>, +} + +struct InflightGuard<'a> { + state: &'a (Mutex<InflightBuilds>, std::sync::Condvar), + id: PipelineCacheIdentity, +} + +impl<'a> InflightGuard<'a> { + fn enter(state: &'a (Mutex<InflightBuilds>, std::sync::Condvar), id: PipelineCacheIdentity) -> Self { + let mut builds = state.0.lock().unwrap_or_else(|e| e.into_inner()); + while builds.active.contains(&id) { + builds = state.1.wait(builds).unwrap_or_else(|e| e.into_inner()); + } + builds.active.insert(id.clone()); + Self { state, id } + } +} + +impl Drop for InflightGuard<'_> { + fn drop(&mut self) { + let mut builds = self.state.0.lock().unwrap_or_else(|e| e.into_inner()); + builds.active.remove(&self.id); + self.state.1.notify_all(); + } +} + +#[cfg(test)] +mod inflight_build_tests { + use super::{InflightBuilds, InflightGuard, PipelineCacheIdentity}; + use std::path::PathBuf; + use std::sync::{mpsc, Condvar, Mutex}; + use std::time::Duration; + + fn identity(dxil: &[u8], flags: i32, node: u32, chained: bool, samplers: &[u32], path: &str) -> PipelineCacheIdentity { + PipelineCacheIdentity::new(dxil, flags, node, chained, samplers.to_vec(), Some(PathBuf::from(path))) + } + + #[test] + fn identity_covers_every_pipeline_input() { + let base = identity(b"abc", 0, 0, false, &[1, 2], "a.pso"); + assert_eq!(base, identity(b"abc", 0, 0, false, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abd", 0, 0, false, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 1, 0, false, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 2, false, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 0, true, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 0, false, &[1, 3], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 0, false, &[1, 2], "b.pso")); + assert_ne!(base, PipelineCacheIdentity::new(b"abc", 0, 0, false, vec![1, 2], None)); + } + + #[test] + fn same_build_waits_while_distinct_builds_and_failures_can_proceed() { + let state = (Mutex::new(InflightBuilds::default()), Condvar::new()); + let base = identity(b"program", 0, 0, false, &[], "same.pso"); + let other = identity(b"other", 0, 0, false, &[], "other.pso"); + let first = InflightGuard::enter(&state, base.clone()); + drop(InflightGuard::enter(&state, other)); + + let (started_tx, started_rx) = mpsc::channel(); + let (done_tx, done_rx) = mpsc::channel(); + std::thread::scope(|scope| { + scope.spawn(|| { + started_tx.send(()).unwrap(); + let _same = InflightGuard::enter(&state, base.clone()); + done_tx.send(()).unwrap(); + }); + started_rx.recv().unwrap(); + assert!(done_rx.recv_timeout(Duration::from_millis(20)).is_err(), "same pipeline did not wait"); + drop(first); + done_rx.recv_timeout(Duration::from_secs(1)).expect("waiter stayed blocked"); + }); + + let retry = identity(b"retry", 0, 0, false, &[], "retry.pso"); + let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _failed = InflightGuard::enter(&state, retry.clone()); + panic!("simulated build failure"); + })); + assert!(panicked.is_err()); + drop(InflightGuard::enter(&state, retry)); + assert!(state.0.lock().unwrap_or_else(|e| e.into_inner()).active.is_empty()); + } +} + enum ClaimAcquire { Acquired(Claim), HeldElsewhere, @@ -1647,6 +1775,7 @@ impl Pipelines { split_pieces: AtomicUsize::new(0), capped: AtomicUsize::new(0), capped_bytes: AtomicUsize::new(0), + inflight: (Mutex::new(InflightBuilds::default()), std::sync::Condvar::new()), running: (Mutex::new(0), std::sync::Condvar::new()), most, max_dxil, @@ -1694,7 +1823,11 @@ impl Pipelines { fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option<PathBuf>) { use windows::Win32::Graphics::Direct3D12::*; - let key: (bool, Vec<u32>) = (chained, samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect()); + let sampler_words: Vec<u32> = samplers + .iter() + .flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])) + .collect(); + let key = (chained, sampler_words.clone()); let rs = { let mut g = self.signatures.lock().unwrap(); match g.get(&key) { @@ -1743,6 +1876,8 @@ impl Pipelines { drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); return; } + let identity = PipelineCacheIdentity::new(dxil, desc.Flags.0, desc.NodeMask, chained, sampler_words, path.clone()); + let _inflight = InflightGuard::enter(&self.inflight, identity); // A valid blob may be used by many processes, but validation itself can fall through to // a full driver compile when the blob is stale. Claim before either path so only one // process can validate/rebuild/remove this exact cache entry at a time. From 202c9623e335f333b3c9d631fda4025977cab1ff Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:04:17 -0800 Subject: [PATCH 165/265] D3D12.X: separate indirect dispatch-chain root ABI PR #2633 changed every split pipeline to a root CBV, including direct dispatches that regressed on RADV. Prepare an indirect-only variant instead: retain the existing direct root constants and legacy driver-cache identity while defining a distinct CBV root layout and cache namespace for indirect pipeline states. This is deliberately wiring-only. The indirect pipeline must be built as a separate PSO because D3D12 pipeline states are tied to their root signatures. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/pso.rs | 73 ++++++++++++++++++++++++++----- crates/xcl/src/hle/d3d12x/real.rs | 36 +++++++++++++++ 2 files changed, 97 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index ceb5aad9cc..807d4f1e25 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1417,7 +1417,15 @@ pub fn static_sampler_desc(k: u32, (w, comparison): &StaticSampler) -> D3D12_STA /// The ABI root signature with the pipeline's static samplers (registers 0.., space 1). pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler]) -> Result<ID3D12RootSignature, String> { - abi_signature(dev, graphics, samplers, false) + abi_signature(dev, graphics, samplers, None) +} + +/// The per-dispatch slab data used by a split compute pipeline. Direct command-list dispatches +/// keep root constants; an indirect-only pipeline can use a root CBV without changing their ABI. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ChainSlabBinding { + RootConstants, + RootCbv, } /// Record all piece dispatches after the six common root views have been bound. @@ -1464,10 +1472,37 @@ pub(crate) unsafe fn record_dispatch_chain<'a>( } pub(crate) fn dispatch_chain_root_signature(dev: &ID3D12Device, samplers: &[StaticSampler]) -> Result<ID3D12RootSignature, String> { - abi_signature(dev, false, samplers, true) + abi_signature(dev, false, samplers, Some(ChainSlabBinding::RootConstants)) +} + +/// A split-pipeline root signature specialized for indirect dispatch. Its pipeline states must +/// remain separate from those made by `dispatch_chain_root_signature` because their root ABIs differ. +#[allow(dead_code)] +pub(crate) fn dispatch_chain_indirect_root_signature(dev: &ID3D12Device, samplers: &[StaticSampler]) -> Result<ID3D12RootSignature, String> { + abi_signature(dev, false, samplers, Some(ChainSlabBinding::RootCbv)) +} + +fn chain_slab_parameter(binding: ChainSlabBinding) -> D3D12_ROOT_PARAMETER1 { + let (ty, value) = match binding { + ChainSlabBinding::RootConstants => ( + D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + D3D12_ROOT_PARAMETER1_0 { Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, RegisterSpace: 2, Num32BitValues: 8, + } }, + ), + ChainSlabBinding::RootCbv => ( + D3D12_ROOT_PARAMETER_TYPE_CBV, + D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, RegisterSpace: 2, Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + } }, + ), + }; + D3D12_ROOT_PARAMETER1 { ParameterType: ty, Anonymous: value, ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL } } -fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], split: bool) -> Result<ID3D12RootSignature, String> { +fn abi_signature( + dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], split: Option<ChainSlabBinding>, +) -> Result<ID3D12RootSignature, String> { let statics: Vec<D3D12_STATIC_SAMPLER_DESC> = samplers.iter().enumerate().map(|(k, s)| static_sampler_desc(k as u32, s)).collect(); unsafe { // u0 io, u1 res, u2..u5 the memory windows (`gpu::uma`; unused ones need no binding) @@ -1480,7 +1515,7 @@ fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }) .collect(); - if split { + if let Some(binding) = split { params.push(D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, Anonymous: D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 { @@ -1488,13 +1523,7 @@ fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], } }, ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); - params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, - Anonymous: D3D12_ROOT_PARAMETER1_0 { Constants: D3D12_ROOT_CONSTANTS { - ShaderRegister: 0, RegisterSpace: 2, Num32BitValues: 8, - } }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }); + params.push(chain_slab_parameter(binding)); } let mut flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; if graphics { @@ -1521,7 +1550,27 @@ fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], #[cfg(test)] mod slab_tests { - use super::dispatch_slabs; + use super::{chain_slab_parameter, dispatch_slabs, ChainSlabBinding}; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + D3D12_ROOT_PARAMETER_TYPE_CBV, + }; + + #[test] + fn direct_and_indirect_chain_slab_parameters_have_distinct_abis() { + let direct = chain_slab_parameter(ChainSlabBinding::RootConstants); + let indirect = chain_slab_parameter(ChainSlabBinding::RootCbv); + assert_eq!(direct.ParameterType, D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS); + assert_eq!(indirect.ParameterType, D3D12_ROOT_PARAMETER_TYPE_CBV); + unsafe { + assert_eq!(direct.Anonymous.Constants.ShaderRegister, 0); + assert_eq!(direct.Anonymous.Constants.RegisterSpace, 2); + assert_eq!(direct.Anonymous.Constants.Num32BitValues, 8); + assert_eq!(indirect.Anonymous.Descriptor.ShaderRegister, 0); + assert_eq!(indirect.Anonymous.Descriptor.RegisterSpace, 2); + assert_eq!(indirect.Anonymous.Descriptor.Flags, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE); + } + } #[test] fn slabs_cover_a_dispatch_once_within_their_size() { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 0608092274..90a49f8eac 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4958,6 +4958,14 @@ pub(crate) mod driver_cache { static REFERENCE_BLOBS: AtomicBool = AtomicBool::new(false); static ACTIVE_KEEPS: Mutex<Option<std::collections::HashSet<PathBuf>>> = Mutex::new(None); + /// Split pipelines with different root ABIs cannot share a persisted driver blob. + #[allow(dead_code)] + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum ChainRoot { + DirectConstants, + IndirectCbv, + } + /// AMD's cached-PSO blobs name entries in the driver's own cache instead of containing /// self-sufficient code. They are not safe to carry across runs unless explicitly enabled. pub fn note_vendor(vendor: u32) { @@ -4993,6 +5001,25 @@ pub(crate) mod driver_cache { /// Include the linked-adapter node in persisted driver state. Node zero keeps legacy names. pub fn name_for_root_node(dxil: &[u8], flags: i32, chained: bool, samplers: &[StaticSampler], node_mask: u32) -> String { let ext = if chained { "chain.pso" } else { "pso" }; + name_for_root_node_with_ext(dxil, flags, samplers, node_mask, ext) + } + + /// The direct split ABI retains `.chain.pso`; the indirect-only CBV ABI has a separate + /// namespace so a driver blob can never be offered with the wrong root signature. + #[allow(dead_code)] + pub fn name_for_chain_root_node( + dxil: &[u8], flags: i32, root: ChainRoot, samplers: &[StaticSampler], node_mask: u32, + ) -> String { + let ext = match root { + ChainRoot::DirectConstants => "chain.pso", + ChainRoot::IndirectCbv => "indirect-chain.pso", + }; + name_for_root_node_with_ext(dxil, flags, samplers, node_mask, ext) + } + + fn name_for_root_node_with_ext( + dxil: &[u8], flags: i32, samplers: &[StaticSampler], node_mask: u32, ext: &str, + ) -> String { let mut base = format!("{:016x}-{:x}-{:x}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags); if node_mask != 0 { base += &format!("-n{node_mask:x}"); @@ -5398,6 +5425,15 @@ pub(crate) mod driver_cache { ); } + #[test] + fn direct_and_indirect_chain_roots_have_distinct_compatible_names() { + let direct = name_for_chain_root_node(b"same dxil", 3, ChainRoot::DirectConstants, &[], 0); + assert_eq!(direct, name_for_root_node(b"same dxil", 3, true, &[], 0)); + assert_ne!(direct, name_for_chain_root_node(b"same dxil", 3, ChainRoot::IndirectCbv, &[], 0)); + assert!(name_for_chain_root_node(b"same dxil", 3, ChainRoot::IndirectCbv, &[], 0) + .ends_with(".indirect-chain.pso")); + } + #[test] fn disk_blobs_default_off_only_for_amd_and_can_be_overridden() { assert!(reference_blob_vendor(0x1002)); From 14524632d1847c704eb16b9ea172d0afc8bc5b71 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:06:45 -0800 Subject: [PATCH 166/265] D3D12.X: complete graphics driver cache identity Translated graphics PSOs could share a driver-blob key even when one retained a native geometry shader that the other did not. Hash and size the final GS bytes, including native GS bytecode, rather than only XCL's generated rectangle shader. Scope bounded RAM entries to the effective per-device root signature. Persisted paths remain adapter-scoped and encode the static-sampler ABI, while in-process entries can no longer cross devices. Stream-output declarations are pointer-backed state not represented by the descriptor key, so leave those pipelines uncached instead of aliasing different layouts. An unreadable nonempty GS is also conservatively uncached. This follows the cache-identity findings in PR #902 and issue #2508. The Windows GNU cross-target library/test check passes; native Windows tests and smoke were unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 57 ++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 90a49f8eac..2f276215d9 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5834,19 +5834,21 @@ fn keep_driver_blob<K: Copy + Eq + std::hash::Hash>( } /// The driver's compiled form of translated graphics pipelines (`GetCachedBlob`), -/// keyed by `(full_state_and_shader_hash, total_dxil_bytes)`, up to `GRAPHICS_BLOBS_MAX`. -static GRAPHICS_BLOBS: DriverBlobs<(u64, usize)> = DriverBlobs::new(); +/// keyed by `(full_state_and_shader_hash, total_dxil_bytes, effective_root_signature)`, up to +/// `GRAPHICS_BLOBS_MAX`. The root address scopes RAM entries to the device; persisted paths are +/// already adapter-scoped and encode the root's static-sampler ABI in the state hash. +static GRAPHICS_BLOBS: DriverBlobs<(u64, usize, usize)> = DriverBlobs::new(); const GRAPHICS_BLOBS_MAX: usize = 256 << 20; -fn graphics_blob(key: (u64, usize)) -> Option<std::sync::Arc<Vec<u8>>> { +fn graphics_blob(key: (u64, usize, usize)) -> Option<std::sync::Arc<Vec<u8>>> { GRAPHICS_BLOBS.get(key) } -fn forget_graphics_blob(key: (u64, usize)) { +fn forget_graphics_blob(key: (u64, usize, usize)) { GRAPHICS_BLOBS.forget(key); } -fn forget_graphics_blob_if(key: (u64, usize), expected: &std::sync::Arc<Vec<u8>>) -> bool { +fn forget_graphics_blob_if(key: (u64, usize, usize), expected: &std::sync::Arc<Vec<u8>>) -> bool { GRAPHICS_BLOBS.forget_if(key, expected) } @@ -5857,7 +5859,7 @@ unsafe fn graphics_blob_key( copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs_dxil: &[u8], ps_dxil: Option<&[u8]>, - rect_gs: Option<&[u8]>, + gs_dxil: Option<&[u8]>, samplers: &[crate::gpu::recomp::pso::StaticSampler], ) -> (u64, usize) { let mut h = 0xcbf2_9ce4_8422_2325u64; @@ -5879,7 +5881,7 @@ unsafe fn graphics_blob_key( } else { feed_u64(&mut h, 0); } - if let Some(gs) = rect_gs { + if let Some(gs) = gs_dxil { feed_u64(&mut h, crate::gpu::shader::fnv64(gs)); feed_u64(&mut h, gs.len() as u64); } else { @@ -5964,10 +5966,19 @@ unsafe fn graphics_blob_key( feed_u32(&mut h, copy.SampleDesc.Quality); feed_u32(&mut h, copy.NodeMask); feed_u32(&mut h, copy.Flags.0 as u32); - let total_bytes = vs_dxil.len() + ps_dxil.map_or(0, <[u8]>::len) + rect_gs.map_or(0, <[u8]>::len); + let total_bytes = vs_dxil.len() + ps_dxil.map_or(0, <[u8]>::len) + gs_dxil.map_or(0, <[u8]>::len); (h, total_bytes) } +/// Stream-output declarations contain pointer-backed arrays that are not represented in the +/// graphics blob key. Keep those PSOs out of this cache rather than aliasing distinct layouts. +fn graphics_blob_cacheable(requested: bool, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, gs_readable: bool) -> bool { + requested + && desc.StreamOutput.NumEntries == 0 + && desc.StreamOutput.NumStrides == 0 + && (desc.GS.BytecodeLength == 0 || gs_readable) +} + #[cfg(test)] mod graphics_blob_tests { use super::*; @@ -5993,6 +6004,22 @@ mod graphics_blob_tests { } } + #[test] + fn graphics_blob_cache_skips_pointer_backed_stream_output() { + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + assert!(graphics_blob_cacheable(true, &d, false)); + assert!(!graphics_blob_cacheable(false, &d, false)); + d.StreamOutput.NumEntries = 1; + assert!(!graphics_blob_cacheable(true, &d, false)); + d.StreamOutput.NumEntries = 0; + d.StreamOutput.NumStrides = 1; + assert!(!graphics_blob_cacheable(true, &d, false)); + d.StreamOutput.NumStrides = 0; + d.GS.BytecodeLength = 4; + assert!(!graphics_blob_cacheable(true, &d, false), "an unreadable native GS has no safe key"); + assert!(graphics_blob_cacheable(true, &d, true)); + } + #[test] fn graphics_blob_key_ignores_struct_padding_bytes() { unsafe { @@ -6322,10 +6349,13 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const if debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash) { copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } - let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + rect_gs.as_ref().map_or(0, Vec::len); - let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers); + let final_gs = shader_bytes(©.GS); + let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + final_gs.map_or(0, <[u8]>::len); + let disk_key = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), final_gs, &samplers); + let gkey = (disk_key.0, disk_key.1, rs as usize); + let cacheable = graphics_blob_cacheable(cacheable, ©, final_gs.is_some()); let mut cached = cacheable.then(|| graphics_blob(gkey)).flatten(); - let disk = cacheable.then(|| driver_cache::graphics_path(gkey.0, gkey.1)).flatten(); + let disk = cacheable.then(|| driver_cache::graphics_path(disk_key.0, disk_key.1)).flatten(); let from_disk = cached.is_none(); let mut loaded = None; if from_disk { @@ -8101,9 +8131,10 @@ unsafe fn translated_graphics_stream_once(this: *mut c_void, desc: *const c_void let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let stream = rewrite_graphics_stream(&subs, rs, &vs_c.dxil, ps_dxil.as_deref(), rect_gs.as_deref(), no_stencil, no_cull); let without_rect_gs = rect_gs.as_ref().map(|_| rewrite_graphics_stream(&subs, rs, &vs_c.dxil, ps_dxil.as_deref(), None, no_stencil, no_cull)); - let key = two_pass_identity::graphics_stream_key(&stream.0, &samplers, crate::gpu::recomp::pso::mem_windows()); + let disk_key = two_pass_identity::graphics_stream_key(&stream.0, &samplers, crate::gpu::recomp::pso::mem_windows()); + let key = disk_key.map(|(hash, bytes)| (hash, bytes, rs as usize)); let mut cached = key.and_then(graphics_blob); - let disk = key.and_then(|k| driver_cache::graphics_path(k.0, k.1)); + let disk = disk_key.and_then(|k| driver_cache::graphics_path(k.0, k.1)); let from_disk = key.is_some() && cached.is_none(); let mut loaded = None; if from_disk { From 277c0f9ae3a21008a194c36bb503c4a76a180ea6 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:08:58 -0800 Subject: [PATCH 167/265] Recompiler: charge split pieces to the shader cache The translated-shader LRU subtracted dispatch-chain piece capacities during eviction but omitted them when admitting an entry. Large split programs could therefore retain substantially more than the configured byte budget. Use the same complete capacity calculation at insertion and eviction, with a regression test whose whole shader fits only when its split pieces are incorrectly ignored. This closes the cache-accounting gap identified in issue #2508. The Windows GNU cross-target library/test check passes; native Windows tests and GPU execution were unavailable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/pso.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 807d4f1e25..0d0e6aad66 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -934,6 +934,7 @@ impl ShaderCache { let bytes = blob.len() + key.cache_dir.capacity() + shader.dxil.capacity() + + shader.dispatch_chain.as_ref().map_or(0, |chain| chain.pieces.iter().map(Vec::capacity).sum()) + shader.samplers.capacity() * std::mem::size_of::<StaticSampler>(); if bytes > self.limit { return; @@ -2144,6 +2145,22 @@ mod shader_cache_tests { assert!(cache.get(&key(0), b"a").is_none()); } + #[test] + fn shader_cache_charges_split_piece_capacity_on_insert() { + let mut split = compiled(7); + split.dispatch_chain = Some(Arc::new(crate::gpu::dxil::kernel::DispatchChain { + dwords_per_group: 8, + pieces: vec![vec![0u8; 4096], vec![0u8; 2048]], + })); + let split = Arc::new(split); + let entry = ShaderEntry { key: key(1), blob: b"split".to_vec(), shader: split.clone(), gen: 0 }; + let piece_bytes: usize = split.dispatch_chain.as_ref().unwrap().pieces.iter().map(Vec::capacity).sum(); + let mut cache = ShaderCache::new(entry.bytes() - piece_bytes); + cache.insert(key(1), b"split", split); + assert!(cache.entries.is_empty(), "a split shader larger than the byte budget is not admitted"); + assert_eq!(cache.bytes, 0); + } + #[test] fn shader_cache_coalesces_concurrent_same_key_compiles() { use std::sync::atomic::{AtomicUsize, Ordering}; From 16e5856369074de74714de3343be1dfd026e6d76 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:07:58 -0800 Subject: [PATCH 168/265] D3D12.X: gate medium AMD compute driver compiles Cold 128-256 KiB compute PSOs took tens of seconds and over 1 GiB each when amdxc64 compiled 16 at once. Give that AMD-only class a RAM-scaled lane separate from the existing huge and giant lanes, without reducing NVIDIA or graphics parallelism. Two-pass pipelines take one outer turn for both driver calls. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 3 + crates/xcl/src/hle/d3d12x/real.rs | 96 +++++++++++++++++++++++++++---- 2 files changed, 89 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 7660f15e99..8a63a5ddbf 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder `XCL_PSO_TRACE=1` logs every driver compile. A huge compute program the driver refuses is logged with the driver's verdict (`the driver refused the compute PSO of record HASH … with 0x…`): its dispatches are skipped. + On AMD, cold 128–256 KiB compute pipelines use a separate lane (three background / four + wanted at once on hosts with at least 32 GiB RAM, two / three below that), configurable with + `XCL_MEDIUM_PSO_CONCURRENCY` and `XCL_MEDIUM_PSO_WANTED_CONCURRENCY`. - With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`. XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with those on which the GPU completed at least one operation. For each, it names the translated diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 2f276215d9..026d39bce0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -20,8 +20,8 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::ffi::c_void; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, LazyLock, Mutex, OnceLock}; use serde::Serialize; use windows::core::{Interface, PCSTR}; @@ -171,6 +171,7 @@ pub struct D3d12Stats { } static ADAPTER: Mutex<String> = Mutex::new(String::new()); +static ADAPTER_VENDOR: AtomicU32 = AtomicU32::new(0x1414); static UNKNOWN_IIDS: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new()); static FALLBACK_PSO: AtomicU64 = AtomicU64::new(0); static FAILED_PSO: AtomicU64 = AtomicU64::new(0); @@ -581,6 +582,7 @@ pub fn init() -> Result<String, String> { } }; driver_cache::note_vendor(vendor); + ADAPTER_VENDOR.store(vendor, Ordering::Release); if debug { // the debug layer's messages into XCL's log (they otherwise go to a debugger only) if let Ok(q) = device.cast::<ID3D12InfoQueue1>() { @@ -4337,6 +4339,23 @@ impl Drop for SlotGuard { } static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 0, wanted_most: 0 }; +const AMD_MEDIUM_COMPUTE: usize = 128 << 10; +const MEDIUM_COMPUTE_END: usize = 256 << 10; +static MEDIUM_COMPILES: LazyLock<Slots> = LazyLock::new(|| { + let (default_most, default_wanted_most) = medium_pso_defaults(total_physical_ram()); + let most = env_count(std::env::var("XCL_MEDIUM_PSO_CONCURRENCY").ok().as_deref(), default_most, 1, 64); + Slots { + n: Mutex::new(0), + cv: std::sync::Condvar::new(), + most, + wanted_most: env_count( + std::env::var("XCL_MEDIUM_PSO_WANTED_CONCURRENCY").ok().as_deref(), + default_wanted_most.max(most), + most, + 64, + ), + } +}); const GIANT_DRIVER_COMPILE: usize = 4 << 20; static GIANT_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 1 }; @@ -4344,6 +4363,27 @@ fn compile_slots(bytes: usize) -> &'static Slots { if bytes >= GIANT_DRIVER_COMPILE { &GIANT_COMPILES } else { &BIG_COMPILES } } +fn total_physical_ram() -> Option<u64> { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullTotalPhys) +} + +fn medium_pso_defaults(total_phys: Option<u64>) -> (usize, usize) { + if total_phys.is_some_and(|n| n < 32u64 << 30) { (2, 3) } else { (3, 4) } +} + +/// AMD's compiler takes tens of seconds and over 1 GiB per cold 128–256 KiB compute PSO. +/// Keep that AMD-only class separate from the existing >=256 KiB gate: graphics and other +/// vendors retain their current parallelism, while a multi-minute huge compile cannot block it. +fn medium_compute_compile(kind: &str, bytes: usize, huge_bytes: usize, vendor: u32) -> bool { + vendor == 0x1002 + && (kind == "compute" || kind == "compute retry") + && bytes >= AMD_MEDIUM_COMPUTE + && bytes < huge_bytes.min(MEDIUM_COMPUTE_END) +} + /// A driver compile of `bytes` of DXIL through `build`: a huge one on an `xcl-pso*` worker /// waits for its slot first (`big_compile_turn`; not a title thread's, nor one the title waits /// for). Logs its time, size and whether it was gated. @@ -4361,18 +4401,23 @@ fn pso_trace() -> bool { /// as in `[SHADER]` lines and `xcl shaders --measure-pso`) and whether a driver blob was supplied. /// Also returns the time spent in the driver alone (not waiting for a slot). fn driver_compile_identified<R>(kind: &str, bytes: usize, gate: bool, record: Option<u64>, cached: bool, build: impl FnOnce() -> R) -> (R, std::time::Duration) { - let huge = gate && bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let huge_bytes = huge_pso_bytes(); + let worker = std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let medium = gate && worker && medium_compute_compile(kind, bytes, huge_bytes, ADAPTER_VENDOR.load(Ordering::Acquire)); + let huge = gate && worker && bytes >= huge_bytes; + let gated = medium || huge; let waited = std::time::Instant::now(); - let gate_stall = huge.then(|| crate::stall::span(crate::stall::StallKind::DriverCompileGate)).flatten(); - let _slot = huge.then(|| { + let gate_stall = gated.then(|| crate::stall::span(crate::stall::StallKind::DriverCompileGate)).flatten(); + let _slot = gated.then(|| { let _waiting = DRIVER_BUILDS.waiting(); - big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted) + let slots = if medium { &*MEDIUM_COMPILES } else { compile_slots(bytes) }; + big_compile_turn(slots, || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted) }); drop(gate_stall); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; - let log = pso_trace() || bytes >= huge_pso_bytes(); + let log = pso_trace() || bytes >= huge_bytes || medium; if log { let record = record.map_or_else( || if cached { ", driver blob supplied".to_string() } else { String::new() }, @@ -4385,7 +4430,7 @@ fn driver_compile_identified<R>(kind: &str, bytes: usize, gate: bool, record: Op let r = build(); let took = started.elapsed(); if log { - crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_pso_bytes(), huge, waited)); + crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_bytes || medium, gated, waited)); } else if took >= std::time::Duration::from_secs(1) { // a slow one below the huge size, logged without XCL_PSO_TRACE too (a title thread's // graphics pipelines took 2 - 5 s each, unlogged) @@ -4602,6 +4647,31 @@ mod big_compile_tests { assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE), &GIANT_COMPILES)); } + #[test] + fn medium_compute_class_is_amd_only_and_respects_the_huge_override() { + let amd = 0x1002; + let nvidia = 0x10de; + assert!(!medium_compute_compile("compute", AMD_MEDIUM_COMPUTE - 1, 256 << 10, amd)); + assert!(medium_compute_compile("compute", AMD_MEDIUM_COMPUTE, 256 << 10, amd)); + assert!(medium_compute_compile("compute retry", 217 << 10, 256 << 10, amd)); + assert!(!medium_compute_compile("compute", MEDIUM_COMPUTE_END, 256 << 10, amd)); + assert!(!medium_compute_compile("graphics", 180 << 10, 256 << 10, amd)); + assert!(!medium_compute_compile("compute", 180 << 10, 256 << 10, nvidia)); + assert!(!medium_compute_compile("compute", 180 << 10, 128 << 10, amd), + "a lower XCL_HUGE_PSO_BYTES routes this size through the existing huge lane"); + assert!(!std::ptr::eq(&*MEDIUM_COMPILES, &BIG_COMPILES), + "medium compute must not occupy the existing huge slot"); + } + + #[test] + fn medium_compute_concurrency_scales_down_below_32_gib() { + assert_eq!(medium_pso_defaults(Some(16u64 << 30)), (2, 3)); + assert_eq!(medium_pso_defaults(Some((32u64 << 30) - 1)), (2, 3)); + assert_eq!(medium_pso_defaults(Some(32u64 << 30)), (3, 4)); + assert_eq!(medium_pso_defaults(Some(64u64 << 30)), (3, 4)); + assert_eq!(medium_pso_defaults(None), (3, 4)); + } + #[test] fn only_a_cold_compute_compile_takes_a_slot() { assert!(!gate_compute_driver_compile(true), "the cached-blob attempt bypasses the gate"); @@ -7131,10 +7201,16 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let desc: [usize; 2] = [stream.0.len(), stream.0.as_ptr() as usize]; // the mesh pass and its compute pass: one turn for both let bytes = stream.shader_bytes() + tp.cs.len(); - let gate = bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let huge_bytes = huge_pso_bytes(); + let medium = bytes < huge_bytes + && medium_compute_compile("compute", tp.cs.len(), huge_bytes, ADAPTER_VENDOR.load(Ordering::Acquire)); + let gate = (bytes >= huge_bytes || medium) && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); let gate_stall = gate.then(|| crate::stall::span(crate::stall::StallKind::DriverCompileGate)).flatten(); - let _slot = gate.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + let _slot = gate.then(|| { + let slots = if medium { &*MEDIUM_COMPILES } else { compile_slots(bytes) }; + big_compile_turn(slots, || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted) + }); drop(gate_stall); if gate { crate::xlog_info!("D3D12.X: two-pass {kind} PSO ({bytes} B DXIL) gated, waited {} ms", waited.elapsed().as_millis()); From bd7d1f96acda9bd334016e8ea324d54e9dbb06ef Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:09:18 -0800 Subject: [PATCH 169/265] D3D12.X: retain accepted disk pipeline blobs A successful warm disk lookup counted the hit and dropped its loaded Arc without offering that generation to the bounded RAM cache. Repeated creates of the same compute, graphics, or two-pass key could therefore reread and copy the same file. Admit the accepted Arc under the existing byte cap while holding capture-reservation ownership in the same lock order. Concurrent admissions charge bytes once, active builders retain ownership, and stale rejection removes only the exact Arc generation used by the driver. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 98 ++++++++++++++++++++++++++++--- 1 file changed, 90 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 026d39bce0..ae0e957e17 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4953,6 +4953,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL loaded = disk.as_deref().and_then(driver_cache::load); cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); } + let rejected_generation = cached.clone(); if let Some(b) = &cached { copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } else if mode == ComputeBuild::CachedWhole { @@ -4970,7 +4971,9 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL let mut persist_took = in_driver; if hr < 0 && cached.is_some() { // a blob the driver does not take (another root signature at the same address…): compiled - forget_compute_blob(key); + if let Some(expected) = rejected_generation.as_ref() { + forget_compute_blob_if(key, expected); + } if from_disk { driver_cache::note(false, loaded.take()); } @@ -4995,6 +4998,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL keep_driver_blob(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, key, dxil.len(), disk.as_deref(), persist_took, || read_pso_cached_blob(*ppv)); } else if reused && from_disk { + COMPUTE_BLOBS.admit(key, cached.as_ref().unwrap().clone(), COMPUTE_BLOBS_MAX); driver_cache::note(true, loaded.take()); } (hr, in_driver, reused) @@ -5662,7 +5666,8 @@ impl<K: Copy + Eq + std::hash::Hash> DriverBlobs<K> { } fn reserve(&self, key: K) -> bool { - if self.get(key).is_some() { + let blobs = self.blobs.lock().unwrap(); + if blobs.as_ref().is_some_and(|(map, _)| map.contains_key(&key)) { return false; } let mut guard = self.keeping.lock().unwrap(); @@ -5670,6 +5675,25 @@ impl<K: Copy + Eq + std::hash::Hash> DriverBlobs<K> { !persisted.contains_key(&key) && active.insert(key) } + /// Admit the exact disk generation accepted by the driver without copying it. Holding both + /// locks excludes a builder reservation between the presence check and insertion. + fn admit(&self, key: K, blob: std::sync::Arc<Vec<u8>>, limit: usize) -> bool { + let mut blobs = self.blobs.lock().unwrap(); + let mut keeping = self.keeping.lock().unwrap(); + let (active, persisted) = keeping.get_or_insert_with(|| (HashSet::new(), HashMap::new())); + if active.contains(&key) { + return false; + } + let (map, total) = blobs.get_or_insert_with(|| (HashMap::new(), 0)); + if map.contains_key(&key) || blob.len() > limit.saturating_sub(*total) { + return false; + } + *total += blob.len(); + persisted.insert(key, std::sync::Arc::downgrade(&blob)); + map.insert(key, blob); + true + } + fn finish(&self, key: K, blob: Option<std::sync::Arc<Vec<u8>>>, limit: usize, persisted: bool) { let mut generation = None; if let Some(blob) = blob { @@ -5715,6 +5739,7 @@ impl<K: Copy + Eq + std::hash::Hash> DriverBlobs<K> { removed } + #[cfg_attr(not(test), allow(dead_code))] fn forget(&self, key: K) { if let Some((map, total)) = self.blobs.lock().unwrap().as_mut() { if let Some(blob) = map.remove(&key) { @@ -5751,10 +5776,15 @@ fn compute_blob(key: (u64, usize, i32)) -> Option<std::sync::Arc<Vec<u8>>> { COMPUTE_BLOBS.get(key) } +#[cfg_attr(not(test), allow(dead_code))] fn forget_compute_blob(key: (u64, usize, i32)) { COMPUTE_BLOBS.forget(key); } +fn forget_compute_blob_if(key: (u64, usize, i32), expected: &std::sync::Arc<Vec<u8>>) -> bool { + COMPUTE_BLOBS.forget_if(key, expected) +} + #[cfg(test)] mod compute_blob_tests { #[test] @@ -5856,6 +5886,53 @@ mod compute_blob_tests { assert!(std::sync::Arc::ptr_eq(&cache.get(7).unwrap(), &fresh)); assert!(cache.forget_if(7, &fresh), "the exact generation remains invalidatable"); } + + #[test] + fn concurrent_disk_admission_counts_one_exact_generation() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let cache = std::sync::Arc::new(super::DriverBlobs::new()); + let blob = std::sync::Arc::new(b"accepted".to_vec()); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(9)); + let admitted = std::sync::Arc::new(AtomicUsize::new(0)); + let threads: Vec<_> = (0..8).map(|_| { + let (cache, blob, barrier, admitted) = + (cache.clone(), blob.clone(), barrier.clone(), admitted.clone()); + std::thread::spawn(move || { + barrier.wait(); + if cache.admit(11u64, blob, 32) { + admitted.fetch_add(1, Ordering::Relaxed); + } + }) + }).collect(); + barrier.wait(); + for thread in threads { + thread.join().unwrap(); + } + + assert_eq!(admitted.load(Ordering::Relaxed), 1); + let accepted = cache.get(11).unwrap(); + assert!(std::sync::Arc::ptr_eq(&accepted, &blob)); + assert_eq!(cache.blobs.lock().unwrap().as_ref().unwrap().1, blob.len()); + let other = std::sync::Arc::new(b"other".to_vec()); + assert!(!cache.forget_if(11, &other)); + assert_eq!(cache.blobs.lock().unwrap().as_ref().unwrap().1, blob.len()); + assert!(cache.forget_if(11, &accepted)); + assert_eq!(cache.blobs.lock().unwrap().as_ref().unwrap().1, 0); + assert!(cache.reserve(11), "exact invalidation also releases persisted ownership"); + cache.finish(11, None, 32, false); + } + + #[test] + fn active_builder_wins_over_disk_admission() { + let cache = super::DriverBlobs::new(); + assert!(cache.reserve(5u64)); + assert!(!cache.admit(5, std::sync::Arc::new(b"disk".to_vec()), 32)); + let built = std::sync::Arc::new(b"built".to_vec()); + cache.finish(5, Some(built.clone()), 32, false); + let kept = cache.get(5).unwrap(); + assert!(std::sync::Arc::ptr_eq(&kept, &built)); + assert_eq!(cache.blobs.lock().unwrap().as_ref().unwrap().1, built.len()); + } } /// Read `GetCachedBlob` from either an adopted or raw PC `ID3D12PipelineState`. @@ -5914,10 +5991,6 @@ fn graphics_blob(key: (u64, usize, usize)) -> Option<std::sync::Arc<Vec<u8>>> { GRAPHICS_BLOBS.get(key) } -fn forget_graphics_blob(key: (u64, usize, usize)) { - GRAPHICS_BLOBS.forget(key); -} - fn forget_graphics_blob_if(key: (u64, usize, usize), expected: &std::sync::Arc<Vec<u8>>) -> bool { GRAPHICS_BLOBS.forget_if(key, expected) } @@ -6432,12 +6505,15 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const loaded = disk.as_deref().and_then(driver_cache::load); cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); } + let rejected_generation = cached.clone(); let build = create_graphics_pso_cached( &mut copy, cached.as_deref().map(Vec::as_slice), rect_gs.is_some(), || { - forget_graphics_blob(gkey); + if let Some(expected) = rejected_generation.as_ref() { + forget_graphics_blob_if(gkey, expected); + } if from_disk { driver_cache::note(false, loaded.take()); } @@ -6450,6 +6526,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const keep_driver_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, gkey, bytes, disk.as_deref(), build.built_in_driver, || read_pso_cached_blob(*ppv)); } else if build.reused && from_disk { + GRAPHICS_BLOBS.admit(gkey, cached.as_ref().unwrap().clone(), GRAPHICS_BLOBS_MAX); driver_cache::note(true, loaded.take()); } if hr < 0 { @@ -7237,6 +7314,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: cloaded = cdisk.as_deref().and_then(driver_cache::load); ccached = cloaded.as_ref().map(driver_cache::LoadedBlob::shared); } + let rejected_cgeneration = ccached.clone(); if let Some(b) = &ccached { cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } @@ -7247,7 +7325,9 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: }); let mut cpersist_took = cin_driver; if hc < 0 && ccached.is_some() { - forget_compute_blob(ckey); + if let Some(expected) = rejected_cgeneration.as_ref() { + forget_compute_blob_if(ckey, expected); + } if cfrom_disk { driver_cache::note(false, cloaded.take()); } @@ -7265,6 +7345,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: keep_driver_blob(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, ckey, tp.cs.len(), cdisk.as_deref(), cpersist_took, || read_pso_cached_blob(compute)); } else if creused && cfrom_disk { + COMPUTE_BLOBS.admit(ckey, ccached.as_ref().unwrap().clone(), COMPUTE_BLOBS_MAX); driver_cache::note(true, cloaded.take()); } drop(_slot); @@ -8240,6 +8321,7 @@ unsafe fn translated_graphics_stream_once(this: *mut c_void, desc: *const c_void keep_driver_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, k, stream.shader_bytes(), disk.as_deref(), build.built_in_driver, || read_pso_cached_blob(*ppv)); } else if build.reused && from_disk { + GRAPHICS_BLOBS.admit(key.unwrap(), cached.as_ref().unwrap().clone(), GRAPHICS_BLOBS_MAX); driver_cache::note(true, loaded.take()); } if hr < 0 { From acb7ced484ab5d102ba7b2eeadce43acc419151c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:13:27 -0800 Subject: [PATCH 170/265] D3D12.X: cache positive mirror range lookups Every mirrored vertex or index bind and draw searched the append-only mirror table behind one global mutex. Once a title created a mirror, repeated hot-path lookups serialized even though existing entries never change. Keep a complete ordered mirror snapshot per thread and answer positive lookups locally. Misses still lock and refresh from the authoritative table, preserving first-match range selection and immediate discovery before creating a mirror; the no-mirror case rejects from the existing byte counter. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 52 ++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 963c041e04..d6691e2025 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4380,10 +4380,41 @@ unsafe fn gpu_va(list: *mut c_void, va: u64, bytes: usize, what: &str, mirror: b static MIRRORS: Mutex<Vec<(u64, usize, usize)>> = Mutex::new(Vec::new()); /// bytes of mirrors made (never freed) static MIRROR_BYTES: AtomicU64 = AtomicU64::new(0); +/// Append generation. Incremented while `MIRRORS` is locked, before publishing a new range, so a +/// lookup that observes it refreshes under that lock and cannot retain a stale negative result. +static MIRROR_GENERATION: AtomicU64 = AtomicU64::new(0); +std::thread_local! { + /// Mirrors are append-only. A full ordered snapshot answers both hits and authoritative misses + /// without the global lock until the append generation changes. + static MIRROR_LOOKUP: std::cell::RefCell<(u64, Vec<(u64, usize, usize)>)> = const { std::cell::RefCell::new((0, Vec::new())) }; +} + +fn mirror_in(ranges: &[(u64, usize, usize)], va: u64, bytes: usize) -> Option<usize> { + ranges.iter() + .find(|&&(start, len, _)| va >= start && va + bytes as u64 <= start + len as u64) + .map(|&(start, _, mirror)| mirror + (va - start) as usize) +} + +fn cached_mirror( + cache: &mut (u64, Vec<(u64, usize, usize)>), generation: u64, va: u64, bytes: usize, + refresh: impl FnOnce() -> Vec<(u64, usize, usize)>, +) -> Option<usize> { + if cache.0 != generation { + cache.1 = refresh(); + cache.0 = generation; + } + mirror_in(&cache.1, va, bytes) +} /// Where `[va, va + bytes)` is in a mirror, if it is in one. fn mirrored(va: u64, bytes: usize) -> Option<usize> { - MIRRORS.lock().unwrap().iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64).map(|&(s, _, m)| m + (va - s) as usize) + let generation = MIRROR_GENERATION.load(Ordering::Acquire); + if generation == 0 { + return None; + } + MIRROR_LOOKUP.with(|cache| { + cached_mirror(&mut cache.borrow_mut(), generation, va, bytes, || MIRRORS.lock().unwrap().clone()) + }) } /// The mirror address of the title's buffer at `va`; its range's mirror is made (and filled @@ -4415,6 +4446,9 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option<usize> { None => u.alloc(len, 0x1_0000)? as usize, }; std::ptr::copy_nonoverlapping(start as *const u8, p as *mut u8, len); + // Invalidate cached misses before publishing while still holding the lock. A lookup that sees + // the new generation blocks on `g` until this range is present in the refreshed snapshot. + MIRROR_GENERATION.fetch_add(1, Ordering::Release); g.push((start, len, p)); let total = MIRROR_BYTES.fetch_add(len as u64, Ordering::Relaxed) + len as u64; if g.len() <= 8 || g.len().is_power_of_two() { @@ -5306,6 +5340,22 @@ mod tests { use super::*; use std::sync::Arc; + #[test] + fn mirror_snapshot_keeps_order_and_refreshes_only_on_miss() { + let first = (100, 100, 1_000); + let second = (150, 100, 2_000); + let mut cache = (0, Vec::new()); + assert_eq!(cached_mirror(&mut cache, 1, 220, 10, || vec![first, second]), Some(2_070)); + // The complete ordered snapshot was retained, not just the range found above: where the + // ranges overlap, lookup still chooses the first global entry without refreshing. + assert_eq!(cached_mirror(&mut cache, 1, 160, 10, || panic!("positive hit locked")), Some(1_060)); + assert_eq!(cached_mirror(&mut cache, 1, 400, 10, || panic!("unchanged miss locked")), None); + + let third = (500, 50, 3_000); + assert_eq!(cached_mirror(&mut cache, 2, 510, 10, || vec![first, second, third]), Some(3_010)); + assert_eq!(mirror_in(&cache.1, 550, 1), None, "ranges are half-open"); + } + /// An internal wait shows in the watchdog's summary while its fence is short of the value, /// and is gone from it once the fence gets there. #[test] From 2a6a8ba238da0732d96fe256fed90d6b0d08f8a9 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:13:08 -0800 Subject: [PATCH 171/265] D3D12.X: run ready split pipelines through ExecuteIndirect A split compute pipeline previously always used its expensive whole form for ExecuteIndirect. For the measured one-Dispatch, one-command shape, generate bounded piece commands on the GPU once that whole fallback is already available. The slicer emits either every piece slab or only the whole dispatch, so it cannot lose work. Generated commands remain owned by the recording until its allocator resets, including when ABI binding fails. The first use and all other command shapes retain the existing whole-form path. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/pso.rs | 152 +++++++++++++++++- crates/xcl/src/hle/d3d12x/bind.rs | 45 ++++++ crates/xcl/src/hle/d3d12x/device_x.rs | 4 + .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 106 +++++++++++- 4 files changed, 304 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 0d0e6aad66..a26e9d0dc9 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1472,6 +1472,145 @@ pub(crate) unsafe fn record_dispatch_chain<'a>( } } +/// Bytes of one indirect chain command: eight slab constants followed by Dispatch arguments. +pub(crate) const CHAIN_COMMAND_BYTES: u32 = 44; + +pub(crate) fn chain_command_signature(dev: &ID3D12Device, rs: &ID3D12RootSignature) -> Result<ID3D12CommandSignature, String> { + let args = [ + D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { + Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { RootParameterIndex: 7, DestOffsetIn32BitValues: 0, Num32BitValuesToSet: 8 } } }, + D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }, + ]; + let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: CHAIN_COMMAND_BYTES, NumArgumentDescs: 2, pArgumentDescs: args.as_ptr(), NodeMask: 0 }; + let mut sig = None; + unsafe { dev.CreateCommandSignature(&desc, rs, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?; + sig.ok_or_else(|| "CreateCommandSignature".into()) +} + +pub(crate) fn dispatch_command_signature(dev: &ID3D12Device) -> Result<ID3D12CommandSignature, String> { + static MADE: Mutex<Option<(usize, ID3D12CommandSignature)>> = Mutex::new(None); + let mut made = MADE.lock().unwrap(); + if let Some((_, sig)) = made.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) { + return Ok(sig.clone()); + } + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }; + let mut sig = None; + unsafe { dev.CreateCommandSignature(&desc, None, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?; + let sig: ID3D12CommandSignature = sig.ok_or("CreateCommandSignature")?; + *made = Some((windows::core::Interface::as_raw(dev) as usize, sig.clone())); + Ok(sig) +} + +const INDIRECT_SLICER: &str = r#" +#define RS "RootConstants(num32BitConstants=3, b0), SRV(t0), UAV(u0)" +cbuffer C : register(b0) { uint rounds; uint most; uint pieces; }; +ByteAddressBuffer args : register(t0); +RWByteAddressBuffer cmds : register(u0); +void put(uint r, uint3 n, uint3 o) { + for (uint i = 0; i < pieces; i++) { + uint at = (r * pieces + i) * 44; + cmds.Store4(at, uint4(n, i)); + cmds.Store4(at + 16, uint4(o, 0)); + cmds.Store3(at + 32, n); + } +} +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint3 g = min(args.Load3(0), 65535); + uint3 s; + s.x = min(g.x, max(most, 1)); + s.y = s.x == g.x ? min(g.y, max(most / max(g.x, 1), 1)) : 1; + s.z = s.x == g.x && s.y == g.y ? min(g.z, max(most / max(g.x, 1) / max(g.y, 1), 1)) : 1; + uint3 c = (g + s - 1) / s; + bool partial = any(g == 0) ? false : c.x > rounds || c.y > rounds / max(c.x, 1) || c.z > rounds / max(c.x * c.y, 1); + uint r = 0; + if (!partial && all(g != 0)) + for (uint oz = 0; oz < g.z; oz += s.z) + for (uint oy = 0; oy < g.y; oy += s.y) + for (uint ox = 0; ox < g.x; ox += s.x) { + uint3 o = uint3(ox, oy, oz); + put(r++, min(s, g - o), o); + } + for (; r < rounds; r++) put(r, 0, 0); + uint at = (rounds * pieces * 44 + 7) & ~7u; + cmds.Store3(at, partial ? g : 0); +} +"#; + +pub(crate) fn chain_tail_offset(rounds: u32, pieces: u32) -> u64 { + (u64::from(rounds) * u64::from(pieces) * u64::from(CHAIN_COMMAND_BYTES)).next_multiple_of(8) +} + +fn indirect_slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static MADE: Mutex<Option<(usize, ID3D12RootSignature, ID3D12PipelineState)>> = Mutex::new(None); + let mut made = MADE.lock().unwrap(); + if let Some((_, rs, pso)) = made.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) { + return Ok((rs.clone(), pso.clone())); + } + let dxil = super::dxc::compile(INDIRECT_SLICER, "main", "cs_6_0", &[])?; + unsafe { + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("indirect slicer root signature: {e}"))?; + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).map_err(|e| format!("indirect slicer pipeline: {e}"))?; + *made = Some((windows::core::Interface::as_raw(dev) as usize, rs.clone(), pso.clone())); + Ok((rs, pso)) + } +} + +pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32, pieces: u32) -> Option<ID3D12Resource> { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: chain_tail_offset(rounds, pieces) + 12, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() + }; + let mut resource = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, CreationNodeMask: 1, VisibleNodeMask: 1, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut resource).ok()?; + resource +} + +pub(crate) unsafe fn record_indirect_slicer( + list: &ID3D12GraphicsCommandList, args: u64, rounds: u32, most: u64, pieces: u32, out: &ID3D12Resource, +) -> Result<(), String> { + let mut dev = None; + list.GetDevice(&mut dev).map_err(|e| e.to_string())?; + let (rs, pso) = indirect_slicer(&dev.ok_or("device")?)?; + let constants = [rounds, most.min(u64::from(u32::MAX)) as u32, pieces]; + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, args); + list.SetComputeRootUnorderedAccessView(2, out.GetGPUVirtualAddress()); + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(out), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }) } }]); + Ok(()) +} + +pub(crate) unsafe fn record_dispatch_chain_indirect<'a>( + list: &ID3D12GraphicsCommandList, sig: &ID3D12CommandSignature, commands: &ID3D12Resource, rounds: u32, + scratch: &ID3D12Resource, pieces: impl IntoIterator<Item = &'a ID3D12PipelineState> + Clone, +) { + let n = pieces.clone().into_iter().count() as u32; + list.SetComputeRootUnorderedAccessView(6, scratch.GetGPUVirtualAddress()); + for r in 0..rounds { + for (i, piece) in pieces.clone().into_iter().enumerate() { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]); + list.SetPipelineState(piece); + let offset = (u64::from(r) * u64::from(n) + i as u64) * u64::from(CHAIN_COMMAND_BYTES); + list.ExecuteIndirect(sig, 1, commands, offset, None::<&ID3D12Resource>, 0); + } + } +} + pub(crate) fn dispatch_chain_root_signature(dev: &ID3D12Device, samplers: &[StaticSampler]) -> Result<ID3D12RootSignature, String> { abi_signature(dev, false, samplers, Some(ChainSlabBinding::RootConstants)) } @@ -1551,7 +1690,7 @@ fn abi_signature( #[cfg(test)] mod slab_tests { - use super::{chain_slab_parameter, dispatch_slabs, ChainSlabBinding}; + use super::{chain_slab_parameter, chain_tail_offset, dispatch_slabs, ChainSlabBinding, CHAIN_COMMAND_BYTES}; use windows::Win32::Graphics::Direct3D12::{ D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, D3D12_ROOT_PARAMETER_TYPE_CBV, @@ -1573,6 +1712,17 @@ mod slab_tests { } } + #[test] + fn indirect_whole_arguments_follow_aligned_piece_commands() { + for (rounds, pieces) in [(1, 2), (16, 9), (1024, 64)] { + let commands = u64::from(rounds * pieces * CHAIN_COMMAND_BYTES); + let tail = chain_tail_offset(rounds, pieces); + assert!(tail >= commands); + assert_eq!(tail % 8, 0); + assert!(tail - commands < 8); + } + } + #[test] fn slabs_cover_a_dispatch_once_within_their_size() { for grid in [[1, 1, 1], [2, 3, 2], [240, 135, 1], [65_535, 2, 1], [5, 1, 7]] { diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3414e2e27b..9f3818d3a5 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -287,6 +287,18 @@ fn signature_dispatches(sig: usize) -> bool { DISPATCH_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) } +/// Command signatures made of one Dispatch argument, keyed to their stride. +static DISPATCH_ONLY: Mutex<Option<HashMap<usize, u32>>> = Mutex::new(None); + +pub(super) fn note_dispatch_only_signature(sig: usize, stride: Option<u32>) { + let mut signatures = DISPATCH_ONLY.lock().unwrap(); + let signatures = signatures.get_or_insert_with(Default::default); + match stride { + Some(stride) => { signatures.insert(sig, stride); } + None => { signatures.remove(&sig); } + } +} + /// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a /// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root /// arguments themselves cannot be – skipped, logged) @@ -300,6 +312,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } let (pso, bound_unbuilt) = super::pso_async::resolve_wait_bound(raw_pso); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); + let args_off_title = args_off; let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if !gfx && !compute { // A pipeline still being built (or whose build failed): its stand-in draws nothing, and @@ -359,6 +372,27 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return; } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + if compute && max == 1 && count_buf == 0 && DISPATCH_ONLY.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&sig)) { + let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(false), |address| { + super::real::dispatch_chain::execute_indirect(list, pso, with(this, |s| s.allocator), address, + || bind_abi(this, list, pso, false)) + }); + match chained { + Ok(true) => { + count(DISPATCHES); + return; + } + Ok(false) => {} + Err(e) => { + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: split ExecuteIndirect skipped: {e}"); + } + return; + } + } + } match bind_abi(this, list, pso, gfx) { Ok(()) => { if compute { @@ -401,6 +435,17 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } +unsafe fn indirect_address(resource: usize, title_offset: u64, pc_offset: u64) -> Option<u64> { + match super::real::console_buffer(resource) { + Some((base, size)) if title_offset.checked_add(12).is_some_and(|end| end <= size as u64) => { + super::real::uma_va_of(base + title_offset as usize) + } + Some(_) => None, + None => Some(ID3D12Resource::from_raw_borrowed(&(resource as *mut c_void))?.GetGPUVirtualAddress()) + .filter(|&address| address != 0).and_then(|address| address.checked_add(pc_offset)), + } +} + /// XCL's own buffer for `fresh_indirect_arguments` (device, buffer): COMMON between its uses static ARGUMENT_ORDER: Mutex<Option<(usize, ID3D12Resource)>> = Mutex::new(None); diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 139b6100cd..7bd0829645 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1321,6 +1321,10 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::bind::note_signature_dispatches(*ppv as usize, list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)); + let stride = u32::from_le_bytes(pc[..4].try_into().unwrap()); + let dispatch_only = list.len() == 1 && list[0][0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32 + && stride >= 12 && stride % 4 == 0; + super::bind::note_dispatch_only_signature(*ppv as usize, dispatch_only.then_some(stride)); } hr } diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 6708d3203a..c146cfa335 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -83,6 +83,10 @@ impl<T: Clone> WholeBuild<T> { } } } + + fn ready(&self) -> Option<Result<T, HRESULT>> { + self.result.get().cloned() + } } /// A transient whole-form OOM is retried after memory has had time to drain. @@ -94,6 +98,7 @@ struct Chain { words: u32, whole_code: Vec<u8>, whole: WholeBuild<ID3D12PipelineState>, + indirect_signature: OnceLock<ID3D12CommandSignature>, } impl Chain { @@ -148,7 +153,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let mut pieces = built.into_iter().collect::<Option<Vec<_>>>()?.into_iter(); let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, - whole_code: whole.to_vec(), whole: WholeBuild::new() }); + whole_code: whole.to_vec(), whole: WholeBuild::new(), indirect_signature: OnceLock::new() }); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -181,6 +186,7 @@ struct Recording { scratch: Arc<Scratch>, first: ID3D12PipelineState, chain: Arc<Chain>, + _indirect_commands: Option<ID3D12Resource>, } static RECORDINGS: LazyLock<Mutex<HashMap<usize, Vec<Arc<Recording>>>>> = LazyLock::new(Default::default); @@ -310,7 +316,7 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, return Ok(()); }; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); - let held = Arc::new(Recording { scratch, first, chain }); + let held = Arc::new(Recording { scratch, first, chain, _indirect_commands: None }); RECORDINGS.lock().unwrap().entry(allocator).or_default().push(held.clone()); DISPATCHES.fetch_add(1, Ordering::Relaxed); SLABS.fetch_add(slabs.len() as u64, Ordering::Relaxed); @@ -318,6 +324,62 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, Ok(()) } +fn indirect_rounds() -> u32 { + static ROUNDS: OnceLock<u32> = OnceLock::new(); + *ROUNDS.get_or_init(|| std::env::var("XCL_SPLIT_INDIRECT_ROUNDS").ok().and_then(|v| v.trim().parse().ok()) + .filter(|&n| n > 0).unwrap_or(16u32).min(1024)) +} + +/// Run one Dispatch-only indirect command through an existing split chain. Until the whole form +/// is already built, return false so the caller preserves the existing synchronous fallback. The +/// slicer writes either bounded piece commands or the whole-form command, never a partial chain. +pub(in crate::hle::d3d12x) unsafe fn execute_indirect( + list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, args: u64, + bind: impl FnOnce() -> Result<(), String>, +) -> Result<bool, String> { + let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(false) }; + let whole = match chain.whole.ready() { + None => return Ok(false), + Some(Ok(pso)) => pso, + Some(Err(hr)) => return Err(format!("whole compute pipeline ({hr:#x})")), + }; + let allocator = if super::super::alloc_pool::enabled() { + super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) + } else { allocator }; + if allocator == 0 || list.GetType() == D3D12_COMMAND_LIST_TYPE_BUNDLE { return Ok(false); } + let group = u64::from(chain.words) * 4; + let Some((scratch, _)) = scratch_for(&chain.builder.device, list.as_raw() as usize, allocator, scratch_budget(), group) else { + return Ok(false); + }; + let signature = match chain.indirect_signature.get() { + Some(sig) => sig.clone(), + None => { + let sig = pso::chain_command_signature(&chain.builder.device, &chain.builder.signature)?; + chain.indirect_signature.get_or_init(|| sig).clone() + } + }; + let whole_signature = pso::dispatch_command_signature(&chain.builder.device)?; + let rounds = indirect_rounds(); + let pieces = chain.tail.len() as u32 + 1; + let commands = pso::chain_commands_buffer(&chain.builder.device, rounds, pieces) + .ok_or("no command buffer for split ExecuteIndirect")?; + let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); + pso::record_indirect_slicer(list, args, rounds, (scratch.bytes / group).max(1), pieces, &commands)?; + let bound = bind(); + if bound.is_ok() { + list.SetPipelineState(&whole); + list.ExecuteIndirect(&whole_signature, 1, &commands, + pso::chain_tail_offset(rounds, pieces), None::<&ID3D12Resource>, 0); + pso::record_dispatch_chain_indirect(list, &signature, &commands, rounds, &scratch.buffer, + std::iter::once(&first).chain(&chain.tail)); + } + RECORDINGS.lock().unwrap().entry(allocator).or_default().push(Arc::new(Recording { + scratch, first, chain, _indirect_commands: Some(commands), + })); + bound?; + Ok(true) +} + #[cfg(test)] mod tests { use super::*; @@ -427,6 +489,46 @@ mod tests { assert_eq!(calls, 2, "the successful retry is retained"); } + #[test] + fn failed_binding_keeps_indirect_commands_until_allocator_reset() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe extern "system" fn never(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { E_INVALIDARG } + unsafe { + let mut dev = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let dev = dev.unwrap(); + let Ok(dxil) = crate::gpu::recomp::dxc::compile("[numthreads(1,1,1)] void main() {}", "main", "cs_6_0", &[]) else { + return crate::gpu::recomp::runner::skip_test("no DXC"); + }; + let rs = pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() }; + let first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap(); + let whole = WholeBuild::new(); + whole.get_or_build(std::time::Instant::now(), || Ok(first.clone())).unwrap(); + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs, samplers: Vec::new(), + flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); + let key = first.as_raw() as usize; + CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, + whole_code: Vec::new(), whole, indirect_signature: OnceLock::new() })); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize); + super::super::super::alloc_pool::created_on(raw_list, allocator, ty.0); + let args = pso::chain_commands_buffer(&dev, 1, 1).unwrap(); + assert_eq!(execute_indirect(&list, key, allocator, args.GetGPUVirtualAddress(), || Err("bind failed".into())), Err("bind failed".into())); + assert!(RECORDINGS.lock().unwrap().get(&allocator).is_some_and(|r| r.iter().any(|r| r._indirect_commands.is_some()))); + list.Close().unwrap(); + allocator_reset(allocator); + list_reset(raw_list); + forget(key); + super::super::super::alloc_pool::forget_list(raw_list); + } + } + #[test] fn remap_compile_oom_retries_but_deterministic_failure_is_final() { let at = std::time::Instant::now(); From 9ec2b4a3e4153f4f7ecda9551b9f288e0c94517c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:14:51 -0800 Subject: [PATCH 172/265] D3D12.X: retain UMA until its native allocator resets Allocator swapping made the logical title allocator differ from the native backing that owns a recording. Key pending console UMA blocks to that native backing and release them only after its exact generation is proved idle and reset or retired. Driver Reset, fence polling, UMA release, and COM Release remain outside allocator pool state. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 17 ++++++++++-- crates/xcl/src/hle/d3d12x/bind.rs | 37 ++++++++++++++++++++++--- crates/xcl/src/hle/d3d12x/real.rs | 16 +++++------ 3 files changed, 55 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 263fe38469..d878fda894 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -316,6 +316,7 @@ fn sweep_release_owners_with( let Some((raw, mut backing)) = removed else { continue }; let owner = backing.release_owner.take(); drop(backing); + super::console_list::allocator_reset(raw as *mut c_void); match owner { Some(owner) => release_transferred(owner), None => release_made(unsafe { ID3D12CommandAllocator::from_raw(raw as *mut c_void) }), @@ -929,19 +930,29 @@ unsafe fn forget_in(s: &mut State, alloc: usize, free: &HashSet<usize>) -> (Vec< } pub unsafe fn forget(alloc: usize) { - let (made, removed) = loop { + let (made, removed, free) = loop { let (mine, probes) = { let g = STATE.lock().unwrap(); - let Some(s) = g.as_ref() else { return }; + let Some(s) = g.as_ref() else { + drop(g); + super::console_list::allocator_reset(alloc as *mut c_void); + return; + }; namespace_probes(s, alloc) }; let free: HashSet<_> = probes.iter().filter(|probe| unsafe { probe.free() }).map(|probe| probe.raw).collect(); let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return }; if namespace_matches(s, alloc, &mine, &probes) { - break forget_in(s, alloc, &free); + let (made, removed) = forget_in(s, alloc, &free); + break (made, removed, free); } }; + // Native backing ownership also keys console UMA allocations. Free only backings whose + // exact generation was proved idle, and do it outside STATE because freeing can re-enter. + for raw in free { + super::console_list::allocator_reset(raw as *mut c_void); + } for mut backing in removed { let owner = backing.release_owner.take(); drop(backing); diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 9f3818d3a5..7314eade25 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -72,12 +72,22 @@ fn with<R>(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default()) } +fn native_backing(list: *mut c_void, allocator: usize) -> usize { + if allocator == 0 { + 0 + } else { + super::alloc_pool::recording_backing(list as usize) + .unwrap_or_else(|| super::alloc_pool::current(allocator)) + } +} + /// The list was created or reset onto `allocator` with `initial_pso`: the previous -/// recording's memory is the previous allocator's until that one is reset, and pipeline -/// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. +/// recording's memory is the previous native backing's until that backing is reset, and +/// pipeline and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { + let backing = native_backing(list, allocator); let (old, blocks) = with(list, |s| { - let old = std::mem::replace(&mut s.allocator, allocator); + let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.pso = initial_pso; s.layout = None; @@ -118,6 +128,7 @@ pub(super) struct PreparedSplit { } pub(super) fn prepare_split(from: *mut c_void, to: *mut c_void, allocator: usize) -> PreparedSplit { + let backing = native_backing(to, allocator); let (layout, args, layout_gfx, args_gfx, rs_gfx, pso) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso) }); @@ -127,7 +138,7 @@ pub(super) fn prepare_split(from: *mut c_void, to: *mut c_void, allocator: usize (old, std::mem::take(&mut s.uma)) }); console_list::hold_until_reset(old, blocks); - PreparedSplit { to: to as usize, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso } + PreparedSplit { to: to as usize, allocator: backing, layout, args, layout_gfx, args_gfx, rs_gfx, pso } } /// Install a preflighted split state without cloning or growing the state map. @@ -1524,6 +1535,24 @@ void main(uint t : SV_GroupIndex) { remove_state_for_test(to); } + #[test] + fn reset_keys_uma_to_the_lists_native_allocator_backing() { + let list = 0x7101_7001usize as *mut c_void; + let (logical, native, old_native, block) = (0x7101_7100usize, 0x7101_7200usize, 0x7101_7300usize, 0x7101_7400usize); + let _ = console_list::take_pending_for_test(old_native); + super::super::alloc_pool::created_on(list as usize, native, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + seed_reset_state_for_test(list, old_native, 0, vec![block]); + + reset(list, logical, 0); + + assert_eq!(reset_state_for_test(list).0, native, + "UMA ownership follows the recording's native backing, not the title allocator"); + assert_eq!(console_list::take_pending_for_test(old_native), vec![block]); + remove_state_for_test(list); + super::super::alloc_pool::forget_list(list as usize); + unsafe { super::super::alloc_pool::forget(native); } + } + #[test] fn abandoned_split_preflight_keeps_old_uma_under_its_allocator() { let from = 0x7102_0001usize as *mut c_void; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ae0e957e17..c522cd8ea7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8659,21 +8659,21 @@ pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void) -> HRESULT; let f: F = std::mem::transmute(orig_fn(raw, slot!(raw, "Reset"))); let hr = f(raw); - if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } + if hr >= 0 { + dispatch_chain::allocator_reset(raw as usize); + // The GPU is done with allocations owned by this exact native backing. + super::console_list::allocator_reset(raw); + } hr } unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { - // (lists may still hold recordings on it that the title submits again: `alloc_pool`) - let hr = match super::alloc_pool::title_reset(this) { + // Lists may still hold recordings on it that the title submits again (`alloc_pool`). UMA + // follows each native backing and is released only when reset_pc_allocator resets that one. + match super::alloc_pool::title_reset(this) { Some(hr) => hr, None => reset_pc_allocator(this), - }; - if hr >= 0 { - // the GPU is done with what lists recorded from this allocator used - super::console_list::allocator_reset(this); } - hr } // --------------------------------------------------------------------------------------- From ae55d1057d39f47f946b0f6026666830bdc3a87b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:18:03 -0800 Subject: [PATCH 173/265] D3D12.X: measure sampled texture residency on activity runs Track resident and SRV-addressable texels only when XCL_ACTIVITY is enabled. Disabled runs do not allocate per-texture accounting or take the PAGES lock from SRV creation. Deferred superseded mappings remain resident until their guarded GPU unmap actually completes. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 3 + crates/xcl/src/hle/d3d12x/vram.rs | 308 +++++++++++++++++++++++++++++- crates/xcl/src/host.rs | 14 ++ 3 files changed, 323 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index c522cd8ea7..627b6c58cd 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2421,6 +2421,9 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } super::console_heap::publish(&slot, false); super::console_heap::note_resource(&slot, res as usize); + if !res.is_null() && super::memory_report::enabled() { + super::vram::note_srv(res as usize, desc.as_ref()); + } if super::present::trace_frame() && super::title_textures::address(res as usize).is_some() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 24 { diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 20739ea7a2..07941a052f 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -240,6 +240,8 @@ struct Target { used_extra: Vec<(usize, usize)>, /// its levels get their pages one by one (`map_levels`); None: all of it has pages levels: Option<Levels>, + /// virtual, resident, and SRV-sampled texel accounting for sampled placed textures (`None` for GPU-owned targets) + texels: Option<TexelMeta>, } /// The tiles of a texture whose levels get video memory when an upload first has texels for @@ -320,6 +322,170 @@ fn level_stats() -> (u64, u64, u64, u64) { (l(0), l(1), l(2), l(3)) } +/// Snapshot of placed sampled-texture residency and SRV mip coverage (`XCL_ACTIVITY`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TexelStats { + pub sampled_textures: u64, + pub srv_textures: u64, + pub total_texels: u64, + pub resident_texels: u64, + pub srv_sampled_texels: u64, +} + +static TEXEL_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +pub fn texel_stats() -> TexelStats { + let l = |k: usize| TEXEL_STATS[k].load(std::sync::atomic::Ordering::Relaxed); + TexelStats { + sampled_textures: l(0), + srv_textures: l(1), + total_texels: l(2), + resident_texels: l(3), + srv_sampled_texels: l(4), + } +} + +fn mip_texels(width: u64, height: u32, depth: u16, dim: i32, mip: u32) -> u64 { + let shift = mip.min(63); + let w = (width >> shift).max(1); + let slices = (depth as u64).max(1); + if dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { + let h = ((height as u64) >> shift).max(1); + let d = ((depth as u64) >> shift).max(1); + w.saturating_mul(h).saturating_mul(d) + } else if dim == D3D12_RESOURCE_DIMENSION_TEXTURE1D.0 { + w.saturating_mul(slices) + } else { + let h = ((height as u64) >> shift).max(1); + w.saturating_mul(h).saturating_mul(slices) + } +} + +fn range_texels(width: u64, height: u32, depth: u16, dim: i32, mips: std::ops::Range<u32>) -> u64 { + mips.fold(0u64, |acc, m| acc.saturating_add(mip_texels(width, height, depth, dim, m))) +} + +fn mip_mask(mips: std::ops::Range<u32>, max_mips: u32) -> u32 { + let cap = max_mips.min(32); + let lo = mips.start.min(cap); + let hi = mips.end.min(cap); + let mut mask = 0u32; + for m in lo..hi { + mask |= 1u32 << m; + } + mask +} + +fn srv_mip_range(res_mips: u32, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> std::ops::Range<u32> { + let Some(v) = desc else { return 0..res_mips }; + // SAFETY: each branch reads only the union field named by `v.ViewDimension`. + let (most_detailed, mip_levels, min_lod_clamp) = unsafe { + match v.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE1D => { + let s = &v.Anonymous.Texture1D; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURE1DARRAY => { + let s = &v.Anonymous.Texture1DArray; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURE2D => { + let s = &v.Anonymous.Texture2D; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { + let s = &v.Anonymous.Texture2DArray; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURE3D => { + let s = &v.Anonymous.Texture3D; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURECUBE => { + let s = &v.Anonymous.TextureCube; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY => { + let s = &v.Anonymous.TextureCubeArray; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + _ => return 0..0, + } + }; + let end = if mip_levels == 0 || mip_levels == u32::MAX { + res_mips + } else { + most_detailed.saturating_add(mip_levels).min(res_mips) + }; + let clamp_mip = if min_lod_clamp.is_finite() && min_lod_clamp > 0.0 { + min_lod_clamp.floor() as u32 + } else { + 0 + }; + let start = most_detailed.max(clamp_mip).min(end); + start..end +} + +struct TexelMeta { + width: u64, + height: u32, + depth: u16, + mips: u16, + dim: i32, + total_texels: u64, + resident_texels: u64, + srv_mask: u32, +} + +impl TexelMeta { + fn from_desc(desc: &D3D12_RESOURCE_DESC, resident: bool) -> Self { + let mips = desc.MipLevels.max(1); + let total_texels = range_texels(desc.Width, desc.Height, desc.DepthOrArraySize, desc.Dimension.0, 0..mips as u32); + TexelMeta { + width: desc.Width, + height: desc.Height, + depth: desc.DepthOrArraySize, + mips, + dim: desc.Dimension.0, + total_texels, + resident_texels: if resident { total_texels } else { 0 }, + srv_mask: 0, + } + } + + fn mask_texels(&self, mask: u32) -> u64 { + let cap = (self.mips as u32).min(32); + let mut total = 0u64; + for m in 0..cap { + if mask & (1u32 << m) != 0 { + total = total.saturating_add(mip_texels(self.width, self.height, self.depth, self.dim, m)); + } + } + total + } + + fn record_srv(&mut self, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> (bool, u64) { + let first_srv = self.srv_mask == 0; + let add = mip_mask(srv_mip_range(self.mips as u32, desc), self.mips as u32) & !self.srv_mask; + if add == 0 { + return (false, 0); + } + self.srv_mask |= add; + (first_srv, self.mask_texels(add)) + } +} + +fn record_texel_insert(texels: &Option<TexelMeta>) { + let Some(tm) = texels.as_ref() else { return }; + TEXEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if tm.total_texels > 0 { + TEXEL_STATS[2].fetch_add(tm.total_texels, std::sync::atomic::Ordering::Relaxed); + } + if tm.resident_texels > 0 { + TEXEL_STATS[3].fetch_add(tm.resident_texels, std::sync::atomic::Ordering::Relaxed); + } +} + impl Levels { /// Its tiles that have pages. fn mapped_tiles(&self) -> u64 { @@ -852,6 +1018,12 @@ impl Pages { LEVEL_STATS[2].fetch_sub(levels.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); levels.groups.iter_mut().for_each(|group| group.3 = false); } + if let Some(tm) = self.targets.get_mut(&key).and_then(|target| target.texels.as_mut()) { + if tm.resident_texels > 0 { + TEXEL_STATS[3].fetch_sub(tm.resident_texels, std::sync::atomic::Ordering::Relaxed); + tm.resident_texels = 0; + } + } self.unmap(&held.res, held.total); self.release_tiles(held.used, held.used_extra, now, true); done.push(held.res); @@ -1132,6 +1304,7 @@ unsafe fn place_on_pages( dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); None }; + let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); let bound = { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { @@ -1139,10 +1312,12 @@ unsafe fn place_on_pages( // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels }); + record_texel_insert(&texels); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, texels }); true } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None }); + record_texel_insert(&texels); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, texels }); true } else { false @@ -1247,6 +1422,12 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { t.used = used; t.used_extra = used_extra; t.mapped = true; + if let Some(tm) = t.texels.as_mut() { + if tm.resident_texels == 0 && tm.total_texels > 0 { + tm.resident_texels = tm.total_texels; + TEXEL_STATS[3].fetch_add(tm.total_texels, std::sync::atomic::Ordering::Relaxed); + } + } } true } @@ -1262,6 +1443,22 @@ fn forget_pages(resource: usize) { LEVEL_STATS[1].fetch_sub(t.total as u64, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); } + if let Some(tm) = &t.texels { + TEXEL_STATS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + if tm.srv_mask != 0 { + TEXEL_STATS[1].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + let sampled = tm.mask_texels(tm.srv_mask); + if sampled > 0 { + TEXEL_STATS[4].fetch_sub(sampled, std::sync::atomic::Ordering::Relaxed); + } + } + if tm.total_texels > 0 { + TEXEL_STATS[2].fetch_sub(tm.total_texels, std::sync::atomic::Ordering::Relaxed); + } + if tm.resident_texels > 0 { + TEXEL_STATS[3].fetch_sub(tm.resident_texels, std::sync::atomic::Ordering::Relaxed); + } + } if t.mapped { pages.release_tiles(t.used, t.used_extra, now, false); } @@ -1615,6 +1812,14 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> if let Some(l) = t.levels.as_mut() { l.groups[k].3 = true; } + if let Some(tm) = t.texels.as_mut() { + let added = range_texels(tm.width, tm.height, tm.depth, tm.dim, levels.clone()); + let delta = tm.total_texels.saturating_sub(tm.resident_texels).min(added); + if delta > 0 { + tm.resident_texels += delta; + TEXEL_STATS[3].fetch_add(delta, std::sync::atomic::Ordering::Relaxed); + } + } LEVEL_STATS[2].fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed); let groups = LEVEL_STATS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; if groups >= 1024 && groups.is_power_of_two() { @@ -1628,6 +1833,26 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> Vec::new() } +/// Record which mip levels of placed sampled texture `resource` an SRV can sample. +pub(super) fn note_srv(resource: usize, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) { + if !super::memory_report::enabled() || resource == 0 || !is_placed_texture(resource) { + return; + } + let mut g = PAGES.lock().unwrap(); + for pages in g.values_mut().flatten() { + let Some(t) = pages.targets.get_mut(&resource) else { continue }; + let Some(tm) = t.texels.as_mut() else { return }; + let (first_srv, added) = tm.record_srv(desc); + if first_srv { + TEXEL_STATS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + if added > 0 { + TEXEL_STATS[4].fetch_add(added, std::sync::atomic::Ordering::Relaxed); + } + return; + } +} + /// Whether `resource` is a texture whose levels get their pages one by one (`map_levels`). pub(super) fn has_lazy_levels(resource: usize) -> bool { PAGES.lock().unwrap().values().flatten().any(|p| p.targets.get(&resource).is_some_and(|t| t.levels.is_some())) @@ -2634,4 +2859,83 @@ mod tests { assert!(new_calls < old_calls); } } + + #[test] + fn mip_texels_and_range_for_2d_array_3d_and_1d() { + assert_eq!(mip_texels(64, 32, 1, D3D12_RESOURCE_DIMENSION_TEXTURE2D.0, 0), 64 * 32); + assert_eq!(mip_texels(64, 32, 1, D3D12_RESOURCE_DIMENSION_TEXTURE2D.0, 1), 32 * 16); + assert_eq!(mip_texels(64, 32, 6, D3D12_RESOURCE_DIMENSION_TEXTURE2D.0, 2), 16 * 8 * 6); + assert_eq!(mip_texels(64, 32, 8, D3D12_RESOURCE_DIMENSION_TEXTURE3D.0, 2), 16 * 8 * 2); + assert_eq!(mip_texels(64, 1, 4, D3D12_RESOURCE_DIMENSION_TEXTURE1D.0, 3), 8 * 4); + assert_eq!(range_texels(4, 4, 1, D3D12_RESOURCE_DIMENSION_TEXTURE2D.0, 0..3), 16 + 4 + 1); + } + + #[test] + fn srv_mip_range_respects_most_detailed_mip_levels_and_min_lod_clamp() { + assert_eq!(srv_mip_range(5, None), 0..5); + let srv_2d = D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 1, + MipLevels: 3, + PlaneSlice: 0, + ResourceMinLODClamp: 2.75, + }, + }, + ..Default::default() + }; + assert_eq!(srv_mip_range(6, Some(&srv_2d)), 2..4); + + let srv_all = D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: 2, + MipLevels: u32::MAX, + FirstArraySlice: 0, + ArraySize: 2, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + ..Default::default() + }; + assert_eq!(srv_mip_range(5, Some(&srv_all)), 2..5); + } + + #[test] + fn texel_meta_unions_overlapping_srv_ranges_without_double_counting() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 4, + ..Default::default() + }; + let mut tm = TexelMeta::from_desc(&desc, false); + assert_eq!(tm.total_texels, 64 + 16 + 4 + 1); + assert_eq!(tm.resident_texels, 0); + + let srv_low = D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 1, MipLevels: 2, PlaneSlice: 0, ResourceMinLODClamp: 0.0 }, + }, + ..Default::default() + }; + assert_eq!(tm.record_srv(Some(&srv_low)), (true, 16 + 4)); + + let srv_all = D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 4, PlaneSlice: 0, ResourceMinLODClamp: 0.0 }, + }, + ..Default::default() + }; + assert_eq!(tm.record_srv(Some(&srv_all)), (false, 64 + 1)); + assert_eq!(tm.record_srv(Some(&srv_all)), (false, 0)); + assert_eq!(tm.mask_texels(tm.srv_mask), tm.total_texels); + } } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 31b2de8894..283f2b8690 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -85,6 +85,20 @@ pub fn host_main(boot_path: &Path) -> i32 { mb(pools_mapped as u64) ); crate::xlog_info!("{}", owner.line()); + let ts = crate::hle::d3d12x::vram::texel_stats(); + if ts.sampled_textures > 0 { + let pct = if ts.total_texels > 0 { ts.resident_texels.saturating_mul(100) / ts.total_texels } else { 0 }; + let mtex = |n: u64| n as f64 / 1_000_000.0; + crate::xlog_info!( + "texture residency: {} sampled ({} with SRV); texels {:.1}M resident / {:.1}M srv-sampled / {:.1}M virtual ({}% resident)", + ts.sampled_textures, + ts.srv_textures, + mtex(ts.resident_texels), + mtex(ts.srv_sampled_texels), + mtex(ts.total_texels), + pct + ); + } last = now; } }); From 05bab7828000ed85ca5e755770e21f407886b15e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:18:10 -0800 Subject: [PATCH 174/265] D3D12.X: attribute submitting-thread recording costs Add a separate detailed stall-tracing tier for high-frequency command recording. The first title submit identifies the submitting thread, and only that thread's draw, dispatch, binding, barrier, copy, and list-lifecycle work is timed. Coarse tracing and default runs still avoid clock reads and counter updates at those hot call sites. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 4 ++ crates/xcl/src/hle/d3d12x/bind.rs | 20 ++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 15 ++++- crates/xcl/src/hle/d3d12x/real.rs | 7 +++ crates/xcl/src/host.rs | 5 +- crates/xcl/src/report.rs | 6 ++ crates/xcl/src/stall.rs | 88 +++++++++++++++++++++++++++-- 7 files changed, 137 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 8a63a5ddbf..b07bf44bb0 100644 --- a/README.md +++ b/README.md @@ -311,6 +311,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder With `XCL_STALL_TRACE=1`, `report.json` also contains versioned aggregate counts, total/max time and log2-nanosecond histograms for coarse runtime stalls, plus a bounded list of the newest spans of at least 50 ms. The tracing is off by default. + `XCL_STALL_TRACE_DETAIL=1` includes high-frequency draw, dispatch, binding, barrier, copy and + command-list lifecycle recording costs on the title's first observed submitting thread; it also + enables the coarse trace. Use it only for a diagnostic run because every recorded call reads the + clock and updates counters. - **Diagnostics for a bug report** (all off by default; set them in the environment of `xcl run`): - `XCL_RUN_SECONDS=n`: the title ends itself after `n` seconds, with the GPU drained and `xcl.log` and `report.json` written, so a run of a fixed length can be attached. A value that diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 7314eade25..f2c79a967e 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -224,6 +224,7 @@ fn put(list: *mut c_void, i: u32, offset: u32, bytes: &[u8]) { /// #34 SetGraphicsRootSignature (PC #30) pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_void, rs: *mut c_void) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); let layout = console_list::layout_of(rs as usize); with(this, |s| { s.args_gfx = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; @@ -234,16 +235,19 @@ pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_vo /// #36 SetGraphicsRootDescriptorTable (PC #32) pub(super) unsafe extern "system" fn set_graphics_root_table(this: *mut c_void, i: u32, handle: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put_in(this, true, i, 0, &(handle as u32).to_le_bytes()); } /// #38 SetGraphicsRoot32BitConstant (PC #34) pub(super) unsafe extern "system" fn set_graphics_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put_in(this, true, i, offset, &value.to_le_bytes()); } /// #40 SetGraphicsRoot32BitConstants (PC #36) pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); if !data.is_null() { let bytes: Vec<u8> = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); put_in(this, true, i, offset, &bytes); @@ -253,6 +257,7 @@ pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_vo /// #42 / #44 / #46 SetGraphicsRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #38 / /// #40 / #42) pub(super) unsafe extern "system" fn set_graphics_root_descriptor(this: *mut c_void, i: u32, va: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); note_address(va); put_in(this, true, i, 0, &va.to_le_bytes()); } @@ -317,7 +322,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); let raw_pso = with(this, |s| s.pso); - let unbuilt_compute = signature_dispatches(sig) && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso); + let dispatches = signature_dispatches(sig); + let _detail = crate::stall::detail_span(if dispatches { crate::stall::StallKind::DetailDispatch } else { crate::stall::StallKind::DetailDraw }); + let unbuilt_compute = dispatches && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso); if unbuilt_compute && super::list_x::defer(this, raw_pso, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { return; } @@ -360,7 +367,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // A native PC compute pipeline is not one of these and still goes to the PC call. // (`CONSOLE_COMPUTE` holds the title's object, which for a shared stand-in differs from // the driver pipeline `resolve_wait` returned.) - if signature_dispatches(sig) && (super::real::is_console_compute(raw_pso) || super::real::is_console_compute(pso)) { + if dispatches && (super::real::is_console_compute(raw_pso) || super::real::is_console_compute(pso)) { count(DISPATCHES_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -587,6 +594,7 @@ fn cpu_rect_expansion(pso: usize) -> bool { /// #12 DrawInstanced pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); if let Some(list) = graphics_bound(this) { if draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { @@ -604,6 +612,7 @@ thread_local! { /// #13 DrawIndexedInstanced pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, if first_instance != 0 { instances.max(2) } else { instances }); emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); @@ -926,6 +935,7 @@ unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { /// #33 SetComputeRootSignature (PC #29) pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_void, rs: *mut c_void) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); let layout = console_list::layout_of(rs as usize); with(this, |s| { s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; @@ -935,16 +945,19 @@ pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_voi /// #35 SetComputeRootDescriptorTable (PC #31): the table's console address, 32 bits pub(super) unsafe extern "system" fn set_compute_root_table(this: *mut c_void, i: u32, handle: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put(this, i, 0, &(handle as u32).to_le_bytes()); } /// #37 SetComputeRoot32BitConstant (PC #33) pub(super) unsafe extern "system" fn set_compute_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put(this, i, offset, &value.to_le_bytes()); } /// #39 SetComputeRoot32BitConstants (PC #35) pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); if !data.is_null() { let bytes: Vec<u8> = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); put(this, i, offset, &bytes); @@ -954,18 +967,21 @@ pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_voi /// #41 / #43 / #45 SetComputeRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #37 / /// #39 / #41): the 64-bit GPU address pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_void, i: u32, va: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); note_address(va); put(this, i, 0, &va.to_le_bytes()); } /// #25 SetPipelineState: noted, then bound as on the PC pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: *mut c_void) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); with(this, |s| s.pso = pso as usize); super::real::bind_pipeline(this, pso); } /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDispatch); dispatch_flags(this, x, y, z, 0); } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index d6691e2025..2647f17441 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4634,6 +4634,7 @@ pub(super) unsafe fn ensure_view_heap(this: *mut c_void) { /// console #32 SetDescriptorHeaps (PC #28) pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n: u32, heaps: *const usize) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); const PC_SET_DESCRIPTOR_HEAPS: usize = 28; let f = pc::<unsafe extern "system" fn(*mut c_void, u32, *const usize)>(this, PC_SET_DESCRIPTOR_HEAPS); if heaps.is_null() || n == 0 { @@ -4856,6 +4857,7 @@ const PC_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 /// PC ones – state bits the PC does not know are dropped (logged: the console's own), a /// transition left with nothing to do goes, aliasing barriers name placed textures pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u32, barriers: *const [u32; 8]) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBarrier); static N: AtomicU64 = AtomicU64::new(0); if barriers.is_null() || n == 0 { return; @@ -4953,6 +4955,7 @@ unsafe fn is_buffer(res: usize) -> bool { /// DMA list #9 Close: as on the PC; a failure is logged (the title stops on it) pub(super) unsafe extern "system" fn dma_close_x(this: *mut c_void) -> i32 { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailListLifecycle); let ext = *(this as *const usize); let hr = pc::<unsafe extern "system" fn(*mut c_void) -> i32>(this, 9)(this); real::preserve_vtable(this, ext); @@ -4991,6 +4994,11 @@ fn note_gpu_write(what: &str, va: usize, n: u64) { } pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); + copy_buffer_region_inner(this, dst, dst_off, src, src_off, n) +} + +unsafe fn copy_buffer_region_inner(this: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) { if super::present::trace_frame() { if let Some(a) = real::title_address(dst) { note_gpu_write("CopyBufferRegion", a + dst_off as usize, n); @@ -5025,6 +5033,7 @@ unsafe fn trace_watched_copy(what: &str, dst: usize, src: usize) { /// CopyTextureRegion(dst, x, y, z, src, box) (PC #16; DMA list #12) pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, dst: *const D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, src: *const D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); if let Some(d) = dst.as_ref() { let r: usize = transmute_copy(&d.pResource); super::present::note_use(r, super::present::USE_COPY); @@ -5157,6 +5166,7 @@ fn uav_clear_handles(gpu: Option<super::console_heap::Slot>, cpu: Option<super:: /// resource, values[4], rects, rect list) (PC #49 / #50): console handles are addresses of /// console heap slots (heap #9 / #10), not PC descriptors unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usize, values: *const c_void, n: u32, rects: *const windows::Win32::Foundation::RECT) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); let (gpu, cpu) = match uav_clear_handles(super::console_heap::slot(gpu), super::console_heap::slot(cpu)) { UavClearHandles::Console { gpu, cpu } => (gpu, cpu), UavClearHandles::Pc => (gpu, cpu), @@ -5209,6 +5219,7 @@ unsafe fn trace_resolve(what: &str, dst: usize, src: usize, format: i32, extra: /// command list #19 ResolveSubresource(dst, dst sub, src, src sub, format) (PC #19) pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, dst: usize, dst_sub: u32, src: usize, src_sub: u32, format: i32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); super::present::note_use(dst, super::present::USE_COPY); trace_resolve("ResolveSubresource", dst, src, format, ""); pc::<unsafe extern "system" fn(*mut c_void, usize, u32, usize, u32, i32)>(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) @@ -5218,6 +5229,7 @@ pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, ds /// mode) (PC #64) #[allow(clippy::too_many_arguments)] pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_void, dst: usize, dst_sub: u32, x: u32, y: u32, src: usize, src_sub: u32, rect: *const windows::Win32::Foundation::RECT, format: i32, mode: i32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); super::present::note_use(dst, super::present::USE_COPY); if super::present::trace_frame() { trace_resolve("ResolveSubresourceRegion", dst, src, format, &format!(" mode {mode} at ({x}, {y}) rect {:?}", rect.as_ref().map(|r| (r.left, r.top, r.right, r.bottom)))); @@ -5228,6 +5240,7 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v /// CopyResource(dst, src) (PC #17; DMA list #13): buffers placed below their console address /// are copied as their own bytes (the PC resources also hold what lies before them) pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); super::present::note_use(dst, super::present::USE_COPY); note_texture_write(this as usize, dst, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); if super::present::trace_frame() { @@ -5238,7 +5251,7 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi return pc::<unsafe extern "system" fn(*mut c_void, usize, usize)>(this, PC_COPY_RESOURCE)(this, dst, src); } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); - copy_buffer_region_x(this, dst, 0, src, 0, n); + copy_buffer_region_inner(this, dst, 0, src, 0, n); } /// command list #28 BeginQuery(heap, type, index) (PC #52) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 627b6c58cd..a0ca5d0818 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3148,6 +3148,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 { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); super::list_x::before_close(this); let ext = *(this as *const usize); let f: RefFn = std::mem::transmute(orig_fn(this, slot!(this, "Close"))); @@ -3162,6 +3163,7 @@ unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { /// Reset (PC path): re-adopt the runtime's new open-state vtable if Reset replaced it. unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, initial_state: *mut c_void) -> HRESULT { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); let ext = *(this as *const usize); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot!(this, "Reset"))); @@ -8463,6 +8465,7 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 // --------------------------------------------------------------------------------------- unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailBind); type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRenderTargetView"))); // a view in a console-only format, or of a target made R8G8B8A8 (`device_x::pc_resource_desc`) @@ -8485,6 +8488,7 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de /// ClearRenderTargetView: as on the PC (`XCL_TRACE_FRAME`: the colours logged) unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *const [f32; 4], n: u32, rects: *const c_void) { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailCopy); type F = unsafe extern "system" fn(*mut c_void, usize, *const [f32; 4], u32, *const c_void); let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ClearRenderTargetView"))); if super::present::trace_frame() { @@ -8500,6 +8504,7 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co } unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailBind); type F = unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize); let f: F = std::mem::transmute(orig_fn(this, slot!(this, "OMSetRenderTargets"))); f(this, n, rtvs, single, dsv); @@ -8671,6 +8676,7 @@ pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { } unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); // Lists may still hold recordings on it that the title submits again (`alloc_pool`). UMA // follows each native backing and is released only when reset_pc_allocator resets that one. match super::alloc_pool::title_reset(this) { @@ -8924,6 +8930,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis stop_if_device_removed(); return; } + crate::stall::note_submitter(); // from here to the end: XCL's uploads and tile mappings before the lists, then the driver's // own work in the submission. Where that takes long, it is not the title's time // (`pso_async::title_held`) diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 283f2b8690..cc86e98d64 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -31,7 +31,10 @@ pub fn host_main(boot_path: &Path) -> i32 { boot.config.title_memory_mb, boot.config.title_memory ); - if std::env::var_os("XCL_STALL_TRACE").is_some() { + if std::env::var_os("XCL_STALL_TRACE_DETAIL").is_some() { + crate::stall::enable_detail(); + crate::xlog_info!("detailed stall attribution enabled (XCL_STALL_TRACE_DETAIL)"); + } else if std::env::var_os("XCL_STALL_TRACE").is_some() { crate::stall::enable(); crate::xlog_info!("stall attribution enabled (XCL_STALL_TRACE)"); } diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index 60612b592d..ec6a29a674 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -98,6 +98,12 @@ fn stall_kind_name(kind: crate::stall::StallKind) -> &'static str { StallKind::GpuWait => "gpu_wait", StallKind::Present => "present", StallKind::DirectStorage => "direct_storage", + StallKind::DetailDraw => "detail_draw", + StallKind::DetailDispatch => "detail_dispatch", + StallKind::DetailBind => "detail_bind", + StallKind::DetailBarrier => "detail_barrier", + StallKind::DetailCopy => "detail_copy", + StallKind::DetailListLifecycle => "detail_list_lifecycle", } } diff --git a/crates/xcl/src/stall.rs b/crates/xcl/src/stall.rs index 06add3c292..c0fc764838 100644 --- a/crates/xcl/src/stall.rs +++ b/crates/xcl/src/stall.rs @@ -1,11 +1,11 @@ //! Opt-in attribution of time spent in coarse runtime operations. //! //! A disabled span is one relaxed atomic load. In particular, it does not read the clock, allocate, -//! lock, or update a counter. Callers should keep spans coarse enough that enabled tracing remains -//! useful diagnostics rather than becoming the workload. +//! lock, or update a counter. High-frequency command-recording spans have a separate detail switch, +//! so enabling coarse attribution does not turn them on. use std::collections::VecDeque; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use std::sync::{Mutex, OnceLock}; use std::time::Instant; @@ -30,10 +30,16 @@ pub enum StallKind { GpuWait, Present, DirectStorage, + DetailDraw, + DetailDispatch, + DetailBind, + DetailBarrier, + DetailCopy, + DetailListLifecycle, } impl StallKind { - pub const ALL: [Self; 14] = [ + pub const ALL: [Self; 20] = [ Self::ShaderTranslation, Self::DxcQueue, Self::DxcCompile, @@ -48,6 +54,12 @@ impl StallKind { Self::GpuWait, Self::Present, Self::DirectStorage, + Self::DetailDraw, + Self::DetailDispatch, + Self::DetailBind, + Self::DetailBarrier, + Self::DetailCopy, + Self::DetailListLifecycle, ]; const fn index(self) -> usize { @@ -125,6 +137,9 @@ struct SlowSpans { struct Recorder { enabled: AtomicBool, + detail_enabled: AtomicBool, + /// First title thread observed submitting command lists; zero until then. + submitter: AtomicU32, aggregates: [Aggregate; StallKind::ALL.len()], slow_spans: Mutex<SlowSpans>, } @@ -137,6 +152,8 @@ impl Recorder { const fn new() -> Self { Self { enabled: AtomicBool::new(false), + detail_enabled: AtomicBool::new(false), + submitter: AtomicU32::new(0), aggregates: [const { Aggregate::new() }; StallKind::ALL.len()], slow_spans: Mutex::new(SlowSpans { next_sequence: 0, spans: VecDeque::new() }), } @@ -146,6 +163,15 @@ impl Recorder { self.enabled.store(true, Ordering::Relaxed); } + fn enable_detail(&self) { + self.enable(); + self.detail_enabled.store(true, Ordering::Relaxed); + } + + fn note_submitter(&self, thread: u32) { + let _ = self.submitter.compare_exchange(0, thread, Ordering::Relaxed, Ordering::Relaxed); + } + #[inline] fn start_with<'a>(&'a self, kind: StallKind, clock: &'a dyn Clock) -> Option<Span<'a>> { if !self.enabled.load(Ordering::Relaxed) { @@ -154,6 +180,14 @@ impl Recorder { Some(Span { recorder: self, kind, started_ns: clock.now_ns(), clock, finished: false }) } + #[inline] + fn start_detail_with<'a>(&'a self, kind: StallKind, clock: &'a dyn Clock, thread: u32) -> Option<Span<'a>> { + if !self.detail_enabled.load(Ordering::Relaxed) || self.submitter.load(Ordering::Relaxed) != thread { + return None; + } + Some(Span { recorder: self, kind, started_ns: clock.now_ns(), clock, finished: false }) + } + fn record(&self, kind: StallKind, started_ns: u64, duration_ns: u64) { self.aggregates[kind.index()].record(duration_ns); if duration_ns < SLOW_SPAN_NS { @@ -204,17 +238,45 @@ pub fn enable() { RECORDER.enable(); } +pub fn enable_detail() { + RECORDER.enable_detail(); +} + +/// Mark the first title thread that submits command lists as the thread detailed spans describe. +pub fn note_submitter() { + RECORDER.note_submitter(current_thread()); +} + #[inline] pub fn span(kind: StallKind) -> Option<Span<'static>> { RECORDER.start_with(kind, &CLOCK) } +/// A high-frequency command-recording span, enabled only by `XCL_STALL_TRACE_DETAIL`. +#[inline] +pub fn detail_span(kind: StallKind) -> Option<Span<'static>> { + if !RECORDER.detail_enabled.load(Ordering::Relaxed) { + return None; + } + RECORDER.start_detail_with(kind, &CLOCK, current_thread()) +} + +/// Like [`detail_span`], without even consulting the detail switch when `on` is false. +#[inline] +pub fn detail_span_if(on: bool, kind: StallKind) -> Option<Span<'static>> { + on.then(|| detail_span(kind)).flatten() +} + pub fn snapshot() -> Option<Snapshot> { RECORDER.enabled.load(Ordering::Relaxed).then(|| RECORDER.snapshot()) } struct SystemClock; +fn current_thread() -> u32 { + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } +} + impl Clock for SystemClock { fn now_ns(&self) -> u64 { static ORIGIN: OnceLock<Instant> = OnceLock::new(); @@ -254,6 +316,24 @@ mod tests { assert_eq!(recorder.snapshot().aggregates[StallKind::DxcCompile.index()].count, 0); } + #[test] + fn coarse_tracing_does_not_enable_detail_spans() { + let recorder = Recorder::new(); + recorder.enable(); + let clock = TestClock::new(10); + recorder.note_submitter(7); + assert!(recorder.start_detail_with(StallKind::DetailDraw, &clock, 7).is_none()); + assert_eq!(clock.calls.load(Ordering::Relaxed), 0); + + recorder.enable_detail(); + assert!(recorder.start_detail_with(StallKind::DetailDraw, &clock, 8).is_none()); + let span = recorder.start_detail_with(StallKind::DetailDraw, &clock, 7).unwrap(); + clock.now.store(42, Ordering::Relaxed); + drop(span); + let aggregate = &recorder.snapshot().aggregates[StallKind::DetailDraw.index()]; + assert_eq!((aggregate.count, aggregate.total_ns), (1, 32)); + } + #[test] fn a_span_updates_its_aggregate_and_log2_bucket() { let recorder = Recorder::new(); From ce989d2aa64858f80ff46aaf4e49e2385d641b8e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:20:15 -0800 Subject: [PATCH 175/265] README: document activity texture residency totals Describe the opt-in resident, SRV-addressable, and virtual texel line emitted with XCL_ACTIVITY. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b07bf44bb0..04832cbe4f 100644 --- a/README.md +++ b/README.md @@ -322,9 +322,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - `XCL_ACTIVITY=1` (any value turns it on): every 2 seconds `xcl.log` gets an `activity (2 s)` line with what the title did in that time (presents, submits, draws, dispatches, frame-event waits, DirectStorage requests), a `memory:` line with the process's commit and video memory in - use, and a `memory by owner` line splitting the known XCL allocations from `other`. A negative - `other` exposes an overlapping or stale sample; unavailable adapter segments say `unknown`. - Where the lines stop changing is where the title stopped. + use, a `memory by owner` line splitting the known XCL allocations from `other`, and sampled + texture resident / SRV-addressable / virtual texel totals. A negative `other` exposes an + overlapping or stale sample; unavailable adapter segments say `unknown`. Where the lines stop + changing is where the title stopped. - `XCL_THREAD_DUMP_AT=s1,s2,…`: at each of those seconds after the start, the state of every thread of the title goes into `xcl.log`, for a title that stalls. - `XCL_TRACE_FAULTS=1` (any value): the first 32 access violations are logged as they are raised From ffac3219c0b22c0371a9479b14719a987efdab0d Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:24:05 -0800 Subject: [PATCH 176/265] D3D12.X: build indirect split pipelines on the CBV ABI Root-constant ExecuteIndirect costs about 15.3 us per piece step on the measured RTX 5070 Ti, versus 0.41 us for a Dispatch-only signature. Build a bounded, speculative indirect-only piece and whole set on one background lane, then share one 256-byte CBV command per round across its pieces. Direct dispatch keeps its existing constants ABI. Until the direct whole and complete indirect set are ready, ExecuteIndirect keeps the existing whole fallback. Source-plan retention and live duplicate admission are each capped at 64 MiB. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/pso.rs | 72 +++--- crates/xcl/src/hle/d3d12x/bind.rs | 21 +- crates/xcl/src/hle/d3d12x/real.rs | 18 +- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 221 +++++++++++++++--- 4 files changed, 249 insertions(+), 83 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index a26e9d0dc9..a8f6b5df24 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1472,20 +1472,10 @@ pub(crate) unsafe fn record_dispatch_chain<'a>( } } -/// Bytes of one indirect chain command: eight slab constants followed by Dispatch arguments. -pub(crate) const CHAIN_COMMAND_BYTES: u32 = 44; - -pub(crate) fn chain_command_signature(dev: &ID3D12Device, rs: &ID3D12RootSignature) -> Result<ID3D12CommandSignature, String> { - let args = [ - D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { - Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { RootParameterIndex: 7, DestOffsetIn32BitValues: 0, Num32BitValuesToSet: 8 } } }, - D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }, - ]; - let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: CHAIN_COMMAND_BYTES, NumArgumentDescs: 2, pArgumentDescs: args.as_ptr(), NodeMask: 0 }; - let mut sig = None; - unsafe { dev.CreateCommandSignature(&desc, rs, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?; - sig.ok_or_else(|| "CreateCommandSignature".into()) -} +/// One round's root-CBV constants, padded to D3D12's 256-byte CBV alignment. Its Dispatch +/// arguments begin after the eight words and are shared by every piece in that round. +pub(crate) const CHAIN_COMMAND_BYTES: u32 = 256; +pub(crate) const CHAIN_DISPATCH_AT: u64 = 32; pub(crate) fn dispatch_command_signature(dev: &ID3D12Device) -> Result<ID3D12CommandSignature, String> { static MADE: Mutex<Option<(usize, ID3D12CommandSignature)>> = Mutex::new(None); @@ -1503,17 +1493,15 @@ pub(crate) fn dispatch_command_signature(dev: &ID3D12Device) -> Result<ID3D12Com } const INDIRECT_SLICER: &str = r#" -#define RS "RootConstants(num32BitConstants=3, b0), SRV(t0), UAV(u0)" -cbuffer C : register(b0) { uint rounds; uint most; uint pieces; }; +#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)" +cbuffer C : register(b0) { uint rounds; uint most; }; ByteAddressBuffer args : register(t0); RWByteAddressBuffer cmds : register(u0); void put(uint r, uint3 n, uint3 o) { - for (uint i = 0; i < pieces; i++) { - uint at = (r * pieces + i) * 44; - cmds.Store4(at, uint4(n, i)); - cmds.Store4(at + 16, uint4(o, 0)); - cmds.Store3(at + 32, n); - } + uint at = r * 256; + cmds.Store4(at, uint4(n, 0)); + cmds.Store4(at + 16, uint4(o, 0)); + cmds.Store3(at + 32, n); } [RootSignature(RS)] [numthreads(1, 1, 1)] @@ -1534,13 +1522,13 @@ void main() { put(r++, min(s, g - o), o); } for (; r < rounds; r++) put(r, 0, 0); - uint at = (rounds * pieces * 44 + 7) & ~7u; + uint at = rounds * 256; cmds.Store3(at, partial ? g : 0); } "#; -pub(crate) fn chain_tail_offset(rounds: u32, pieces: u32) -> u64 { - (u64::from(rounds) * u64::from(pieces) * u64::from(CHAIN_COMMAND_BYTES)).next_multiple_of(8) +pub(crate) fn chain_tail_offset(rounds: u32) -> u64 { + u64::from(rounds) * u64::from(CHAIN_COMMAND_BYTES) } fn indirect_slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { @@ -1560,9 +1548,9 @@ fn indirect_slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12Pip } } -pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32, pieces: u32) -> Option<ID3D12Resource> { +pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32) -> Option<ID3D12Resource> { let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: chain_tail_offset(rounds, pieces) + 12, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: chain_tail_offset(rounds) + 12, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() }; @@ -1573,15 +1561,15 @@ pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32, piec } pub(crate) unsafe fn record_indirect_slicer( - list: &ID3D12GraphicsCommandList, args: u64, rounds: u32, most: u64, pieces: u32, out: &ID3D12Resource, + list: &ID3D12GraphicsCommandList, args: u64, rounds: u32, most: u64, out: &ID3D12Resource, ) -> Result<(), String> { let mut dev = None; list.GetDevice(&mut dev).map_err(|e| e.to_string())?; let (rs, pso) = indirect_slicer(&dev.ok_or("device")?)?; - let constants = [rounds, most.min(u64::from(u32::MAX)) as u32, pieces]; + let constants = [rounds, most.min(u64::from(u32::MAX)) as u32]; list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); - list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.SetComputeRoot32BitConstants(0, 2, constants.as_ptr().cast(), 0); list.SetComputeRootShaderResourceView(1, args); list.SetComputeRootUnorderedAccessView(2, out.GetGPUVirtualAddress()); list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -1590,7 +1578,8 @@ pub(crate) unsafe fn record_indirect_slicer( list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(out), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, - StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }) } }]); + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER }) } }]); Ok(()) } @@ -1598,15 +1587,15 @@ pub(crate) unsafe fn record_dispatch_chain_indirect<'a>( list: &ID3D12GraphicsCommandList, sig: &ID3D12CommandSignature, commands: &ID3D12Resource, rounds: u32, scratch: &ID3D12Resource, pieces: impl IntoIterator<Item = &'a ID3D12PipelineState> + Clone, ) { - let n = pieces.clone().into_iter().count() as u32; list.SetComputeRootUnorderedAccessView(6, scratch.GetGPUVirtualAddress()); for r in 0..rounds { - for (i, piece) in pieces.clone().into_iter().enumerate() { + let offset = u64::from(r) * u64::from(CHAIN_COMMAND_BYTES); + list.SetComputeRootConstantBufferView(7, commands.GetGPUVirtualAddress() + offset); + for piece in pieces.clone() { list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]); list.SetPipelineState(piece); - let offset = (u64::from(r) * u64::from(n) + i as u64) * u64::from(CHAIN_COMMAND_BYTES); - list.ExecuteIndirect(sig, 1, commands, offset, None::<&ID3D12Resource>, 0); + list.ExecuteIndirect(sig, 1, commands, offset + CHAIN_DISPATCH_AT, None::<&ID3D12Resource>, 0); } } } @@ -1690,7 +1679,7 @@ fn abi_signature( #[cfg(test)] mod slab_tests { - use super::{chain_slab_parameter, chain_tail_offset, dispatch_slabs, ChainSlabBinding, CHAIN_COMMAND_BYTES}; + use super::{chain_slab_parameter, chain_tail_offset, dispatch_slabs, ChainSlabBinding, CHAIN_COMMAND_BYTES, CHAIN_DISPATCH_AT}; use windows::Win32::Graphics::Direct3D12::{ D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, D3D12_ROOT_PARAMETER_TYPE_CBV, @@ -1714,12 +1703,11 @@ mod slab_tests { #[test] fn indirect_whole_arguments_follow_aligned_piece_commands() { - for (rounds, pieces) in [(1, 2), (16, 9), (1024, 64)] { - let commands = u64::from(rounds * pieces * CHAIN_COMMAND_BYTES); - let tail = chain_tail_offset(rounds, pieces); - assert!(tail >= commands); - assert_eq!(tail % 8, 0); - assert!(tail - commands < 8); + for rounds in [1, 16, 1024] { + let tail = chain_tail_offset(rounds); + assert_eq!(tail, u64::from(rounds * CHAIN_COMMAND_BYTES)); + assert_eq!(tail % 256, 0); + assert_eq!(CHAIN_DISPATCH_AT, 32); } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index f2c79a967e..80569779f8 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -393,7 +393,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if compute && max == 1 && count_buf == 0 && DISPATCH_ONLY.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&sig)) { let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(false), |address| { super::real::dispatch_chain::execute_indirect(list, pso, with(this, |s| s.allocator), address, - || bind_abi(this, list, pso, false)) + |root| bind_abi_with_root(this, list, pso, false, root)) }); match chained { Ok(true) => { @@ -1181,6 +1181,12 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis /// arguments the console's way – compute or graphics) and the argument table in unified /// memory, u1 res, u2… the memory windows; then the pipeline. unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { + bind_abi_with_root(this, list, pso, gfx, 0) +} + +unsafe fn bind_abi_with_root( + this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, root: usize, +) -> Result<(), String> { super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); @@ -1213,7 +1219,10 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::<Vec<u8>>())?; let res_at = copy(&[0u8; 256])?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); - let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; + let rs = (root != 0).then_some(root) + .or_else(|| super::real::pso_root_signature(real)) + .or_else(|| super::real::abi_rs_cached().map(|p| p as usize)) + .ok_or("no XCL ABI root signature")?; let rs = rs as *mut c_void; let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().filter(|&v| v != 0).unwrap_or(first))); @@ -1228,9 +1237,11 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi list.SetComputeRootUnorderedAccessView(k as u32, v); } } - let real = real as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; - list.SetPipelineState(pc); + if root == 0 { + let real = real as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; + list.SetPipelineState(pc); + } Ok(()) } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a0ca5d0818..0c48fd6ed0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4936,7 +4936,8 @@ enum ComputeBuild { // through to building the pieces, whose cold build is cheaper. CachedWhole, // The chain root signature has a separate on-disk namespace. - Chain, + DirectChain, + IndirectChain, } unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void, @@ -4951,7 +4952,13 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL let key = compute_blob_key_for(dxil, rs as usize, copy.Flags.0, copy.NodeMask); let mut cached = compute_blob(key); // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) - let disk = driver_cache::path_for_root_node(dxil, copy.Flags.0, mode == ComputeBuild::Chain, samplers, copy.NodeMask); + let disk = match mode { + ComputeBuild::DirectChain => driver_cache::path_for_chain_root_node( + dxil, copy.Flags.0, driver_cache::ChainRoot::DirectConstants, samplers, copy.NodeMask), + ComputeBuild::IndirectChain => driver_cache::path_for_chain_root_node( + dxil, copy.Flags.0, driver_cache::ChainRoot::IndirectCbv, samplers, copy.NodeMask), + _ => driver_cache::path_for_root_node(dxil, copy.Flags.0, false, samplers, copy.NodeMask), + }; let from_disk = cached.is_none(); let mut loaded = None; if from_disk { @@ -5154,6 +5161,13 @@ pub(crate) mod driver_cache { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for_root_node(dxil, flags, chained, samplers, node_mask))) } + pub fn path_for_chain_root_node( + dxil: &[u8], flags: i32, root: ChainRoot, samplers: &[StaticSampler], node_mask: u32, + ) -> Option<PathBuf> { + enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver") + .join(name_for_chain_root_node(dxil, flags, root, samplers, node_mask))) + } + pub fn graphics_path(hash: u64, bytes: usize) -> Option<PathBuf> { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(graphics_name(hash, bytes))) } diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index c146cfa335..9986c135c2 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -2,7 +2,7 @@ //! to the caller. Other pieces and the lazily built whole form belong to it. use super::*; use crate::gpu::{dxil::kernel::DispatchChain, recomp::pso}; -use std::sync::{Arc, LazyLock, OnceLock}; +use std::sync::{Arc, LazyLock, OnceLock, Weak}; static PROGRAMS: AtomicU64 = AtomicU64::new(0); static PIECES: AtomicU64 = AtomicU64::new(0); @@ -37,6 +37,7 @@ struct PipelineBuilder { flags: D3D12_PIPELINE_STATE_FLAGS, node: u32, record: u64, + mode: ComputeBuild, } impl PipelineBuilder { @@ -44,7 +45,7 @@ impl PipelineBuilder { let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; let mut raw = std::ptr::null_mut(); let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), - dxil, &self.samplers, self.record, iid, &mut raw, ComputeBuild::Chain); + dxil, &self.samplers, self.record, iid, &mut raw, self.mode); if hr >= 0 && !raw.is_null() { Ok(ID3D12PipelineState::from_raw(raw)) } else { Err(hr) } } } @@ -98,7 +99,34 @@ struct Chain { words: u32, whole_code: Vec<u8>, whole: WholeBuild<ID3D12PipelineState>, - indirect_signature: OnceLock<ID3D12CommandSignature>, + plan: Weak<DispatchChain>, + indirect: IndirectBuild, +} + +struct IndirectChain { + signature: ID3D12RootSignature, + whole: ID3D12PipelineState, + pieces: Vec<ID3D12PipelineState>, + _charge: IndirectCharge, +} + +struct IndirectCharge(usize); + +impl Drop for IndirectCharge { + fn drop(&mut self) { + INDIRECT_VARIANT_SOURCE.fetch_sub(self.0, Ordering::AcqRel); + } +} + +struct IndirectBuild { + requested: AtomicBool, + result: OnceLock<Result<Arc<IndirectChain>, HRESULT>>, +} + +impl IndirectBuild { + fn new() -> Self { + Self { requested: AtomicBool::new(false), result: OnceLock::new() } + } } impl Chain { @@ -111,18 +139,106 @@ impl Chain { static CHAINS: LazyLock<Mutex<HashMap<usize, Arc<Chain>>>> = LazyLock::new(Default::default); /// Shared for the process lifetime so chains with a common piece also share its driver blob. -static SIGNATURES: LazyLock<Mutex<HashMap<(usize, Vec<u32>), ID3D12RootSignature>>> = LazyLock::new(Default::default); +static SIGNATURES: LazyLock<Mutex<HashMap<(usize, bool, Vec<u32>), ID3D12RootSignature>>> = LazyLock::new(Default::default); fn sampler_key(samplers: &[pso::StaticSampler]) -> Vec<u32> { samplers.iter().flat_map(|(words, comparison)| words.iter().copied().chain([*comparison as u32])).collect() } -unsafe fn signature_for(dev: &ID3D12Device, samplers: &[pso::StaticSampler]) -> Option<ID3D12RootSignature> { - let key = (dev.as_raw() as usize, sampler_key(samplers)); +const INDIRECT_PLAN_BYTES: usize = 64 << 20; +const INDIRECT_VARIANT_BYTES: usize = 64 << 20; +static INDIRECT_VARIANT_SOURCE: AtomicUsize = AtomicUsize::new(0); + +fn reserve_indirect_source(used: &AtomicUsize, bytes: usize, limit: usize) -> bool { + used.fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| { + current.checked_add(bytes).filter(|&next| next <= limit) + }).is_ok() +} + +#[derive(Default)] +struct PlanCache { + bytes: usize, + plans: std::collections::VecDeque<(usize, Arc<DispatchChain>)>, +} + +impl PlanCache { + fn insert(&mut self, plan: Arc<DispatchChain>, limit: usize) { + let key = Arc::as_ptr(&plan) as usize; + if let Some(at) = self.plans.iter().position(|p| p.0 == key) { + self.plans.remove(at); + } else { + self.bytes = self.bytes.saturating_add(plan.pieces.iter().map(Vec::capacity).sum::<usize>()); + } + self.plans.push_back((key, plan)); + while self.bytes > limit { + let Some((_, old)) = self.plans.pop_front() else { break }; + self.bytes = self.bytes.saturating_sub(old.pieces.iter().map(Vec::capacity).sum::<usize>()); + } + } +} + +fn retain_indirect_plan(plan: Arc<DispatchChain>) { + static PLANS: LazyLock<Mutex<PlanCache>> = LazyLock::new(Default::default); + PLANS.lock().unwrap().insert(plan, INDIRECT_PLAN_BYTES); +} + +fn build_indirect(chain: &Arc<Chain>) -> Result<Arc<IndirectChain>, HRESULT> { + let plan = chain.plan.upgrade().ok_or(E_INVALIDARG)?; + let source_bytes = plan.pieces.iter().map(Vec::len).sum::<usize>().saturating_add(chain.whole_code.len()); + if !reserve_indirect_source(&INDIRECT_VARIANT_SOURCE, source_bytes, INDIRECT_VARIANT_BYTES) { + return Err(E_OUTOFMEMORY); + } + let charge = IndirectCharge(source_bytes); + let signature = unsafe { signature_for(&chain.builder.device, &chain.builder.samplers, true) }.ok_or(E_INVALIDARG)?; + let builder = Arc::new(PipelineBuilder { + device: chain.builder.device.clone(), + create: chain.builder.create, + signature: signature.clone(), + samplers: chain.builder.samplers.clone(), + flags: chain.builder.flags, + node: chain.builder.node, + record: chain.builder.record, + mode: ComputeBuild::IndirectChain, + }); + // These variants are speculative: the ready direct whole form remains correct. Keep their + // cold driver compiles on this one low-impact lane instead of fanning out across PSO workers. + let mut pieces = Vec::with_capacity(plan.pieces.len()); + for code in &plan.pieces { + pieces.push(unsafe { builder.pipeline(code, &pc_iid(Kind::PipelineState))? }); + } + let whole = unsafe { builder.pipeline(&chain.whole_code, &pc_iid(Kind::PipelineState))? }; + Ok(Arc::new(IndirectChain { signature, whole, pieces, _charge: charge })) +} + +fn request_indirect(chain: &Arc<Chain>) { + if chain.indirect.requested.swap(true, Ordering::AcqRel) { + return; + } + static BUILDS: LazyLock<Option<std::sync::mpsc::Sender<Weak<Chain>>>> = LazyLock::new(|| { + let (tx, rx) = std::sync::mpsc::channel::<Weak<Chain>>(); + std::thread::Builder::new().name("xcl-pso-chain-indirect".into()).stack_size(64 << 20).spawn(move || { + while let Ok(weak) = rx.recv() { + let Some(chain) = weak.upgrade() else { continue }; + let result = build_indirect(&chain); + let _ = chain.indirect.result.set(result); + } + }).ok().map(|_| tx) + }); + if BUILDS.as_ref().is_none_or(|queue| queue.send(Arc::downgrade(chain)).is_err()) { + chain.indirect.requested.store(false, Ordering::Release); + } +} + +unsafe fn signature_for(dev: &ID3D12Device, samplers: &[pso::StaticSampler], indirect: bool) -> Option<ID3D12RootSignature> { + let key = (dev.as_raw() as usize, indirect, sampler_key(samplers)); if let Some(signature) = SIGNATURES.lock().unwrap().get(&key).cloned() { return Some(signature); } - let created = match pso::dispatch_chain_root_signature(dev, samplers) { + let created = match if indirect { + pso::dispatch_chain_indirect_root_signature(dev, samplers) + } else { + pso::dispatch_chain_root_signature(dev, samplers) + } { Ok(signature) => signature, Err(e) => { note_translation_error(format!("dispatch-chain root signature: {e}")); @@ -137,10 +253,10 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT plan: Arc<DispatchChain>) -> Option<usize> { if result.is_null() || iid.is_null() || plan.pieces.len() < 2 { return None; } let dev = ID3D12Device::from_raw_borrowed(&this)?; - let signature = signature_for(dev, samplers)?; + let signature = signature_for(dev, samplers, false)?; let rs = signature.as_raw() as usize; let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, samplers: samplers.to_vec(), - flags: desc.Flags, node: desc.NodeMask, record }); + flags: desc.Flags, node: desc.NodeMask, record, mode: ComputeBuild::DirectChain }); let jobs = (0..plan.pieces.len()).map(|i| { let plan = plan.clone(); let builder = builder.clone(); @@ -153,7 +269,8 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let mut pieces = built.into_iter().collect::<Option<Vec<_>>>()?.into_iter(); let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, - whole_code: whole.to_vec(), whole: WholeBuild::new(), indirect_signature: OnceLock::new() }); + whole_code: whole.to_vec(), whole: WholeBuild::new(), plan: Arc::downgrade(&plan), indirect: IndirectBuild::new() }); + retain_indirect_plan(plan.clone()); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -184,6 +301,8 @@ impl Drop for Scratch { struct Recording { scratch: Arc<Scratch>, + /// Keep the title-visible direct first piece alive while this recording may still execute. + /// Indirect execution uses its separate CBV-compatible duplicates. first: ID3D12PipelineState, chain: Arc<Chain>, _indirect_commands: Option<ID3D12Resource>, @@ -335,13 +454,21 @@ fn indirect_rounds() -> u32 { /// slicer writes either bounded piece commands or the whole-form command, never a partial chain. pub(in crate::hle::d3d12x) unsafe fn execute_indirect( list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, args: u64, - bind: impl FnOnce() -> Result<(), String>, + bind: impl FnOnce(usize) -> Result<(), String>, ) -> Result<bool, String> { let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(false) }; - let whole = match chain.whole.ready() { + match chain.whole.ready() { None => return Ok(false), - Some(Ok(pso)) => pso, + Some(Ok(_)) => {} Some(Err(hr)) => return Err(format!("whole compute pipeline ({hr:#x})")), + } + let indirect = match chain.indirect.result.get() { + Some(Ok(indirect)) => indirect.clone(), + Some(Err(_)) => return Ok(false), + None => { + request_indirect(&chain); + return Ok(false); + } }; let allocator = if super::super::alloc_pool::enabled() { super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) @@ -351,27 +478,19 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( let Some((scratch, _)) = scratch_for(&chain.builder.device, list.as_raw() as usize, allocator, scratch_budget(), group) else { return Ok(false); }; - let signature = match chain.indirect_signature.get() { - Some(sig) => sig.clone(), - None => { - let sig = pso::chain_command_signature(&chain.builder.device, &chain.builder.signature)?; - chain.indirect_signature.get_or_init(|| sig).clone() - } - }; - let whole_signature = pso::dispatch_command_signature(&chain.builder.device)?; + let signature = pso::dispatch_command_signature(&chain.builder.device)?; let rounds = indirect_rounds(); - let pieces = chain.tail.len() as u32 + 1; - let commands = pso::chain_commands_buffer(&chain.builder.device, rounds, pieces) + let commands = pso::chain_commands_buffer(&chain.builder.device, rounds) .ok_or("no command buffer for split ExecuteIndirect")?; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); - pso::record_indirect_slicer(list, args, rounds, (scratch.bytes / group).max(1), pieces, &commands)?; - let bound = bind(); + pso::record_indirect_slicer(list, args, rounds, (scratch.bytes / group).max(1), &commands)?; + let bound = bind(indirect.signature.as_raw() as usize); if bound.is_ok() { - list.SetPipelineState(&whole); - list.ExecuteIndirect(&whole_signature, 1, &commands, - pso::chain_tail_offset(rounds, pieces), None::<&ID3D12Resource>, 0); + list.SetPipelineState(&indirect.whole); + list.ExecuteIndirect(&signature, 1, &commands, + pso::chain_tail_offset(rounds), None::<&ID3D12Resource>, 0); pso::record_dispatch_chain_indirect(list, &signature, &commands, rounds, &scratch.buffer, - std::iter::once(&first).chain(&chain.tail)); + indirect.pieces.iter()); } RECORDINGS.lock().unwrap().entry(allocator).or_default().push(Arc::new(Recording { scratch, first, chain, _indirect_commands: Some(commands), @@ -386,6 +505,33 @@ mod tests { const MB: u64 = 1 << 20; + #[test] + fn retained_indirect_plans_are_deduplicated_and_bounded() { + let plan = |byte: u8| Arc::new(DispatchChain { + pieces: vec![vec![byte; 40], vec![byte; 40]], + dwords_per_group: 4, + }); + let (first, second) = (plan(1), plan(2)); + let first_weak = Arc::downgrade(&first); + let mut cache = PlanCache::default(); + cache.insert(first.clone(), 100); + cache.insert(first, 100); + assert_eq!((cache.plans.len(), cache.bytes), (1, 80)); + cache.insert(second, 100); + assert_eq!((cache.plans.len(), cache.bytes), (1, 80)); + assert!(first_weak.upgrade().is_none(), "the oldest plan was released at the cap"); + } + + #[test] + fn indirect_variant_source_admission_never_exceeds_its_cap() { + let used = AtomicUsize::new(0); + assert!(reserve_indirect_source(&used, 60, 100)); + assert!(!reserve_indirect_source(&used, 41, 100)); + assert_eq!(used.load(Ordering::Relaxed), 60); + assert!(reserve_indirect_source(&used, 40, 100)); + assert_eq!(used.load(Ordering::Relaxed), 100); + } + #[test] fn signature_identity_includes_sampler_words_order_and_comparison() { let a = ([1, 2, 3, 4], false); @@ -508,18 +654,25 @@ mod tests { let first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap(); let whole = WholeBuild::new(); whole.get_or_build(std::time::Instant::now(), || Ok(first.clone())).unwrap(); - let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs, samplers: Vec::new(), - flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), samplers: Vec::new(), + flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0, mode: ComputeBuild::DirectChain }); let key = first.as_raw() as usize; + let plan = Arc::new(DispatchChain { pieces: vec![dxil.clone(), dxil.clone()], dwords_per_group: 4 }); + assert!(reserve_indirect_source(&INDIRECT_VARIANT_SOURCE, 1, INDIRECT_VARIANT_BYTES)); + let indirect = Arc::new(IndirectChain { signature: rs.clone(), whole: first.clone(), + pieces: vec![first.clone(), first.clone()], _charge: IndirectCharge(1) }); + let indirect_build = IndirectBuild::new(); + indirect_build.requested.store(true, Ordering::Relaxed); + indirect_build.result.set(Ok(indirect)).unwrap_or_else(|_| unreachable!()); CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, - whole_code: Vec::new(), whole, indirect_signature: OnceLock::new() })); + whole_code: Vec::new(), whole, plan: Arc::downgrade(&plan), indirect: indirect_build })); let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize); super::super::super::alloc_pool::created_on(raw_list, allocator, ty.0); - let args = pso::chain_commands_buffer(&dev, 1, 1).unwrap(); - assert_eq!(execute_indirect(&list, key, allocator, args.GetGPUVirtualAddress(), || Err("bind failed".into())), Err("bind failed".into())); + let args = pso::chain_commands_buffer(&dev, 1).unwrap(); + assert_eq!(execute_indirect(&list, key, allocator, args.GetGPUVirtualAddress(), |_| Err("bind failed".into())), Err("bind failed".into())); assert!(RECORDINGS.lock().unwrap().get(&allocator).is_some_and(|r| r.iter().any(|r| r._indirect_commands.is_some()))); list.Close().unwrap(); allocator_reset(allocator); From 8191c1b14d7d192379bf82d104243327104bff31 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:25:24 -0800 Subject: [PATCH 177/265] Shaders: report driver-cache write failures A successful offline driver compile could silently fail to persist its blob and repeat the same expensive work on the next run. Count attempted persistence failures, warn once with the affected path, and include the total in the preparation summary without changing completion semantics. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/shaders.rs | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 07f45075d0..f425ffcd30 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1207,6 +1207,8 @@ struct Pipelines { made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, + /// pipelines made successfully whose driver blob could not be persisted + write_failures: AtomicUsize, /// pipelines an OS-backed claim proves another process is already building elsewhere: AtomicUsize, split_programs: AtomicUsize, @@ -1227,6 +1229,25 @@ struct Pipelines { cache_dir: Option<PathBuf>, } +fn record_driver_blob_write(wrote: bool, failures: &AtomicUsize) -> Option<usize> { + (!wrote).then(|| failures.fetch_add(1, Ordering::Relaxed) + 1) +} + +#[cfg(test)] +mod pipeline_write_tests { + use super::record_driver_blob_write; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[test] + fn only_failed_driver_blob_writes_are_counted() { + let failures = AtomicUsize::new(0); + assert_eq!(record_driver_blob_write(true, &failures), None); + assert_eq!(record_driver_blob_write(false, &failures), Some(1)); + assert_eq!(record_driver_blob_write(false, &failures), Some(2)); + assert_eq!(failures.load(Ordering::Relaxed), 2); + } +} + #[derive(Clone, Debug, Eq, Hash, PartialEq)] struct PipelineCacheIdentity { dxil_len: usize, @@ -1770,6 +1791,7 @@ impl Pipelines { made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), + write_failures: AtomicUsize::new(0), elsewhere: AtomicUsize::new(0), split_programs: AtomicUsize::new(0), split_pieces: AtomicUsize::new(0), @@ -1939,11 +1961,17 @@ impl Pipelines { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let pso = unsafe { self.dev.CreateComputePipelineState::<ID3D12PipelineState>(&desc) }; if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { - if let Ok(blob) = unsafe { pso.GetCachedBlob() } { + let wrote = if let Ok(blob) = unsafe { pso.GetCachedBlob() } { let bytes = unsafe { blob.GetBufferPointer() }.cast::<u8>(); let len = unsafe { blob.GetBufferSize() }; - if !bytes.is_null() && len != 0 { - driver_cache::write(path, unsafe { std::slice::from_raw_parts(bytes, len) }); + !bytes.is_null() && len != 0 + && driver_cache::write(path, unsafe { std::slice::from_raw_parts(bytes, len) }) + } else { + false + }; + if let Some(failures) = record_driver_blob_write(wrote, &self.write_failures) { + if failures == 1 { + crate::xlog_warn!("Shader preparation: failed to persist driver blob {}; this pipeline will be rebuilt on the next run", path.display()); } } } @@ -2128,6 +2156,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on if let Some(p) = pipelines { println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); println!("pipelines loaded from the driver cache {}", p.reused.load(Ordering::Relaxed)); + let write_failures = p.write_failures.load(Ordering::Relaxed); + if write_failures != 0 { + println!("pipeline driver-cache writes failed {write_failures}"); + } let elsewhere = p.elsewhere.load(Ordering::Relaxed); if elsewhere != 0 { println!("pipelines left to another preparation process {elsewhere}"); From c162ffb15427a852a02249c67f4745eb71fe169a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:24:18 -0800 Subject: [PATCH 178/265] Shaders: prewarm observed indirect split pipelines Record the canonical console compute record hash when a split chain reaches ExecuteIndirect. The bounded journal lets used-only preparation distinguish the few split programs whose GPU-written dimensions require the exact whole fallback. Build their duplicate pieces and whole form with the indirect-CBV root and cache namespace, while preserving direct-root pieces and leaving unobserved split programs unchanged. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 4 + crates/xcl/src/eh.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 3 + .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 57 ++++++ crates/xcl/src/hle/d3d12x/used_journal.rs | 3 +- crates/xcl/src/host.rs | 2 + crates/xcl/src/shaders.rs | 180 +++++++++++++----- 7 files changed, 199 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 04832cbe4f..2e43e5afed 100644 --- a/README.md +++ b/README.md @@ -235,6 +235,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - For compute shaders that XCL can split, the runtime first tries the saved driver blob for the whole shader. A usable blob lets the GPU run it in one dispatch. If the blob is missing or the driver rejects it, XCL builds the split pieces. +- A split program first seen through `ExecuteIndirect` is also kept in + `used-indirect-split.txt` beside the DXIL cache. A later `--pipelines --used-only` pass still + builds its direct-dispatch pieces and additionally saves both its pieces and whole fallback under + the indirect root; other split programs do not pay for those potentially long driver compiles. - **`--pipelines` size cap**: a compute program whose DXIL is over 8 MiB and that has no saved blob is left to the runtime instead of being compiled in the pass — those compiles take tens of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB` diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index d2a7674fee..2a94cd36e0 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -137,6 +137,7 @@ unsafe extern "system" fn hk_nt_terminate_process(h: isize, status: i32) -> i32 } crate::log::flush(); crate::hle::d3d12x::pso_async::flush_used_bounded(std::time::Duration::from_millis(100)); + crate::hle::d3d12x::real::flush_indirect_split_records(std::time::Duration::from_millis(100)); } let orig: unsafe extern "system" fn(isize, i32) -> i32 = std::mem::transmute(ORIG_NT_TERMINATE.load(Ordering::Acquire)); orig(h, status) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 0c48fd6ed0..160e58efe0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4855,6 +4855,9 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const pub(super) mod dispatch_chain; pub(crate) use dispatch_chain::log_counts as log_dispatch_chain_counts; +pub(crate) use dispatch_chain::earlier_indirect_used as earlier_indirect_split_records; +pub(crate) use dispatch_chain::flush_indirect_used as flush_indirect_split_records; +pub(crate) use dispatch_chain::shutdown_indirect_used as shutdown_indirect_split_records; pub(super) mod remap_fallback { use super::*; diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 9986c135c2..29db8ef012 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -1,7 +1,9 @@ //! PSOs for a split compute entry. The first piece is the real PSO returned //! to the caller. Other pieces and the lazily built whole form belong to it. use super::*; +use super::super::used_journal::Journal; use crate::gpu::{dxil::kernel::DispatchChain, recomp::pso}; +use std::collections::HashSet; use std::sync::{Arc, LazyLock, OnceLock, Weak}; static PROGRAMS: AtomicU64 = AtomicU64::new(0); @@ -14,6 +16,55 @@ static LIVE: AtomicU64 = AtomicU64::new(0); static PEAK: AtomicU64 = AtomicU64::new(0); static WANTED: AtomicU64 = AtomicU64::new(0); +struct IndirectUsed { + now: Journal, +} + +static INDIRECT_USED: OnceLock<IndirectUsed> = OnceLock::new(); + +fn parse_used(text: &str) -> HashSet<u64> { + text.lines() + .filter_map(|line| u64::from_str_radix(line.trim(), 16).ok()) + .filter(|&record| record != 0) + .collect() +} + +fn indirect_used_path() -> std::path::PathBuf { + crate::gpu::recomp::dxc::cache_dir().join("used-indirect-split.txt") +} + +fn indirect_used() -> &'static IndirectUsed { + INDIRECT_USED.get_or_init(|| { + if cfg!(test) { + return IndirectUsed { now: Journal::memory(HashSet::new()) }; + } + let path = indirect_used_path(); + let earlier = parse_used(&std::fs::read_to_string(&path).unwrap_or_default()); + let now = Journal::file(path, earlier.clone()); + IndirectUsed { now } + }) +} + +fn note_indirect_use(record: u64) { + indirect_used().now.note(record); +} + +pub(crate) fn earlier_indirect_used() -> HashSet<u64> { + parse_used(&std::fs::read_to_string(indirect_used_path()).unwrap_or_default()) +} + +pub(crate) fn shutdown_indirect_used(timeout: std::time::Duration) { + if let Some(used) = INDIRECT_USED.get() { + let _ = used.now.shutdown_bounded(timeout); + } +} + +pub(crate) fn flush_indirect_used(timeout: std::time::Duration) { + if let Some(used) = INDIRECT_USED.get() { + let _ = used.now.flush_bounded(timeout); + } +} + pub(crate) fn log_counts() { let mib = |a: &AtomicU64| a.load(Ordering::Relaxed) >> 20; crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; scratch {} MiB (most {}, largest dispatch {} in one slab)", @@ -457,6 +508,7 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( bind: impl FnOnce(usize) -> Result<(), String>, ) -> Result<bool, String> { let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(false) }; + note_indirect_use(chain.builder.record); match chain.whole.ready() { None => return Ok(false), Some(Ok(_)) => {} @@ -503,6 +555,11 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( mod tests { use super::*; + #[test] + fn indirect_used_records_parse_unique_nonzero_hex() { + assert_eq!(parse_used("1\n0000000000000002\ninvalid\n0\n1\n"), [1, 2].into()); + } + const MB: u64 = 1 << 20; #[test] diff --git a/crates/xcl/src/hle/d3d12x/used_journal.rs b/crates/xcl/src/hle/d3d12x/used_journal.rs index 11f6083082..685b0a0e28 100644 --- a/crates/xcl/src/hle/d3d12x/used_journal.rs +++ b/crates/xcl/src/hle/d3d12x/used_journal.rs @@ -160,8 +160,7 @@ impl Journal { #[cfg(test)] pub(super) fn contains(&self, key: u64) -> bool { self.shared.state.lock().unwrap_or_else(|e| e.into_inner()).seen.contains(&key) } - #[cfg(test)] - fn flush_bounded(&self, timeout: Duration) -> bool { self.wait_bounded(timeout, false) } + pub(super) fn flush_bounded(&self, timeout: Duration) -> bool { self.wait_bounded(timeout, false) } pub(super) fn shutdown_bounded(&self, timeout: Duration) -> bool { self.wait_bounded(timeout, true) } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index cc86e98d64..728be14a41 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -130,6 +130,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::report::write_final(None); crate::log::flush(); crate::hle::d3d12x::pso_async::shutdown_used(); + crate::hle::d3d12x::real::shutdown_indirect_split_records(std::time::Duration::from_millis(500)); crate::hle::d3d12x::real::end_title(0); }); } @@ -175,5 +176,6 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::report::write_final(None); crate::log::flush(); crate::hle::d3d12x::pso_async::shutdown_used(); + crate::hle::d3d12x::real::shutdown_indirect_split_records(std::time::Duration::from_millis(500)); code as i32 } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index f425ffcd30..cd4ef947e5 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -974,9 +974,14 @@ pub fn run(path: &Path, args: &[String]) -> i32 { if opts.precompile { // `--used-only`: only the compute programs whose pipelines an earlier run of a title used let used = opts.used_only.then(crate::hle::d3d12x::pso_async::earlier_used_keys); + let indirect = (opts.used_only && opts.pipelines) + .then(crate::hle::d3d12x::real::earlier_indirect_split_records); // the runtime's key: heap windows with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`) let windows = runtime_windows(); - return precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0); + return precompile( + &input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, + used.as_ref(), indirect.as_ref(), t0, + ); } if opts.direct { return direct_sweep(&input, &opts, t0); @@ -1203,7 +1208,7 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl /// (the > 8 MB HLSL programs DXC compiles at `-O0`, #1269). struct Pipelines { dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, - signatures: Mutex<std::collections::HashMap<(bool, Vec<u32>), windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, + signatures: Mutex<std::collections::HashMap<(PipelineRoot, Vec<u32>), windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, @@ -1213,6 +1218,7 @@ struct Pipelines { elsewhere: AtomicUsize, split_programs: AtomicUsize, split_pieces: AtomicUsize, + indirect_programs: AtomicUsize, /// programs over `max_dxil` with no blob yet, and their DXIL bytes capped: AtomicUsize, capped_bytes: AtomicUsize, @@ -1248,6 +1254,21 @@ mod pipeline_write_tests { } } +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +enum PipelineRoot { + Whole, + DirectChain, + IndirectChain, +} + +fn split_piece_roots(prewarm_indirect: bool) -> &'static [PipelineRoot] { + if prewarm_indirect { + &[PipelineRoot::DirectChain, PipelineRoot::IndirectChain] + } else { + &[PipelineRoot::DirectChain] + } +} + #[derive(Clone, Debug, Eq, Hash, PartialEq)] struct PipelineCacheIdentity { dxil_len: usize, @@ -1255,7 +1276,7 @@ struct PipelineCacheIdentity { dxil_hash_b: u64, flags: i32, node_mask: u32, - chained: bool, + root: PipelineRoot, sampler_words: Vec<u32>, cache_path: Option<PathBuf>, } @@ -1265,7 +1286,7 @@ impl PipelineCacheIdentity { dxil: &[u8], flags: i32, node_mask: u32, - chained: bool, + root: PipelineRoot, sampler_words: Vec<u32>, cache_path: Option<PathBuf>, ) -> Self { @@ -1280,7 +1301,7 @@ impl PipelineCacheIdentity { dxil_hash_b: alt, flags, node_mask, - chained, + root, sampler_words, cache_path, } @@ -1318,33 +1339,40 @@ impl Drop for InflightGuard<'_> { #[cfg(test)] mod inflight_build_tests { - use super::{InflightBuilds, InflightGuard, PipelineCacheIdentity}; + use super::{InflightBuilds, InflightGuard, PipelineCacheIdentity, PipelineRoot}; use std::path::PathBuf; use std::sync::{mpsc, Condvar, Mutex}; use std::time::Duration; - fn identity(dxil: &[u8], flags: i32, node: u32, chained: bool, samplers: &[u32], path: &str) -> PipelineCacheIdentity { - PipelineCacheIdentity::new(dxil, flags, node, chained, samplers.to_vec(), Some(PathBuf::from(path))) + fn identity(dxil: &[u8], flags: i32, node: u32, root: PipelineRoot, samplers: &[u32], path: &str) -> PipelineCacheIdentity { + PipelineCacheIdentity::new(dxil, flags, node, root, samplers.to_vec(), Some(PathBuf::from(path))) } #[test] fn identity_covers_every_pipeline_input() { - let base = identity(b"abc", 0, 0, false, &[1, 2], "a.pso"); - assert_eq!(base, identity(b"abc", 0, 0, false, &[1, 2], "a.pso")); - assert_ne!(base, identity(b"abd", 0, 0, false, &[1, 2], "a.pso")); - assert_ne!(base, identity(b"abc", 1, 0, false, &[1, 2], "a.pso")); - assert_ne!(base, identity(b"abc", 0, 2, false, &[1, 2], "a.pso")); - assert_ne!(base, identity(b"abc", 0, 0, true, &[1, 2], "a.pso")); - assert_ne!(base, identity(b"abc", 0, 0, false, &[1, 3], "a.pso")); - assert_ne!(base, identity(b"abc", 0, 0, false, &[1, 2], "b.pso")); - assert_ne!(base, PipelineCacheIdentity::new(b"abc", 0, 0, false, vec![1, 2], None)); + let base = identity(b"abc", 0, 0, PipelineRoot::Whole, &[1, 2], "a.pso"); + assert_eq!(base, identity(b"abc", 0, 0, PipelineRoot::Whole, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abd", 0, 0, PipelineRoot::Whole, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 1, 0, PipelineRoot::Whole, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 2, PipelineRoot::Whole, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 0, PipelineRoot::DirectChain, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 0, PipelineRoot::IndirectChain, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 0, PipelineRoot::Whole, &[1, 3], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 0, PipelineRoot::Whole, &[1, 2], "b.pso")); + assert_ne!(base, PipelineCacheIdentity::new(b"abc", 0, 0, PipelineRoot::Whole, vec![1, 2], None)); + } + + #[test] + fn indirect_selection_adds_indirect_pieces_without_changing_direct_pieces() { + assert_eq!(super::split_piece_roots(false), &[PipelineRoot::DirectChain]); + assert_eq!(super::split_piece_roots(true), &[PipelineRoot::DirectChain, PipelineRoot::IndirectChain]); } #[test] fn same_build_waits_while_distinct_builds_and_failures_can_proceed() { let state = (Mutex::new(InflightBuilds::default()), Condvar::new()); - let base = identity(b"program", 0, 0, false, &[], "same.pso"); - let other = identity(b"other", 0, 0, false, &[], "other.pso"); + let base = identity(b"program", 0, 0, PipelineRoot::Whole, &[], "same.pso"); + let other = identity(b"other", 0, 0, PipelineRoot::Whole, &[], "other.pso"); let first = InflightGuard::enter(&state, base.clone()); drop(InflightGuard::enter(&state, other)); @@ -1362,7 +1390,7 @@ mod inflight_build_tests { done_rx.recv_timeout(Duration::from_secs(1)).expect("waiter stayed blocked"); }); - let retry = identity(b"retry", 0, 0, false, &[], "retry.pso"); + let retry = identity(b"retry", 0, 0, PipelineRoot::Whole, &[], "retry.pso"); let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let _failed = InflightGuard::enter(&state, retry.clone()); panic!("simulated build failure"); @@ -1795,6 +1823,7 @@ impl Pipelines { elsewhere: AtomicUsize::new(0), split_programs: AtomicUsize::new(0), split_pieces: AtomicUsize::new(0), + indirect_programs: AtomicUsize::new(0), capped: AtomicUsize::new(0), capped_bytes: AtomicUsize::new(0), inflight: (Mutex::new(InflightBuilds::default()), std::sync::Condvar::new()), @@ -1812,53 +1841,68 @@ impl Pipelines { /// dispatch-chain root signature (`.chain.pso`) as the runtime does (`dispatch_chain::build`), /// instead of the unsplit whole container. fn make(&self, c: &recomp::pso::Compiled) { - self.make_with_cache_path(c, None); + self.make_selected(c, false, None); } + #[cfg(test)] fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option<PathBuf>) { + self.make_selected(c, false, path_override); + } + + fn make_selected(&self, c: &recomp::pso::Compiled, prewarm_indirect: bool, path_override: Option<PathBuf>) { if path_override.is_none() { if let Some(chain) = c.dispatch_chain.as_deref().filter(|chain| chain.pieces.len() >= 2) { self.split_programs.fetch_add(1, Ordering::Relaxed); self.split_pieces.fetch_add(chain.pieces.len(), Ordering::Relaxed); - let workers = chain.pieces.len().min(self.most); - if workers <= 1 { - for piece in &chain.pieces { - self.make_one(piece, &c.samplers, true, None); - } - } else { - let next = AtomicUsize::new(0); - std::thread::scope(|s| { - for _ in 0..workers { - s.spawn(|| loop { - let i = next.fetch_add(1, Ordering::Relaxed); - let Some(piece) = chain.pieces.get(i) else { break }; - self.make_one(piece, &c.samplers, true, None); - }); - } - }); + for &root in split_piece_roots(prewarm_indirect) { + self.make_chain_pieces(&chain.pieces, &c.samplers, root); + } + if prewarm_indirect { + self.indirect_programs.fetch_add(1, Ordering::Relaxed); + self.make_one(&c.dxil, &c.samplers, PipelineRoot::IndirectChain, None); } return; } } - self.make_one(&c.dxil, &c.samplers, false, path_override); + self.make_one(&c.dxil, &c.samplers, PipelineRoot::Whole, path_override); + } + + fn make_chain_pieces(&self, pieces: &[Vec<u8>], samplers: &[recomp::pso::StaticSampler], root: PipelineRoot) { + let workers = pieces.len().min(self.most); + if workers <= 1 { + for piece in pieces { + self.make_one(piece, samplers, root, None); + } + } else { + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..workers { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(piece) = pieces.get(i) else { break }; + self.make_one(piece, samplers, root, None); + }); + } + }); + } } - fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option<PathBuf>) { + fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], root: PipelineRoot, path_override: Option<PathBuf>) { use windows::Win32::Graphics::Direct3D12::*; let sampler_words: Vec<u32> = samplers .iter() .flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])) .collect(); - let key = (chained, sampler_words.clone()); + let key = (root, sampler_words.clone()); let rs = { let mut g = self.signatures.lock().unwrap(); match g.get(&key) { Some(rs) => rs.clone(), None => { - let created = if chained { - recomp::pso::dispatch_chain_root_signature(&self.dev, samplers) - } else { - recomp::pso::abi_root_signature_with(&self.dev, true, samplers) + let created = match root { + PipelineRoot::Whole => recomp::pso::abi_root_signature_with(&self.dev, true, samplers), + PipelineRoot::DirectChain => recomp::pso::dispatch_chain_root_signature(&self.dev, samplers), + PipelineRoot::IndirectChain => recomp::pso::dispatch_chain_indirect_root_signature(&self.dev, samplers), }; match created { Ok(rs) => { @@ -1882,9 +1926,25 @@ impl Pipelines { let path = path_override.or_else(|| { #[cfg(test)] if let Some(dir) = self.cache_dir.as_deref() { - return Some(dir.join(driver_cache::name_for_root(dxil, desc.Flags.0, chained, samplers))); + return Some(dir.join(match root { + PipelineRoot::Whole => driver_cache::name_for_root(dxil, desc.Flags.0, false, samplers), + PipelineRoot::DirectChain => driver_cache::name_for_chain_root_node( + dxil, desc.Flags.0, driver_cache::ChainRoot::DirectConstants, samplers, desc.NodeMask, + ), + PipelineRoot::IndirectChain => driver_cache::name_for_chain_root_node( + dxil, desc.Flags.0, driver_cache::ChainRoot::IndirectCbv, samplers, desc.NodeMask, + ), + })); + } + match root { + PipelineRoot::Whole => driver_cache::path_for_root(dxil, desc.Flags.0, false, samplers), + PipelineRoot::DirectChain => driver_cache::path_for_chain_root_node( + dxil, desc.Flags.0, driver_cache::ChainRoot::DirectConstants, samplers, desc.NodeMask, + ), + PipelineRoot::IndirectChain => driver_cache::path_for_chain_root_node( + dxil, desc.Flags.0, driver_cache::ChainRoot::IndirectCbv, samplers, desc.NodeMask, + ), } - driver_cache::path_for_root(dxil, desc.Flags.0, chained, samplers) }); let mut loaded = path.as_deref().and_then(driver_cache::load); let mut cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); @@ -1898,7 +1958,7 @@ impl Pipelines { drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); return; } - let identity = PipelineCacheIdentity::new(dxil, desc.Flags.0, desc.NodeMask, chained, sampler_words, path.clone()); + let identity = PipelineCacheIdentity::new(dxil, desc.Flags.0, desc.NodeMask, root, sampler_words, path.clone()); let _inflight = InflightGuard::enter(&self.inflight, identity); // A valid blob may be used by many processes, but validation itself can fall through to // a full driver compile when the blob is stale. Claim before either path so only one @@ -1994,6 +2054,10 @@ fn used_compute(blob: &[u8], used: &std::collections::HashSet<u64>) -> bool { used.contains(&crate::hle::d3d12x::real::shaders_key(&[blob.to_vec()])) } +fn used_indirect_split(blob: &[u8], used: &std::collections::HashSet<u64>) -> bool { + used.contains(&crate::gpu::shader::fnv64(blob)) +} + /// Standalone graphics variants whose runtime cache keys can be known without a pipeline pairing. /// Runtime selection also uses the first hardware stage of the first matching FSSM (4: VS, 5: PS). fn standalone_graphics_variants(blob: &[u8], sh: &xbox::XboxShader, split: bool, windows: u32) -> Vec<(recomp::pso::Stage, u32, bool, u32)> { @@ -2007,7 +2071,11 @@ fn standalone_graphics_variants(blob: &[u8], sh: &xbox::XboxShader, split: bool, .collect() } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet<u64>>, t0: std::time::Instant) -> i32 { +fn precompile( + input: &Input, limit: usize, windows: u32, split: Option<bool>, only: Option<&str>, pipelines: bool, + used: Option<&std::collections::HashSet<u64>>, indirect: Option<&std::collections::HashSet<u64>>, + t0: std::time::Instant, +) -> i32 { let pipelines = if pipelines { match Pipelines::new() { Ok(p) => Some(p), @@ -2028,6 +2096,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on if let Some(u) = used { println!("--used-only: {} pipelines earlier runs used (used-pipelines.txt); compute programs of other pipelines are passed over", u.len()); } + if let Some(i) = indirect { + println!("--used-only: {} split programs earlier runs dispatched indirectly get indirect pieces and a whole fallback", i.len()); + } // the compiles run on the DXC pool; these threads translate and keep it fed let threads = recomp::dxc::compile_threads() + 2; // no title runs: only a little commit is kept free besides the compiles @@ -2069,7 +2140,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { - p.make(&c); + if indirect.is_some_and(|i| used_indirect_split(&blob, i)) { + p.make_selected(&c, true, None); + } else { + p.make(&c); + } } compiled.fetch_add(1, Ordering::Relaxed) } @@ -2168,6 +2243,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on if split_programs != 0 { println!("split compute programs: {} ({} pieces)", split_programs, p.split_pieces.load(Ordering::Relaxed)); } + let indirect_programs = p.indirect_programs.load(Ordering::Relaxed); + if indirect_programs != 0 { + println!("indirect split programs (pieces and whole fallback): {indirect_programs}"); + } let capped = p.capped.load(Ordering::Relaxed); if capped != 0 { println!("pipelines over the {} MiB DXIL cap, left to the runtime: {} ({} MiB of DXIL; XCL_PIPELINE_MAX_KB)", p.max_dxil >> 20, capped, p.capped_bytes.load(Ordering::Relaxed) >> 20); @@ -2543,6 +2622,9 @@ mod tests { ", crate::hle::d3d12x::real::shaders_key(&[b.clone()])); let keys: std::collections::HashSet<u64> = text.lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).collect(); assert!(super::used_compute(&b, &keys)); + let indirect: std::collections::HashSet<u64> = [crate::gpu::shader::fnv64(&a)].into(); + assert!(super::used_indirect_split(&a, &indirect)); + assert!(!super::used_indirect_split(&b, &indirect)); } use super::*; From aa446c29c6cd0881e695595951f92c4735c2a9f4 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:28:12 -0800 Subject: [PATCH 179/265] D3D12.X: reuse indirect commands within one recording list ExecuteIndirect command storage was a committed resource per call. Keep one weakly indexed resource per command-list recording and reuse offset zero after a complete UAV-to-read-to-UAV state cycle. Recordings retain it through the native allocator reset, including bind failures, while list reset and release invalidate future reuse. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/pso.rs | 17 ++++- crates/xcl/src/hle/d3d12x/list_x.rs | 2 + .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 62 ++++++++++++++++--- 3 files changed, 73 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index a8f6b5df24..acc5ef06b2 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1548,9 +1548,14 @@ fn indirect_slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12Pip } } +#[cfg(test)] pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32) -> Option<ID3D12Resource> { + chain_commands_storage(dev, chain_tail_offset(rounds) + 12) +} + +pub(crate) unsafe fn chain_commands_storage(dev: &ID3D12Device, bytes: u64) -> Option<ID3D12Resource> { let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: chain_tail_offset(rounds) + 12, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() }; @@ -1583,6 +1588,16 @@ pub(crate) unsafe fn record_indirect_slicer( Ok(()) } +/// Complete the command-storage state cycle. A closed list can then be submitted repeatedly, and +/// another indirect dispatch recorded later on this list can overwrite the same commands at zero. +pub(crate) unsafe fn restore_indirect_commands(list: &ID3D12GraphicsCommandList, commands: &ID3D12Resource) { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(commands), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, + StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS }) } }]); +} + pub(crate) unsafe fn record_dispatch_chain_indirect<'a>( list: &ID3D12GraphicsCommandList, sig: &ID3D12CommandSignature, commands: &ID3D12Resource, rounds: u32, scratch: &ID3D12Resource, pieces: impl IntoIterator<Item = &'a ID3D12PipelineState> + Clone, diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 2647f17441..a2ae0bbf9f 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1245,6 +1245,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C let key = list as usize; // (of a list that was here before and whose release was not seen: the GPU may still use it) release_copy_scratch(key); + super::real::dispatch_chain::list_reset(key); let old = { let mut g = LISTS.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); @@ -1279,6 +1280,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C pub(super) fn on_release(list: usize) { super::alloc_pool::forget_list(list); release_copy_scratch(list); + super::real::dispatch_chain::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { if !old.sparse_writes.is_empty() { diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 29db8ef012..ef101018f4 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -356,17 +356,49 @@ struct Recording { /// Indirect execution uses its separate CBV-compatible duplicates. first: ID3D12PipelineState, chain: Arc<Chain>, - _indirect_commands: Option<ID3D12Resource>, + _indirect_commands: Option<Arc<CommandStorage>>, } static RECORDINGS: LazyLock<Mutex<HashMap<usize, Vec<Arc<Recording>>>>> = LazyLock::new(Default::default); /// list → the allocator it records on and the scratch its chains share: they are dispatched one /// after another, with a barrier between them (the recordings keep it alive) static SHARED: LazyLock<Mutex<HashMap<usize, (usize, std::sync::Weak<Scratch>)>>> = LazyLock::new(Default::default); +/// One recording list reuses indirect commands at offset zero. Buffer state transitions are +/// resource-wide, so storage is deliberately never shared across lists. +static COMMANDS: LazyLock<Mutex<HashMap<usize, (usize, Weak<CommandStorage>)>>> = LazyLock::new(Default::default); + +struct CommandStorage { + buffer: ID3D12Resource, + bytes: u64, +} + +const COMMAND_STORAGE_BYTES: u64 = 64 << 10; + +fn command_storage_bytes(bytes: u64) -> u64 { + bytes.max(COMMAND_STORAGE_BYTES).next_multiple_of(COMMAND_STORAGE_BYTES) +} + +unsafe fn commands_for( + dev: &ID3D12Device, list: usize, allocator: usize, bytes: u64, +) -> Option<Arc<CommandStorage>> { + { + let commands = COMMANDS.lock().unwrap(); + if let Some((_, storage)) = commands.get(&list).filter(|entry| entry.0 == allocator) { + if let Some(storage) = storage.upgrade().filter(|storage| storage.bytes >= bytes) { + return Some(storage); + } + } + } + let size = command_storage_bytes(bytes); + let storage = Arc::new(CommandStorage { buffer: pso::chain_commands_storage(dev, size)?, bytes: size }); + COMMANDS.lock().unwrap().insert(list, (allocator, Arc::downgrade(&storage))); + Some(storage) +} /// `list` begins another recording, which the GPU may run beside the last one. pub(in crate::hle::d3d12x) fn list_reset(list: usize) { SHARED.lock().unwrap().remove(&list); + COMMANDS.lock().unwrap().remove(&list); } /// `to` records right after `from` on the same allocator: its chains go on in `from`'s scratch. @@ -532,18 +564,21 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( }; let signature = pso::dispatch_command_signature(&chain.builder.device)?; let rounds = indirect_rounds(); - let commands = pso::chain_commands_buffer(&chain.builder.device, rounds) - .ok_or("no command buffer for split ExecuteIndirect")?; + let command_bytes = pso::chain_tail_offset(rounds) + 12; + let commands = commands_for( + &chain.builder.device, list.as_raw() as usize, allocator, command_bytes, + ).ok_or("no command buffer for split ExecuteIndirect")?; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); - pso::record_indirect_slicer(list, args, rounds, (scratch.bytes / group).max(1), &commands)?; + pso::record_indirect_slicer(list, args, rounds, (scratch.bytes / group).max(1), &commands.buffer)?; let bound = bind(indirect.signature.as_raw() as usize); if bound.is_ok() { list.SetPipelineState(&indirect.whole); - list.ExecuteIndirect(&signature, 1, &commands, + list.ExecuteIndirect(&signature, 1, &commands.buffer, pso::chain_tail_offset(rounds), None::<&ID3D12Resource>, 0); - pso::record_dispatch_chain_indirect(list, &signature, &commands, rounds, &scratch.buffer, + pso::record_dispatch_chain_indirect(list, &signature, &commands.buffer, rounds, &scratch.buffer, indirect.pieces.iter()); } + pso::restore_indirect_commands(list, &commands.buffer); RECORDINGS.lock().unwrap().entry(allocator).or_default().push(Arc::new(Recording { scratch, first, chain, _indirect_commands: Some(commands), })); @@ -562,6 +597,14 @@ mod tests { const MB: u64 = 1 << 20; + #[test] + fn indirect_command_storage_covers_the_fixed_recording_at_64k_granularity() { + assert_eq!(command_storage_bytes(12), 64 << 10); + assert_eq!(command_storage_bytes((64 << 10) + 1), 128 << 10); + assert!(command_storage_bytes(pso::chain_tail_offset(1024) + 12) + >= pso::chain_tail_offset(1024) + 12); + } + #[test] fn retained_indirect_plans_are_deduplicated_and_bounded() { let plan = |byte: u8| Arc::new(DispatchChain { @@ -730,7 +773,12 @@ mod tests { super::super::super::alloc_pool::created_on(raw_list, allocator, ty.0); let args = pso::chain_commands_buffer(&dev, 1).unwrap(); assert_eq!(execute_indirect(&list, key, allocator, args.GetGPUVirtualAddress(), |_| Err("bind failed".into())), Err("bind failed".into())); - assert!(RECORDINGS.lock().unwrap().get(&allocator).is_some_and(|r| r.iter().any(|r| r._indirect_commands.is_some()))); + let recorded = RECORDINGS.lock().unwrap().get(&allocator).unwrap()[0]._indirect_commands.clone().unwrap(); + let reused = commands_for(&dev, raw_list, allocator, pso::chain_tail_offset(1) + 12).unwrap(); + assert!(Arc::ptr_eq(&recorded, &reused)); + list_reset(raw_list); + let next_recording = commands_for(&dev, raw_list, allocator, pso::chain_tail_offset(1) + 12).unwrap(); + assert!(!Arc::ptr_eq(&recorded, &next_recording)); list.Close().unwrap(); allocator_reset(allocator); list_reset(raw_list); From cf4c3ebc6a1e8df27dc78eef655d579f16edc2bc Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:28:56 -0800 Subject: [PATCH 180/265] D3D12.X: separate tile pool allocation classes Teach the tile allocator to keep evictable and pinned allocations on different backing heaps. Existing production allocation remains pinned, so this is a behavior-neutral foundation for reclaiming fully evicted heaps later. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/vram.rs | 74 ++++++++++++++++++++++--------- 1 file changed, 54 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 07941a052f..8dd802ecbe 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -521,6 +521,8 @@ struct TilePool { free_by_heap: Vec<Vec<u32>>, /// Whether `free_by_heap[h]` must be sorted descending before popping. dirty_sort: Vec<bool>, + /// Whether heap `h` belongs to the evictable allocation class. + heap_evictable: Vec<bool>, /// Total free tiles currently available across all heaps. free_total: usize, /// Tiles given back, reusable after `COOL`. @@ -532,20 +534,23 @@ impl TilePool { TilePool { free_by_heap: Vec::new(), dirty_sort: Vec::new(), + heap_evictable: Vec::new(), free_total: 0, cooling: std::collections::VecDeque::new(), } } - fn add_heap_at(&mut self, slot: u32, pool_pages: u32) { + fn add_heap_at(&mut self, slot: u32, pool_pages: u32, evictable: bool) { let idx = slot as usize; if idx >= self.free_by_heap.len() { self.free_by_heap.resize_with(idx + 1, Vec::new); self.dirty_sort.resize(idx + 1, false); + self.heap_evictable.resize(idx + 1, false); } debug_assert!(self.free_by_heap[idx].is_empty()); self.free_by_heap[idx] = (0..pool_pages).rev().collect(); self.dirty_sort[idx] = false; + self.heap_evictable[idx] = evictable; self.free_total += pool_pages as usize; } @@ -568,6 +573,7 @@ impl TilePool { self.free_by_heap[h].clear(); self.free_by_heap[h].shrink_to_fit(); self.dirty_sort[h] = false; + self.heap_evictable[h] = false; self.free_total -= full; reclaimed.push(h as u32); } @@ -603,16 +609,19 @@ impl TilePool { } } - /// Pick the pool heap to take up to `rem` tiles from: + /// Pick a pool heap in the requested allocation class to take up to `rem` tiles from: /// 1. `preferred` if it fits all `rem` tiles (keeps partial-overlap placements on 1 heap), /// 2. otherwise best-fit heap with `len >= rem` (fits the whole texture in 1 heap without /// splitting fuller pools), /// 3. otherwise the heap with the most free tiles (minimizing distinct heaps touched). - fn pick_heap(&self, rem: usize, preferred: Option<u32>) -> Option<usize> { + fn pick_heap(&self, rem: usize, preferred: Option<u32>, evictable: bool) -> Option<usize> { if self.free_total == 0 { return None; } - if let Some(p) = preferred.map(|h| h as usize).filter(|&h| h < self.free_by_heap.len()) { + if let Some(p) = preferred + .map(|h| h as usize) + .filter(|&h| h < self.free_by_heap.len() && self.heap_evictable.get(h).copied() == Some(evictable)) + { if self.free_by_heap[p].len() >= rem { return Some(p); } @@ -620,6 +629,9 @@ impl TilePool { let mut best_fit: Option<(usize, usize)> = None; let mut largest: Option<(usize, usize)> = None; for (h, tiles) in self.free_by_heap.iter().enumerate() { + if self.heap_evictable.get(h).copied() != Some(evictable) { + continue; + } let len = tiles.len(); if len == 0 { continue; @@ -635,13 +647,14 @@ impl TilePool { best_fit.or(largest).map(|(h, _)| h) } - /// Allocate `count` tiles, preferring a single heap and ascending contiguous offsets. - /// `make_heap` allocates a new backing pool heap of `pool_pages` tiles when `free_total == 0`. - /// On failure, any tiles already taken are returned untouched. + /// Allocate `count` tiles in one allocation class, preferring a single heap and ascending + /// contiguous offsets. `make_heap` allocates a new backing pool heap when the class has no + /// free tiles. On failure, any tiles already taken are returned untouched. fn take_batch( &mut self, count: usize, preferred: Option<u32>, + evictable: bool, now: std::time::Instant, pool_pages: u32, mut make_heap: impl FnMut() -> Option<u32>, @@ -653,14 +666,14 @@ impl TilePool { let mut out = Vec::with_capacity(count); while out.len() < count { let rem = count - out.len(); - let h = match self.pick_heap(rem, preferred) { + let h = match self.pick_heap(rem, preferred, evictable) { Some(h) => h, None => { let Some(new_h) = make_heap() else { self.return_tiles(&out); return None; }; - self.add_heap_at(new_h, pool_pages); + self.add_heap_at(new_h, pool_pages, evictable); new_h as usize } }; @@ -1096,7 +1109,7 @@ impl Pages { let pools = &mut self.pools; let pool = &mut self.pool; - let fresh = pool.take_batch(missing, preferred, now, POOL_PAGES, || { + let fresh = pool.take_batch(missing, preferred, false, now, POOL_PAGES, || { let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) })?; @@ -2019,7 +2032,7 @@ mod tests { const P: u32 = 64; let mut live: Vec<Vec<Tile>> = Vec::new(); for _ in 0..100 { - live.push(pool.take_batch(P as usize, None, t0, P, &mut make).unwrap()); + live.push(pool.take_batch(P as usize, None, false, t0, P, &mut make).unwrap()); } assert_eq!(heaps_made.get(), 100); assert_eq!(pool.free_total, 0); @@ -2039,7 +2052,7 @@ mod tests { // - yield 1 single contiguous tile range (0..32) per texture! let t1 = t0 + COOL + Duration::from_millis(1); for _ in 0..100 { - let alloc = pool.take_batch(32, None, t1, P, &mut make).unwrap(); + let alloc = pool.take_batch(32, None, false, t1, P, &mut make).unwrap(); assert_eq!(alloc.len(), 32); let h0 = alloc[0].0; assert!(alloc.iter().all(|&(h, _)| h == h0), "texture scattered across multiple heaps"); @@ -2055,18 +2068,39 @@ mod tests { pool.push_cooling((3, t), t1); } let t2 = t1 + COOL + Duration::from_millis(1); - let pref = pool.take_batch(8, Some(7), t2, P, &mut make).unwrap(); + let pref = pool.take_batch(8, Some(7), false, t2, P, &mut make).unwrap(); assert!(pref.iter().all(|&(h, _)| h == 7), "preferred heap should be chosen"); assert_eq!(heap_ranges_trimmed(7, &pref), [(true, 10, 8)]); // Rollback on OOM: requesting more tiles than available when make_heap fails returns every // popped tile cleanly so free_total is preserved. assert_eq!(pool.free_total, 8); - let fail = pool.take_batch(16, None, t2, P, || None); + let fail = pool.take_batch(16, None, false, t2, P, || None); assert!(fail.is_none()); assert_eq!(pool.free_total, 8, "OOM rollback must return all popped tiles"); } + #[test] + fn tile_pool_keeps_evictable_and_pinned_tiles_in_separate_heaps() { + let t0 = Instant::now(); + let mut pool = TilePool::new(); + let next_slot = std::cell::Cell::new(0u32); + let mut alloc_slot = || { + let slot = next_slot.get(); + next_slot.set(slot + 1); + Some(slot) + }; + + const P: u32 = 64; + let evictable = pool.take_batch(32, None, true, t0, P, &mut alloc_slot).unwrap(); + let pinned = pool.take_batch(32, None, false, t0, P, &mut alloc_slot).unwrap(); + let evictable_again = pool.take_batch(32, None, true, t0, P, &mut alloc_slot).unwrap(); + + assert!(evictable.iter().chain(&evictable_again).all(|&(h, _)| h == evictable[0].0)); + assert!(pinned.iter().all(|&(h, _)| h == pinned[0].0)); + assert_ne!(evictable[0].0, pinned[0].0, "allocation classes must not share a pool heap"); + } + /// Empty cooled pool heaps (above the warm spare count) are reclaimed cleanly back to VRAM and /// their slot indices can be reused without growing the heap table. #[test] @@ -2084,10 +2118,10 @@ mod tests { }; const P: u32 = 64; - let h0 = pool.take_batch(P as usize, None, t0, P, &mut alloc_slot).unwrap(); - let h1 = pool.take_batch(P as usize, None, t0, P, &mut alloc_slot).unwrap(); - let h2 = pool.take_batch(P as usize, None, t0, P, &mut alloc_slot).unwrap(); - let h3 = pool.take_batch(P as usize, None, t0, P, &mut alloc_slot).unwrap(); + let h0 = pool.take_batch(P as usize, None, false, t0, P, &mut alloc_slot).unwrap(); + let h1 = pool.take_batch(P as usize, None, false, t0, P, &mut alloc_slot).unwrap(); + let h2 = pool.take_batch(P as usize, None, false, t0, P, &mut alloc_slot).unwrap(); + let h3 = pool.take_batch(P as usize, None, false, t0, P, &mut alloc_slot).unwrap(); assert_eq!(next_slot.get(), 4); assert_eq!(pool.free_total, 0); @@ -2112,13 +2146,13 @@ mod tests { free_slots.borrow_mut().extend(reclaimed); // First 64-tile allocation reuses warm spare heap 1 (no new heap allocated). - let reuse_spare = pool.take_batch(P as usize, None, t1, P, &mut alloc_slot).unwrap(); + let reuse_spare = pool.take_batch(P as usize, None, false, t1, P, &mut alloc_slot).unwrap(); assert!(reuse_spare.iter().all(|&(h, _)| h == 1)); assert_eq!(free_slots.borrow().len(), 2); // Next 64-tile allocation consumes heap 0's 63 free tiles plus 1 tile from reclaimed slot 3 // without advancing `next_slot`. - let reuse_slot = pool.take_batch(P as usize, None, t1, P, &mut alloc_slot).unwrap(); + let reuse_slot = pool.take_batch(P as usize, None, false, t1, P, &mut alloc_slot).unwrap(); assert_eq!(reuse_slot.iter().filter(|&&(h, _)| h == 0).count(), 63); assert_eq!(reuse_slot.iter().filter(|&&(h, _)| h == 3).count(), 1); assert_eq!(next_slot.get(), 4); From 70a58f4314baa7dd3e745670602485ed42d49990 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:31:53 -0800 Subject: [PATCH 181/265] D3D12.X: retain tile ownership by mip group MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep each lazily mapped mip group’s page keys separate through normal release, deferred superseded unmap, and cancellation. This prepares fence-safe group retirement without enabling eviction; all current groups still allocate from the pinned class. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/vram.rs | 74 +++++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 8dd802ecbe..89a60beeab 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -251,6 +251,8 @@ struct Target { struct Levels { /// (the group's first subresource, its first tile in the resource, its tiles, mapped) groups: Vec<(u32, u32, u32, bool)>, + /// Physical-page keys owned by each mapped group. + group_tiles: Vec<(Vec<usize>, Vec<(usize, usize)>)>, /// the texture's levels (the last group's go up to here) mips: u32, } @@ -273,7 +275,8 @@ impl Levels { } next = g.1.checked_add(g.2)?; } - (next == total && !groups.is_empty()).then_some(Levels { groups, mips }) + let group_tiles = vec![(Vec::new(), Vec::new()); groups.len()]; + (next == total && !groups.is_empty()).then_some(Levels { groups, group_tiles, mips }) } /// The levels of group `k`. @@ -287,6 +290,12 @@ impl Levels { } } +fn take_level_tiles(levels: Option<&mut Levels>) -> Vec<(Vec<usize>, Vec<(usize, usize)>)> { + levels + .map(|levels| levels.group_tiles.iter_mut().map(std::mem::take).collect()) + .unwrap_or_default() +} + /// `XCL_TEXTURE_LEVEL_PAGES=1` (off by default): a sampled 2D texture of one slice on the /// shared pages gets the pages of a level when an upload first has texels for it. A retail game /// places its streamed textures at full size and maps memory under their levels as it loads @@ -771,6 +780,7 @@ struct HeldUnmap { total: u32, used: Vec<usize>, used_extra: Vec<(usize, usize)>, + level_tiles: Vec<(Vec<usize>, Vec<(usize, usize)>)>, /// Completion marks for every relevant title or upload queue. marks: Vec<(ID3D12Fence, u64)>, } @@ -1039,6 +1049,9 @@ impl Pages { } self.unmap(&held.res, held.total); self.release_tiles(held.used, held.used_extra, now, true); + for (used, used_extra) in held.level_tiles { + self.release_tiles(used, used_extra, now, true); + } done.push(held.res); } else { self.held_unmaps.push(held); @@ -1082,12 +1095,15 @@ impl Pages { /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option<u64>, total: u32) -> Option<(Vec<usize>, Vec<(usize, usize)>)> { - self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize) + self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize, false) } /// `bind` for the tiles `range` of the resource's `total`, which start at subresource `sub`. #[allow(clippy::too_many_arguments)] - unsafe fn bind_range(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option<u64>, total: u32, sub: u32, range: std::ops::Range<usize>) -> Option<(Vec<usize>, Vec<(usize, usize)>)> { + unsafe fn bind_range( + &mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, + console_bytes: Option<u64>, total: u32, sub: u32, range: std::ops::Range<usize>, evictable: bool, + ) -> Option<(Vec<usize>, Vec<(usize, usize)>)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); self.sweep(now); @@ -1109,7 +1125,7 @@ impl Pages { let pools = &mut self.pools; let pool = &mut self.pool; - let fresh = pool.take_batch(missing, preferred, false, now, POOL_PAGES, || { + let fresh = pool.take_batch(missing, preferred, evictable, now, POOL_PAGES, || { let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) })?; @@ -1378,6 +1394,7 @@ pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { total: target.total, used: std::mem::take(&mut target.used), used_extra: std::mem::take(&mut target.used_extra), + level_tiles: take_level_tiles(target.levels.as_mut()), marks, }; target.mapped = false; @@ -1417,6 +1434,14 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { if let Some(target) = pages.targets.get_mut(&key) { target.used = held.used; target.used_extra = held.used_extra; + if let Some(levels) = target.levels.as_mut().filter(|levels| levels.group_tiles.len() == held.level_tiles.len()) { + levels.group_tiles = held.level_tiles; + } else { + for (used, used_extra) in held.level_tiles { + target.used.extend(used); + target.used_extra.extend(used_extra); + } + } target.mapped = true; } drop(g); @@ -1450,7 +1475,7 @@ fn forget_pages(resource: usize) { let mut g = PAGES.lock().unwrap(); let now = std::time::Instant::now(); for pages in g.values_mut().flatten() { - let Some(t) = pages.targets.remove(&resource) else { continue }; + let Some(mut t) = pages.targets.remove(&resource) else { continue }; if let Some(l) = &t.levels { LEVEL_STATS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_sub(t.total as u64, std::sync::atomic::Ordering::Relaxed); @@ -1474,6 +1499,9 @@ fn forget_pages(resource: usize) { } if t.mapped { pages.release_tiles(t.used, t.used_extra, now, false); + for (used, used_extra) in take_level_tiles(t.levels.as_mut()) { + pages.release_tiles(used, used_extra, now, false); + } } return; } @@ -1818,12 +1846,12 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return Vec::new() }; let mut fresh = Vec::new(); for (k, sub, first, n, levels) in todo { - let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize) else { continue }; + let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize, false) else { continue }; let Some(t) = pages.targets.get_mut(&key) else { return fresh }; - t.used.extend(used); - t.used_extra.extend(used_extra); if let Some(l) = t.levels.as_mut() { l.groups[k].3 = true; + l.group_tiles[k].0.extend(used); + l.group_tiles[k].1.extend(used_extra); } if let Some(tm) = t.texels.as_mut() { let added = range_texels(tm.width, tm.height, tm.depth, tm.dim, levels.clone()); @@ -1971,6 +1999,36 @@ mod tests { assert_eq!(Levels::new(&[], None, 0, 1), None); } + #[test] + fn level_tile_owners_round_trip_through_a_deferred_unmap() { + let mut levels = Levels::new(&[(0, 2), (2, 1)], None, 3, 2).unwrap(); + levels.group_tiles[0] = (vec![0x1000, 0x2000], vec![(0x3000, 0)]); + levels.group_tiles[1] = (vec![0x4000], Vec::new()); + let expected = levels.group_tiles.clone(); + + let held = take_level_tiles(Some(&mut levels)); + assert_eq!(held, expected); + assert!(levels.group_tiles.iter().all(|(used, extra)| used.is_empty() && extra.is_empty())); + + levels.group_tiles = held; + assert_eq!(levels.group_tiles, expected, "cancelling a deferred unmap restores every group owner"); + } + + #[test] + fn resource_release_takes_every_level_group_owner() { + let mut levels = Levels::new(&[(0, 1), (1, 1)], Some((2, 1)), 3, 4).unwrap(); + levels.group_tiles[0].0.push(0x1000); + levels.group_tiles[1].1.push((0x2000, 1)); + levels.group_tiles[2].0.push(0x3000); + + let released = take_level_tiles(Some(&mut levels)); + let used: Vec<_> = released.iter().flat_map(|owners| owners.0.iter().copied()).collect(); + let extra: Vec<_> = released.iter().flat_map(|owners| owners.1.iter().copied()).collect(); + assert_eq!(used, [0x1000, 0x3000]); + assert_eq!(extra, [(0x2000, 1)]); + assert!(levels.group_tiles.iter().all(|(used, extra)| used.is_empty() && extra.is_empty())); + } + #[test] fn packed_console_3d_mip_tails_use_the_detile_upload_path() { fn desc( From 6495067f3a7f796267542b88e59e3119b62f70f6 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:33:21 -0800 Subject: [PATCH 182/265] Shaders: prewarm the first indirect split dispatch Selected prewarming built the indirect variants but left the direct whole fallback cold, while ExecuteIndirect refused to use those variants until the direct whole had already been built. This preserved the first-use stall despite a successful prewarm pass. Persist both whole roots for selected programs, start cached indirect loading during chain preparation, and let a ready indirect set run independently. Initialize and gate the use journal off the recording hot path. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 5 +- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 112 ++++++++++++++---- crates/xcl/src/shaders.rs | 21 +++- 3 files changed, 113 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 2e43e5afed..ec5a5121c9 100644 --- a/README.md +++ b/README.md @@ -237,8 +237,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder or the driver rejects it, XCL builds the split pieces. - A split program first seen through `ExecuteIndirect` is also kept in `used-indirect-split.txt` beside the DXIL cache. A later `--pipelines --used-only` pass still - builds its direct-dispatch pieces and additionally saves both its pieces and whole fallback under - the indirect root; other split programs do not pay for those potentially long driver compiles. + builds its direct-dispatch pieces and whole fallback, and additionally saves both its pieces and + whole fallback under the indirect root; other split programs do not pay for those potentially + long driver compiles. - **`--pipelines` size cap**: a compute program whose DXIL is over 8 MiB and that has no saved blob is left to the runtime instead of being compiled in the pass — those compiles take tens of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB` diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index ef101018f4..e980ee6ca3 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -21,6 +21,13 @@ struct IndirectUsed { } static INDIRECT_USED: OnceLock<IndirectUsed> = OnceLock::new(); +static EARLIER_INDIRECT_USED: LazyLock<HashSet<u64>> = LazyLock::new(|| { + if cfg!(test) { + HashSet::new() + } else { + parse_used(&std::fs::read_to_string(indirect_used_path()).unwrap_or_default()) + } +}); fn parse_used(text: &str) -> HashSet<u64> { text.lines() @@ -39,18 +46,19 @@ fn indirect_used() -> &'static IndirectUsed { return IndirectUsed { now: Journal::memory(HashSet::new()) }; } let path = indirect_used_path(); - let earlier = parse_used(&std::fs::read_to_string(&path).unwrap_or_default()); - let now = Journal::file(path, earlier.clone()); + let now = Journal::file(path, EARLIER_INDIRECT_USED.clone()); IndirectUsed { now } }) } -fn note_indirect_use(record: u64) { - indirect_used().now.note(record); +fn note_indirect_use(chain: &Chain) { + if !chain.indirect_noted.swap(true, Ordering::Relaxed) { + indirect_used().now.note(chain.builder.record); + } } pub(crate) fn earlier_indirect_used() -> HashSet<u64> { - parse_used(&std::fs::read_to_string(indirect_used_path()).unwrap_or_default()) + EARLIER_INDIRECT_USED.clone() } pub(crate) fn shutdown_indirect_used(timeout: std::time::Duration) { @@ -152,6 +160,7 @@ struct Chain { whole: WholeBuild<ID3D12PipelineState>, plan: Weak<DispatchChain>, indirect: IndirectBuild, + indirect_noted: AtomicBool, } struct IndirectChain { @@ -261,6 +270,20 @@ fn build_indirect(chain: &Arc<Chain>) -> Result<Arc<IndirectChain>, HRESULT> { Ok(Arc::new(IndirectChain { signature, whole, pieces, _charge: charge })) } +fn indirect_blobs_present(chain: &Chain, plan: &DispatchChain) -> bool { + plan.pieces.iter().map(Vec::as_slice).chain([chain.whole_code.as_slice()]).all(|dxil| { + super::driver_cache::path_for_chain_root_node( + dxil, + chain.builder.flags.0, + super::driver_cache::ChainRoot::IndirectCbv, + &chain.builder.samplers, + chain.builder.node, + ) + .and_then(|path| std::fs::metadata(path).ok()) + .is_some_and(|metadata| metadata.len() != 0) + }) +} + fn request_indirect(chain: &Arc<Chain>) { if chain.indirect.requested.swap(true, Ordering::AcqRel) { return; @@ -320,8 +343,14 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let mut pieces = built.into_iter().collect::<Option<Vec<_>>>()?.into_iter(); let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, - whole_code: whole.to_vec(), whole: WholeBuild::new(), plan: Arc::downgrade(&plan), indirect: IndirectBuild::new() }); + whole_code: whole.to_vec(), whole: WholeBuild::new(), plan: Arc::downgrade(&plan), + indirect: IndirectBuild::new(), indirect_noted: AtomicBool::new(false) }); retain_indirect_plan(plan.clone()); + // Initialize the journal on this preparation worker, never on the first recording call. + let _ = indirect_used(); + if EARLIER_INDIRECT_USED.contains(&record) && indirect_blobs_present(&chain, &plan) { + request_indirect(&chain); + } PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -532,28 +561,51 @@ fn indirect_rounds() -> u32 { .filter(|&n| n > 0).unwrap_or(16u32).min(1024)) } -/// Run one Dispatch-only indirect command through an existing split chain. Until the whole form -/// is already built, return false so the caller preserves the existing synchronous fallback. The -/// slicer writes either bounded piece commands or the whole-form command, never a partial chain. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum IndirectReadiness { + Run, + Request, + Fallback, + Fail(HRESULT), +} + +fn indirect_readiness( + whole: Option<Result<(), HRESULT>>, + indirect: Option<Result<(), HRESULT>>, +) -> IndirectReadiness { + match (whole, indirect) { + (_, Some(Ok(()))) => IndirectReadiness::Run, + (Some(Err(hr)), _) => IndirectReadiness::Fail(hr), + (Some(Ok(())), None) => IndirectReadiness::Request, + _ => IndirectReadiness::Fallback, + } +} + +/// Run one Dispatch-only indirect command through an existing split chain. A complete indirect +/// set is independent of the direct whole-form build. Otherwise preserve the synchronous fallback; +/// the slicer writes either bounded piece commands or the whole-form command, never a partial chain. pub(in crate::hle::d3d12x) unsafe fn execute_indirect( list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, args: u64, bind: impl FnOnce(usize) -> Result<(), String>, ) -> Result<bool, String> { let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(false) }; - note_indirect_use(chain.builder.record); - match chain.whole.ready() { - None => return Ok(false), - Some(Ok(_)) => {} - Some(Err(hr)) => return Err(format!("whole compute pipeline ({hr:#x})")), - } - let indirect = match chain.indirect.result.get() { - Some(Ok(indirect)) => indirect.clone(), - Some(Err(_)) => return Ok(false), - None => { + note_indirect_use(&chain); + let whole = chain.whole.ready().map(|result| result.map(|_| ())); + let indirect = chain.indirect.result.get().map(|result| match result { + Ok(_) => Ok(()), + Err(hr) => Err(*hr), + }); + match indirect_readiness(whole, indirect) { + IndirectReadiness::Run => {} + IndirectReadiness::Request => { request_indirect(&chain); return Ok(false); } + IndirectReadiness::Fallback => return Ok(false), + IndirectReadiness::Fail(hr) => return Err(format!("whole compute pipeline ({hr:#x})")), }; + let Some(Ok(indirect)) = chain.indirect.result.get() else { unreachable!() }; + let indirect = indirect.clone(); let allocator = if super::super::alloc_pool::enabled() { super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) } else { allocator }; @@ -595,6 +647,25 @@ mod tests { assert_eq!(parse_used("1\n0000000000000002\ninvalid\n0\n1\n"), [1, 2].into()); } + #[test] + fn ready_indirect_set_does_not_wait_for_direct_whole() { + assert_eq!(indirect_readiness(None, Some(Ok(()))), IndirectReadiness::Run); + assert_eq!( + indirect_readiness(Some(Err(E_INVALIDARG)), Some(Ok(()))), + IndirectReadiness::Run, + ); + assert_eq!(indirect_readiness(Some(Ok(())), None), IndirectReadiness::Request); + assert_eq!(indirect_readiness(None, None), IndirectReadiness::Fallback); + assert_eq!( + indirect_readiness(Some(Ok(())), Some(Err(E_INVALIDARG))), + IndirectReadiness::Fallback, + ); + assert_eq!( + indirect_readiness(Some(Err(E_INVALIDARG)), Some(Err(E_OUTOFMEMORY))), + IndirectReadiness::Fail(E_INVALIDARG), + ); + } + const MB: u64 = 1 << 20; #[test] @@ -765,7 +836,8 @@ mod tests { indirect_build.requested.store(true, Ordering::Relaxed); indirect_build.result.set(Ok(indirect)).unwrap_or_else(|_| unreachable!()); CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, - whole_code: Vec::new(), whole, plan: Arc::downgrade(&plan), indirect: indirect_build })); + whole_code: Vec::new(), whole, plan: Arc::downgrade(&plan), indirect: indirect_build, + indirect_noted: AtomicBool::new(false) })); let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index cd4ef947e5..18a158fabc 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1269,6 +1269,14 @@ fn split_piece_roots(prewarm_indirect: bool) -> &'static [PipelineRoot] { } } +fn split_whole_roots(prewarm_indirect: bool) -> &'static [PipelineRoot] { + if prewarm_indirect { + &[PipelineRoot::DirectChain, PipelineRoot::IndirectChain] + } else { + &[] + } +} + #[derive(Clone, Debug, Eq, Hash, PartialEq)] struct PipelineCacheIdentity { dxil_len: usize, @@ -1366,6 +1374,11 @@ mod inflight_build_tests { fn indirect_selection_adds_indirect_pieces_without_changing_direct_pieces() { assert_eq!(super::split_piece_roots(false), &[PipelineRoot::DirectChain]); assert_eq!(super::split_piece_roots(true), &[PipelineRoot::DirectChain, PipelineRoot::IndirectChain]); + assert!(super::split_whole_roots(false).is_empty()); + assert_eq!( + super::split_whole_roots(true), + &[PipelineRoot::DirectChain, PipelineRoot::IndirectChain], + ); } #[test] @@ -1859,7 +1872,9 @@ impl Pipelines { } if prewarm_indirect { self.indirect_programs.fetch_add(1, Ordering::Relaxed); - self.make_one(&c.dxil, &c.samplers, PipelineRoot::IndirectChain, None); + for &root in split_whole_roots(true) { + self.make_one(&c.dxil, &c.samplers, root, None); + } } return; } @@ -2097,7 +2112,7 @@ fn precompile( println!("--used-only: {} pipelines earlier runs used (used-pipelines.txt); compute programs of other pipelines are passed over", u.len()); } if let Some(i) = indirect { - println!("--used-only: {} split programs earlier runs dispatched indirectly get indirect pieces and a whole fallback", i.len()); + println!("--used-only: {} split programs earlier runs dispatched indirectly get direct and indirect pieces/whole", i.len()); } // the compiles run on the DXC pool; these threads translate and keep it fed let threads = recomp::dxc::compile_threads() + 2; @@ -2245,7 +2260,7 @@ fn precompile( } let indirect_programs = p.indirect_programs.load(Ordering::Relaxed); if indirect_programs != 0 { - println!("indirect split programs (pieces and whole fallback): {indirect_programs}"); + println!("indirect split programs (direct and indirect pieces/whole): {indirect_programs}"); } let capped = p.capped.load(Ordering::Relaxed); if capped != 0 { From 27f8efedbfc09061875d98f2e0a1071014d9f70b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:37:09 -0800 Subject: [PATCH 183/265] Shaders: report durable pipeline preparation outcomes A successful offline PSO creation did not say whether it produced a reusable driver blob. Count only successful fresh creations and assign each exactly one terminal persistence outcome: saved, unavailable, disabled, or write failed. Preserve the existing cache-hit, refusal, and failure output while making cold preparation results auditable. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/shaders.rs | 161 +++++++++++++++++++++++++++++++------- 1 file changed, 133 insertions(+), 28 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 18a158fabc..562eb04dc5 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; @@ -1212,8 +1212,11 @@ struct Pipelines { made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, - /// pipelines made successfully whose driver blob could not be persisted - write_failures: AtomicUsize, + /// Successful uncached native creations (as distinct from accepted saved blobs). + created: AtomicUsize, + /// What durable artifact, if any, each successful uncached creation produced. + persistence: PersistenceCounters, + persistence_warned: AtomicBool, /// pipelines an OS-backed claim proves another process is already building elsewhere: AtomicUsize, split_programs: AtomicUsize, @@ -1235,22 +1238,100 @@ struct Pipelines { cache_dir: Option<PathBuf>, } -fn record_driver_blob_write(wrote: bool, failures: &AtomicUsize) -> Option<usize> { - (!wrote).then(|| failures.fetch_add(1, Ordering::Relaxed) + 1) +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum PersistenceOutcome { + Saved, + BlobUnavailable, + Disabled, + WriteFailed, +} + +#[derive(Default)] +struct PersistenceCounters { + saved: AtomicUsize, + blob_unavailable: AtomicUsize, + disabled: AtomicUsize, + write_failed: AtomicUsize, +} + +#[derive(Debug, Default, Eq, PartialEq)] +struct PersistenceSnapshot { + saved: usize, + blob_unavailable: usize, + disabled: usize, + write_failed: usize, +} + +impl PersistenceCounters { + fn note(&self, outcome: PersistenceOutcome) { + let counter = match outcome { + PersistenceOutcome::Saved => &self.saved, + PersistenceOutcome::BlobUnavailable => &self.blob_unavailable, + PersistenceOutcome::Disabled => &self.disabled, + PersistenceOutcome::WriteFailed => &self.write_failed, + }; + counter.fetch_add(1, Ordering::Relaxed); + } + + fn snapshot(&self) -> PersistenceSnapshot { + PersistenceSnapshot { + saved: self.saved.load(Ordering::Relaxed), + blob_unavailable: self.blob_unavailable.load(Ordering::Relaxed), + disabled: self.disabled.load(Ordering::Relaxed), + write_failed: self.write_failed.load(Ordering::Relaxed), + } + } +} + +impl PersistenceSnapshot { + fn total(&self) -> usize { + self.saved + self.blob_unavailable + self.disabled + self.write_failed + } +} + +fn record_fresh_creation( + outcome: Option<PersistenceOutcome>, created: &AtomicUsize, persistence: &PersistenceCounters, +) { + let Some(outcome) = outcome else { return }; + created.fetch_add(1, Ordering::Relaxed); + persistence.note(outcome); } #[cfg(test)] -mod pipeline_write_tests { - use super::record_driver_blob_write; +mod pipeline_persistence_tests { + use super::{ + record_fresh_creation, PersistenceCounters, PersistenceOutcome, PersistenceSnapshot, + }; use std::sync::atomic::{AtomicUsize, Ordering}; #[test] - fn only_failed_driver_blob_writes_are_counted() { - let failures = AtomicUsize::new(0); - assert_eq!(record_driver_blob_write(true, &failures), None); - assert_eq!(record_driver_blob_write(false, &failures), Some(1)); - assert_eq!(record_driver_blob_write(false, &failures), Some(2)); - assert_eq!(failures.load(Ordering::Relaxed), 2); + fn every_fresh_creation_has_one_persistence_outcome() { + let created = AtomicUsize::new(0); + let counters = PersistenceCounters::default(); + record_fresh_creation(None, &created, &counters); + assert_eq!( + created.load(Ordering::Relaxed), + 0, + "a failed native creation has no persistence outcome", + ); + for outcome in [ + PersistenceOutcome::Saved, + PersistenceOutcome::BlobUnavailable, + PersistenceOutcome::Disabled, + PersistenceOutcome::WriteFailed, + PersistenceOutcome::WriteFailed, + ] { + record_fresh_creation(Some(outcome), &created, &counters); + } + let snapshot = counters.snapshot(); + assert_eq!(snapshot, PersistenceSnapshot { + saved: 1, + blob_unavailable: 1, + disabled: 1, + write_failed: 2, + }); + assert_eq!(snapshot.total(), 5); + assert_eq!(snapshot.total(), created.load(Ordering::Relaxed)); } } @@ -1832,7 +1913,9 @@ impl Pipelines { made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), - write_failures: AtomicUsize::new(0), + created: AtomicUsize::new(0), + persistence: PersistenceCounters::default(), + persistence_warned: AtomicBool::new(false), elsewhere: AtomicUsize::new(0), split_programs: AtomicUsize::new(0), split_pieces: AtomicUsize::new(0), @@ -2035,17 +2118,29 @@ impl Pipelines { } else { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let pso = unsafe { self.dev.CreateComputePipelineState::<ID3D12PipelineState>(&desc) }; - if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { - let wrote = if let Ok(blob) = unsafe { pso.GetCachedBlob() } { - let bytes = unsafe { blob.GetBufferPointer() }.cast::<u8>(); - let len = unsafe { blob.GetBufferSize() }; - !bytes.is_null() && len != 0 - && driver_cache::write(path, unsafe { std::slice::from_raw_parts(bytes, len) }) - } else { - false - }; - if let Some(failures) = record_driver_blob_write(wrote, &self.write_failures) { - if failures == 1 { + let persistence = pso.as_ref().ok().map(|pso| match path.as_deref() { + None => PersistenceOutcome::Disabled, + Some(path) => match unsafe { pso.GetCachedBlob() } { + Ok(blob) => { + let bytes = unsafe { blob.GetBufferPointer() }.cast::<u8>(); + let len = unsafe { blob.GetBufferSize() }; + if bytes.is_null() || len == 0 { + PersistenceOutcome::BlobUnavailable + } else if driver_cache::write(path, unsafe { std::slice::from_raw_parts(bytes, len) }) { + PersistenceOutcome::Saved + } else { + PersistenceOutcome::WriteFailed + } + } + Err(_) => PersistenceOutcome::BlobUnavailable, + }, + }); + record_fresh_creation(persistence, &self.created, &self.persistence); + if let Some(outcome) = persistence { + if matches!(outcome, PersistenceOutcome::BlobUnavailable | PersistenceOutcome::WriteFailed) + && !self.persistence_warned.swap(true, Ordering::Relaxed) + { + if let Some(path) = path.as_deref() { crate::xlog_warn!("Shader preparation: failed to persist driver blob {}; this pipeline will be rebuilt on the next run", path.display()); } } @@ -2246,9 +2341,19 @@ fn precompile( if let Some(p) = pipelines { println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); println!("pipelines loaded from the driver cache {}", p.reused.load(Ordering::Relaxed)); - let write_failures = p.write_failures.load(Ordering::Relaxed); - if write_failures != 0 { - println!("pipeline driver-cache writes failed {write_failures}"); + let created = p.created.load(Ordering::Relaxed); + let persistence = p.persistence.snapshot(); + println!( + "fresh GPU pipeline creations {created}: driver blobs saved {}, unavailable {}, persistence disabled {}, cache writes failed {}", + persistence.saved, persistence.blob_unavailable, persistence.disabled, persistence.write_failed, + ); + debug_assert_eq!(persistence.total(), created); + debug_assert_eq!( + created + p.reused.load(Ordering::Relaxed), + p.made.load(Ordering::Relaxed), + ); + if persistence.write_failed != 0 { + println!("pipeline driver-cache writes failed {}", persistence.write_failed); } let elsewhere = p.elsewhere.load(Ordering::Relaxed); if elsewhere != 0 { From f574f0cab08f6a43e35787a4f067891176e692f4 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:37:56 -0800 Subject: [PATCH 184/265] D3D12.X: attribute CPU-write looks only during activity runs XCL_ACTIVITY now reports the foreground cost of each serialized look before title submission: write-watch bytes, ranges and dirty pages; sparse lock, scan and upload phases; and remaining texture refresh work. When activity reporting is disabled, remove the prior unconditional sparse timing clocks, range-byte sums, atomic counter updates and power-of-two timing logs. GetWriteWatch retains its atomic retrieve-and-reset behavior. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 7 +- crates/xcl/src/hle/d3d12x/sparse.rs | 130 ++++++++++++++------ crates/xcl/src/hle/d3d12x/title_textures.rs | 22 +++- crates/xcl/src/host.rs | 6 + 4 files changed, 121 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index ec5a5121c9..60e9dc2307 100644 --- a/README.md +++ b/README.md @@ -328,9 +328,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder line with what the title did in that time (presents, submits, draws, dispatches, frame-event waits, DirectStorage requests), a `memory:` line with the process's commit and video memory in use, a `memory by owner` line splitting the known XCL allocations from `other`, and sampled - texture resident / SRV-addressable / virtual texel totals. A negative `other` exposes an - overlapping or stale sample; unavailable adapter segments say `unknown`. Where the lines stop - changing is where the title stopped. + texture resident / SRV-addressable / virtual texel totals, and the foreground CPU time spent + looking for CPU writes before submits (write-watch bytes/ranges/pages, sparse copy phases, and + other refresh work). A negative `other` exposes an overlapping or stale sample; unavailable + adapter segments say `unknown`. Where the lines stop changing is where the title stopped. - `XCL_THREAD_DUMP_AT=s1,s2,…`: at each of those seconds after the start, the state of every thread of the title goes into `xcl.log`, for a title that stalls. - `XCL_TRACE_FAULTS=1` (any value): the first 32 access violations are logged as they are raised diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 106bd0713d..79fcb2c963 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1888,14 +1888,62 @@ pub fn mapped_ranges() -> Vec<(usize, usize)> { s.runs.clone().unwrap_or_default() } -/// time spent and pages found by the write-watch scans (`refresh_once`), for the timing line -static WATCH: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; -/// [lock wait, chunk scan, upload] in µs, runs uploaded -static PHASES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; +/// `XCL_ACTIVITY` look counters: whole µs, write-watch µs, dirty pages, looks, watched bytes, +/// watched ranges, sparse lock/scan/upload µs, and sparse runs. Callers touch them only while +/// activity reporting is enabled, so normal title submission pays no clocks or atomic updates. +static LOOK: [AtomicU64; 10] = [const { AtomicU64::new(0) }; 10]; + +/// One write-watch scan inside a look before title submission. +pub fn note_watch(t: std::time::Duration, pages: usize, watched: usize, ranges: usize) { + LOOK[1].fetch_add(t.as_micros() as u64, Ordering::Relaxed); + LOOK[2].fetch_add(pages as u64, Ordering::Relaxed); + LOOK[4].fetch_add(watched as u64, Ordering::Relaxed); + LOOK[5].fetch_add(ranges as u64, Ordering::Relaxed); +} + +/// The whole serialized look: write-watch, sparse propagation, and title-texture refresh. +pub fn note_look(t: std::time::Duration) { + LOOK[0].fetch_add(t.as_micros() as u64, Ordering::Relaxed); + LOOK[3].fetch_add(1, Ordering::Relaxed); +} + +fn note_sparse_phases( + lock: std::time::Duration, + scan: std::time::Duration, + upload: std::time::Duration, + runs: usize, +) { + LOOK[6].fetch_add(lock.as_micros() as u64, Ordering::Relaxed); + LOOK[7].fetch_add(scan.as_micros() as u64, Ordering::Relaxed); + LOOK[8].fetch_add(upload.as_micros() as u64, Ordering::Relaxed); + LOOK[9].fetch_add(runs as u64, Ordering::Relaxed); +} -pub fn note_watch(t: std::time::Duration, pages: usize) { - WATCH[0].fetch_add(t.as_micros() as u64, Ordering::Relaxed); - WATCH[1].fetch_add(pages as u64, Ordering::Relaxed); +pub fn look_counters() -> [u64; 10] { + std::array::from_fn(|i| LOOK[i].load(Ordering::Relaxed)) +} + +pub fn look_delta(now: [u64; 10], before: [u64; 10]) -> [u64; 10] { + std::array::from_fn(|i| now[i].wrapping_sub(before[i])) +} + +/// Foreground CPU cost of looks before title submits over one `XCL_ACTIVITY` interval. +pub fn look_line(d: [u64; 10], secs: u64) -> String { + let [all, watch, pages, looks, watched, ranges, lock, scan, upload, runs] = d; + let ms = |us: u64| us / 1000; + let copies = lock.saturating_add(scan).saturating_add(upload); + format!( + "looks before submits ({secs} s): {looks} looks took {} ms ({:.1} % of the time): write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); sparse copies lock/scan/upload {}/{}/{} ms ({runs} runs); the rest {} ms", + ms(all), + all as f64 / (secs.max(1) * 10_000) as f64, + ms(watch), + watched as f64 / looks.max(1) as f64 / (1 << 20) as f64, + ranges as f64 / looks.max(1) as f64, + ms(lock), + ms(scan), + ms(upload), + ms(all.saturating_sub(watch.saturating_add(copies))) + ) } fn poll_unique<F>(mut fences: Vec<F>, key: impl Fn(&F) -> usize, mut completed: impl FnMut(&F) -> u64) -> Vec<(F, u64)> { @@ -1946,11 +1994,11 @@ unsafe fn poll_retirement_fences() -> Vec<(ID3D12Fence, u64)> { /// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB /// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video /// memory, and `queue` GPU-waits for that and for new tile mappings. -pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) { +pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize, measure: bool) { let q = queue.as_raw() as usize; + let t0 = measure.then(std::time::Instant::now); let queue_gate = WAIT_GATES.lock().unwrap().entry(q).or_default().clone(); let _queue_serial = queue_gate.lock().unwrap(); - let t0 = std::time::Instant::now(); let observed = poll_retirement_fences(); let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; @@ -1963,8 +2011,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: let sparse_done = observed_completion(&observed, &s.fence, |known, current| known.as_raw() == current.as_raw()); s.retire_free_pools_with(sparse_done); } - let t_locked = std::time::Instant::now(); - PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Ordering::Relaxed); + let t_locked = t0.map(|_| std::time::Instant::now()); let zero_runs = std::mem::take(&mut s.to_zero); for &(a, n) in &zero_runs { s.clear_sent_range(a, n); @@ -1999,9 +2046,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: x = end; } } - let t_scanned = std::time::Instant::now(); - PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Ordering::Relaxed); - PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); + let t_scanned = t_locked.map(|_| std::time::Instant::now()); // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. if !zero_runs.is_empty() { if !s.upload_zeros(&zero_runs) { @@ -2011,28 +2056,14 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: if !dirty_runs.is_empty() { let _ = s.upload_dirty(&dirty_runs); } - PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Ordering::Relaxed); - { - static CALLS: AtomicU64 = AtomicU64::new(0); - static BYTES: AtomicU64 = AtomicU64::new(0); - static MICROS: AtomicU64 = AtomicU64::new(0); - let bytes: usize = zero_runs.iter().chain(dirty_runs.iter()).map(|r| r.1).sum(); - let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; - let b = BYTES.fetch_add(bytes as u64, Ordering::Relaxed) + bytes as u64; - let us = MICROS.fetch_add(t0.elapsed().as_micros() as u64, Ordering::Relaxed) + t0.elapsed().as_micros() as u64; - if n.is_power_of_two() && n >= 16 { - crate::xlog_info!("sparse windows: {n} submits, {} MB of CPU writes uploaded, {} ms spent, {} tiles mapped", b >> 20, us / 1000, s.mapped.len()); - let ms = |x: &AtomicU64| x.load(Ordering::Relaxed) / 1000; - crate::xlog_info!( - "sparse windows timing: write-watch {} ms ({} dirty pages), lock wait {} ms, chunk scan {} ms, upload {} ms ({} runs)", - ms(&WATCH[0]), - WATCH[1].load(Ordering::Relaxed), - ms(&PHASES[0]), - ms(&PHASES[1]), - ms(&PHASES[2]), - PHASES[3].load(Ordering::Relaxed) - ); - } + if let (Some(t0), Some(t_locked), Some(t_scanned)) = (t0, t_locked, t_scanned) { + let t_uploaded = std::time::Instant::now(); + note_sparse_phases( + t_locked.duration_since(t0), + t_scanned.duration_since(t_locked), + t_uploaded.duration_since(t_scanned), + zero_runs.len() + dirty_runs.len(), + ); } dirty_runs.clear(); s.scratch_runs = dirty_runs; @@ -2196,6 +2227,33 @@ fn forget_in(s: &mut State, res: usize) { mod tests { use super::*; + #[test] + fn activity_look_line_splits_foreground_costs() { + let line = look_line([ + 830_000, + 610_000, + 4_800, + 240, + 240 * 1_641 << 20, + 240 * 69, + 40_000, + 30_000, + 50_000, + 90, + ], 2); + assert!(line.contains("240 looks took 830 ms (41.5 % of the time)"), "{line}"); + assert!(line.contains("write-watch 610 ms (1641.0 MB in 69.0 ranges/look, 4800 pages written)"), "{line}"); + assert!(line.contains("sparse copies lock/scan/upload 40/30/50 ms (90 runs); the rest 100 ms"), "{line}"); + let idle = look_line([0; 10], 2); + assert!(idle.contains("0 looks took 0 ms (0.0 % of the time)"), "{idle}"); + assert!(idle.contains("0.0 MB in 0.0 ranges/look"), "{idle}"); + } + + #[test] + fn activity_look_counter_delta_survives_wrap() { + assert_eq!(look_delta([0; 10], [u64::MAX; 10]), [1; 10]); + } + #[test] fn writable_record_requires_every_touched_page_and_tracks_protection() { let mut mapped = FxHashMap::default(); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 258e8f168c..8419a7b5cd 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -879,8 +879,13 @@ pub(super) unsafe fn refresh(queue: *mut c_void) { if BUSY.with(|b| b.get()) { return; } + let measure = super::memory_report::enabled(); + let t0 = measure.then(std::time::Instant::now); let _refresh = REFRESH.lock().unwrap(); - own_work(|| refresh_once(queue)); + own_work(|| refresh_once(queue, measure)); + if let Some(t0) = t0 { + super::sparse::note_look(t0.elapsed()); + } } /// The pages of `[base, base + size)` written since the last look, added to `dirty` and reset @@ -903,16 +908,16 @@ unsafe fn take_written(base: usize, size: usize, buf: &mut [*mut c_void], dirty: } } -unsafe fn refresh_once(queue: *mut c_void) { +unsafe fn refresh_once(queue: *mut c_void, measure: bool) { let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); if !sparse && CPU_TEXTURES_LEN.load(Ordering::Relaxed) == 0 { return; } recheck_gpu_view_sources(); - let watch_t0 = std::time::Instant::now(); let mut page = 0x1000u32; let ranges = cached_watch_ranges(u); + let watch_t0 = measure.then(std::time::Instant::now); let dirty_len = DIRTY_BUF.with(|dcell| { let mut dirty = dcell.borrow_mut(); dirty.clear(); @@ -928,7 +933,14 @@ unsafe fn refresh_once(queue: *mut c_void) { dirty.sort_unstable(); dirty.len() }); - super::sparse::note_watch(watch_t0.elapsed(), dirty_len); + if let Some(watch_t0) = watch_t0 { + super::sparse::note_watch( + watch_t0.elapsed(), + dirty_len, + ranges.iter().fold(0usize, |bytes, range| bytes.saturating_add(range.1)), + ranges.len(), + ); + } if super::present::trace_frame() { // every 600th look: what the CPU's view of a few textures holds now (does the title's // data reach the address at all, and is the texture still kept in step?) @@ -962,7 +974,7 @@ unsafe fn refresh_once(queue: *mut c_void) { if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); - super::sparse::before_execute(q, &dirty, page as usize); + super::sparse::before_execute(q, &dirty, page as usize, measure); super::vram::before_execute(q); }); } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 728be14a41..01ac45823c 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -58,6 +58,7 @@ pub fn host_main(boot_path: &Path) -> i32 { [p, e, d, x, f[0], f[1], f[2], f[3], r, b >> 20, fail] }; let mut last = snap(); + let mut last_looks = crate::hle::d3d12x::sparse::look_counters(); loop { std::thread::sleep(std::time::Duration::from_secs(2)); let now = snap(); @@ -66,6 +67,11 @@ pub fn host_main(boot_path: &Path) -> i32 { "activity (2 s): {} presents, {} submits, {} draws, {} dispatches, {} frame-event waits ({} timed out), {} frame statistics ({} not flipped); DirectStorage {} requests, {} MB, {} failed", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8], d[9], d[10] ); + let looks = crate::hle::d3d12x::sparse::look_counters(); + crate::xlog_info!("{}", crate::hle::d3d12x::sparse::look_line( + crate::hle::d3d12x::sparse::look_delta(looks, last_looks), 2, + )); + last_looks = looks; // where the memory is: the process's commit, video memory, and XCL's parts of it let owner = crate::hle::d3d12x::memory_report::snapshot(); let private = owner.commit.unwrap_or(0); From 3d0d0558cd915804322e74d9108513f17ad38333 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:38:52 -0800 Subject: [PATCH 185/265] D3D12.X: create lists on the active allocator backing A title allocator can already have rotated to another native backing when it creates a command list. Pass that backing to native CreateCommandList and allocator-pool recording ownership while retaining the logical title allocator for list reset, KickoffX, and allocator-release tracking. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/device_x.rs | 21 ++++++++++++++++++-- crates/xcl/src/hle/d3d12x/list_x.rs | 28 ++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 7bd0829645..cff823329a 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -89,6 +89,14 @@ pub(super) unsafe extern "system" fn create_command_allocator_x(this: *mut c_voi real::dev_create_command_allocator(this, pc_list_type(ty) as usize, riid, ppv) } +fn active_list_allocator(alloc: usize) -> usize { + active_list_allocator_with(alloc, super::alloc_pool::current) +} + +fn active_list_allocator_with(alloc: usize, current: impl FnOnce(usize) -> usize) -> usize { + current(alloc) +} + unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let dma = !riid.is_null() && guid_bytes(&*riid) == guid_bytes(&IID_XBOX_DMA_COMMAND_LIST); let riid = if dma { &IID_GRAPHICS_COMMAND_LIST as *const GUID } else { riid }; @@ -97,9 +105,10 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: real::dev_create_command_list_x(this, node, ty, alloc, pso, riid, ppv) } else { let resolved_pso = super::pso_async::resolve_for_bind(pso); - let hr = real::dev_create_command_list(this, node, ty, alloc, resolved_pso, riid, ppv); + let pc_alloc = active_list_allocator(alloc); + let hr = real::dev_create_command_list(this, node, ty, pc_alloc, resolved_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { - super::list_x::on_create(*ppv, alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + super::list_x::on_create_with_backing(*ppv, alloc, pc_alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); super::dred::reset(*ppv); if pso != 0 { super::dred::mark_pipeline(*ppv, pso, resolved_pso); @@ -1333,6 +1342,14 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi mod tests { use super::*; + #[test] + fn new_command_lists_use_the_allocator_pools_active_backing() { + assert_eq!(active_list_allocator_with(0x1000, |alloc| { + assert_eq!(alloc, 0x1000); + 0x2000 + }), 0x2000); + } + #[test] fn console_types_and_descs_become_pc_ones() { assert_eq!(pc_list_type(XBOX_TYPE_DMA), D3D12_COMMAND_LIST_TYPE_COPY.0 as u32); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index a2ae0bbf9f..08eb066478 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1239,6 +1239,14 @@ unsafe fn try_native_depth_bias(list: *mut c_void, bias: DepthBias) -> bool { /// # 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) { + on_create_with_backing(list, alloc, alloc, pso, ty) +} + +/// Record a newly created command list's logical title allocator and native recording backing. +/// +/// # Safety +/// `list` must be null or a valid `ID3D12GraphicsCommandList` COM pointer. +pub(super) unsafe fn on_create_with_backing(list: *mut c_void, alloc: usize, backing: usize, pso: usize, ty: D3D12_COMMAND_LIST_TYPE) { if list.is_null() { return; } @@ -1258,7 +1266,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); } } - super::alloc_pool::created_on(key, alloc, ty.0); + super::alloc_pool::created_on(key, backing, ty.0); m.insert(key, ListState { allocator: alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); old }; @@ -5355,6 +5363,24 @@ mod tests { use super::*; use std::sync::Arc; + #[test] + fn creation_keeps_logical_allocator_separate_from_recording_backing() { + let list = 0x7e57_a101usize as *mut c_void; + let (logical, backing) = (0x7e57_a110usize, 0x7e57_a120usize); + unsafe { on_create_with_backing(list, logical, backing, 0, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + + let tracked = LISTS.lock().unwrap().as_ref().unwrap()[&(list as usize)].allocator; + assert_eq!(tracked, logical); + assert_eq!(super::super::alloc_pool::recording_backing_for_test(list as usize), Some(backing)); + + on_allocator_release(logical); + assert_eq!(LISTS.lock().unwrap().as_ref().unwrap()[&(list as usize)].allocator, 0); + assert_eq!(super::super::alloc_pool::recording_backing_for_test(list as usize), Some(backing)); + + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + super::super::alloc_pool::forget_list(list as usize); + } + #[test] fn mirror_snapshot_keeps_order_and_refreshes_only_on_miss() { let first = (100, 100, 1_000); From 44656285f4a10439a79ad783f1c10979667cd5a5 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:46:40 -0800 Subject: [PATCH 186/265] D3D12.X: attribute submitting-thread descriptor costs Detailed stall tracing already accounts for command recording but leaves descriptor and view creation untimed. Add one submitter-only category around title descriptor API entry points, retaining the existing one-atomic-load disabled path and avoiding a second accounting system. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 8 ++++---- crates/xcl/src/hle/d3d12x/real.rs | 11 ++++++++++- crates/xcl/src/report.rs | 1 + crates/xcl/src/stall.rs | 18 +++++++++++++++++- 4 files changed, 32 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 60e9dc2307..f09bf4e7aa 100644 --- a/README.md +++ b/README.md @@ -316,10 +316,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder With `XCL_STALL_TRACE=1`, `report.json` also contains versioned aggregate counts, total/max time and log2-nanosecond histograms for coarse runtime stalls, plus a bounded list of the newest spans of at least 50 ms. The tracing is off by default. - `XCL_STALL_TRACE_DETAIL=1` includes high-frequency draw, dispatch, binding, barrier, copy and - command-list lifecycle recording costs on the title's first observed submitting thread; it also - enables the coarse trace. Use it only for a diagnostic run because every recorded call reads the - clock and updates counters. + `XCL_STALL_TRACE_DETAIL=1` includes high-frequency draw, dispatch, binding, descriptor/view, + barrier, copy and command-list lifecycle recording costs on the title's first observed submitting + thread; it also enables the coarse trace. Use it only for a diagnostic run because every recorded + call reads the clock and updates counters. - **Diagnostics for a bug report** (all off by default; set them in the environment of `xcl run`): - `XCL_RUN_SECONDS=n`: the title ends itself after `n` seconds, with the GPU drained and `xcl.log` and `report.json` written, so a run of a fixed length can be attached. A value that diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 160e58efe0..8b526dc511 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2048,6 +2048,7 @@ fn note_buffer_view() { /// (`desc::cbv_words`; unified memory, anything else gets an empty V#). No PC CBV: translated /// shaders read buffers through `mem`. unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, cpu: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let Some(slot) = super::console_heap::slot(cpu).filter(|s| !s.sampler) else { let f: unsafe extern "system" fn(*mut c_void, *const D3D12_CONSTANT_BUFFER_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 17)); return f(this, desc, cpu); @@ -2064,6 +2065,7 @@ unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12 /// #22 CreateSampler: the PC sampler at the slot's index, the S# in XCL ABI form (word 3 /// [11:0] = sampler heap index; the state lives in the PC sampler). pub(super) unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, desc: *const D3D12_SAMPLER_DESC, cpu: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let f: unsafe extern "system" fn(*mut c_void, *const D3D12_SAMPLER_DESC, u64) = std::mem::transmute(orig_fn(this, 22)); let Some(slot) = super::console_heap::slot(cpu).filter(|s| s.sampler) else { return f(this, desc, cpu) }; f(this, desc, slot.pc_srv); @@ -2111,6 +2113,7 @@ fn note_mixed_copy() { /// #24 CopyDescriptorsSimple(n, dst, src, type) unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let ty = pc_heap_type(ty); note_copy_call("CopyDescriptorsSimple", n, dst, src); if copy_console_slots(this, n, dst, src, ty) { @@ -2127,6 +2130,7 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 /// #23 CopyDescriptors(dst ranges, src ranges, type): range by range over console slots. #[allow(clippy::too_many_arguments)] unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dsts: *const u64, dsizes: *const u32, ns: u32, srcs: *const u64, ssizes: *const u32, ty: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let ty = pc_heap_type(ty); note_copy_call("CopyDescriptors", nd, if dsts.is_null() { 0 } else { *dsts }, if srcs.is_null() { 0 } else { *srcs }); use super::console_heap::{slot, SAMPLER_SLOT, SLOT}; @@ -2229,6 +2233,7 @@ unsafe extern "system" fn dev_create_uav_checked_x( desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64, ) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { let rd = r.GetDesc(); let is_tex = rd.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER; @@ -2273,6 +2278,7 @@ unsafe extern "system" fn dev_create_uav_checked_x( /// #21 CreateDepthStencilView: the console's view formats as the PC's (`pc_view_format`). unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, cpu: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DEPTH_STENCIL_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 21)); let mut copy = desc.as_ref().copied(); if let Some(c) = copy.as_mut() { @@ -2364,6 +2370,7 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) } unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, cpu: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); let mut copy = desc.as_ref().copied(); if let Some(c) = copy.as_mut() { @@ -2521,6 +2528,7 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u let va = (view.add(0x28) as *const u64).read_unaligned(); let v = (view as *const D3D12_SHADER_RESOURCE_VIEW_DESC).read_unaligned(); if v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let Some(slot) = super::console_heap::slot(cpu) else { return }; let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; @@ -2538,6 +2546,7 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u } let va = (view.add(0x28) as *const u64).read_unaligned(); let v = (view as *const D3D12_UNORDERED_ACCESS_VIEW_DESC).read_unaligned(); + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); if v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER { let Some(slot) = super::console_heap::slot(cpu) else { return }; let b = &v.Anonymous.Buffer; @@ -8482,7 +8491,7 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 // --------------------------------------------------------------------------------------- unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { - let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailBind); + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailViewDescriptor); type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRenderTargetView"))); // a view in a console-only format, or of a target made R8G8B8A8 (`device_x::pc_resource_desc`) diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index ec6a29a674..45aa5584ab 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -101,6 +101,7 @@ fn stall_kind_name(kind: crate::stall::StallKind) -> &'static str { StallKind::DetailDraw => "detail_draw", StallKind::DetailDispatch => "detail_dispatch", StallKind::DetailBind => "detail_bind", + StallKind::DetailViewDescriptor => "detail_view_descriptor", StallKind::DetailBarrier => "detail_barrier", StallKind::DetailCopy => "detail_copy", StallKind::DetailListLifecycle => "detail_list_lifecycle", diff --git a/crates/xcl/src/stall.rs b/crates/xcl/src/stall.rs index c0fc764838..219ce60ba4 100644 --- a/crates/xcl/src/stall.rs +++ b/crates/xcl/src/stall.rs @@ -33,13 +33,14 @@ pub enum StallKind { DetailDraw, DetailDispatch, DetailBind, + DetailViewDescriptor, DetailBarrier, DetailCopy, DetailListLifecycle, } impl StallKind { - pub const ALL: [Self; 20] = [ + pub const ALL: [Self; 21] = [ Self::ShaderTranslation, Self::DxcQueue, Self::DxcCompile, @@ -57,6 +58,7 @@ impl StallKind { Self::DetailDraw, Self::DetailDispatch, Self::DetailBind, + Self::DetailViewDescriptor, Self::DetailBarrier, Self::DetailCopy, Self::DetailListLifecycle, @@ -334,6 +336,20 @@ mod tests { assert_eq!((aggregate.count, aggregate.total_ns), (1, 32)); } + #[test] + fn descriptor_detail_is_attributed_only_to_the_submitter() { + let recorder = Recorder::new(); + recorder.enable_detail(); + recorder.note_submitter(7); + let clock = TestClock::new(100); + assert!(recorder.start_detail_with(StallKind::DetailViewDescriptor, &clock, 8).is_none()); + let span = recorder.start_detail_with(StallKind::DetailViewDescriptor, &clock, 7).unwrap(); + clock.now.store(145, Ordering::Relaxed); + drop(span); + let aggregate = &recorder.snapshot().aggregates[StallKind::DetailViewDescriptor.index()]; + assert_eq!((aggregate.count, aggregate.total_ns), (1, 45)); + } + #[test] fn a_span_updates_its_aggregate_and_log2_bucket() { let recorder = Recorder::new(); From a608310164d32bb7a3b8536953ad2cd740f4f554 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:47:03 -0800 Subject: [PATCH 187/265] D3D12.X: make activity look intervals coherent Publish each completed look as one record so a reporting boundary cannot split its phases from its total. Separate refresh serialization wait from active work, name queue and fence/state phases for what they contain, and retain zero/dirty transfer volume without adding work when activity reporting is disabled. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 7 +- crates/xcl/src/hle/d3d12x/sparse.rs | 159 +++++++++++++------- crates/xcl/src/hle/d3d12x/title_textures.rs | 19 ++- 3 files changed, 119 insertions(+), 66 deletions(-) diff --git a/README.md b/README.md index f09bf4e7aa..1399c3816a 100644 --- a/README.md +++ b/README.md @@ -328,9 +328,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder line with what the title did in that time (presents, submits, draws, dispatches, frame-event waits, DirectStorage requests), a `memory:` line with the process's commit and video memory in use, a `memory by owner` line splitting the known XCL allocations from `other`, and sampled - texture resident / SRV-addressable / virtual texel totals, and the foreground CPU time spent - looking for CPU writes before submits (write-watch bytes/ranges/pages, sparse copy phases, and - other refresh work). A negative `other` exposes an overlapping or stale sample; unavailable + texture resident / SRV-addressable / virtual texel totals, and the active foreground time plus + serialization wait spent looking for CPU writes before submits (write-watch bytes/ranges/pages, + sparse queue/fence-state/copy phases and zero/dirty volume, and other refresh work). A negative + `other` exposes an overlapping or stale sample; unavailable adapter segments say `unknown`. Where the lines stop changing is where the title stopped. - `XCL_THREAD_DUMP_AT=s1,s2,…`: at each of those seconds after the start, the state of every thread of the title goes into `xcl.log`, for a title that stalls. diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 79fcb2c963..9dcb2a8c6c 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1888,61 +1888,87 @@ pub fn mapped_ranges() -> Vec<(usize, usize)> { s.runs.clone().unwrap_or_default() } -/// `XCL_ACTIVITY` look counters: whole µs, write-watch µs, dirty pages, looks, watched bytes, -/// watched ranges, sparse lock/scan/upload µs, and sparse runs. Callers touch them only while -/// activity reporting is enabled, so normal title submission pays no clocks or atomic updates. -static LOOK: [AtomicU64; 10] = [const { AtomicU64::new(0) }; 10]; +const LOOK_FIELDS: usize = 13; +const ACTIVE_US: usize = 0; +const REFRESH_WAIT_US: usize = 1; +const WATCH_US: usize = 2; +const PAGES: usize = 3; +const LOOKS: usize = 4; +const WATCHED: usize = 5; +const RANGES: usize = 6; +const QUEUE_WAIT_US: usize = 7; +const MAINTENANCE_US: usize = 8; +const SCAN_US: usize = 9; +const UPLOAD_US: usize = 10; +const RUNS: usize = 11; +const TRANSFER_BYTES: usize = 12; + +/// One complete `XCL_ACTIVITY` look. It is built without shared updates, then published once so +/// the reporting thread cannot split one look across adjacent intervals. +#[derive(Default)] +pub(super) struct LookSample([u64; LOOK_FIELDS]); + +impl LookSample { + pub(super) fn add(&mut self, field: usize, value: u64) { + self.0[field] = self.0[field].wrapping_add(value); + } -/// One write-watch scan inside a look before title submission. -pub fn note_watch(t: std::time::Duration, pages: usize, watched: usize, ranges: usize) { - LOOK[1].fetch_add(t.as_micros() as u64, Ordering::Relaxed); - LOOK[2].fetch_add(pages as u64, Ordering::Relaxed); - LOOK[4].fetch_add(watched as u64, Ordering::Relaxed); - LOOK[5].fetch_add(ranges as u64, Ordering::Relaxed); + pub(super) fn add_time(&mut self, field: usize, value: std::time::Duration) { + self.add(field, value.as_micros() as u64); + } } -/// The whole serialized look: write-watch, sparse propagation, and title-texture refresh. -pub fn note_look(t: std::time::Duration) { - LOOK[0].fetch_add(t.as_micros() as u64, Ordering::Relaxed); - LOOK[3].fetch_add(1, Ordering::Relaxed); +/// Cumulative complete looks. Disabled title submission never locks or updates this mutex. +static LOOK: Mutex<[u64; LOOK_FIELDS]> = Mutex::new([0; LOOK_FIELDS]); + +fn merge_look(total: &mut [u64; LOOK_FIELDS], sample: [u64; LOOK_FIELDS]) { + for (total, value) in total.iter_mut().zip(sample) { + *total = total.wrapping_add(value); + } } -fn note_sparse_phases( - lock: std::time::Duration, - scan: std::time::Duration, - upload: std::time::Duration, - runs: usize, -) { - LOOK[6].fetch_add(lock.as_micros() as u64, Ordering::Relaxed); - LOOK[7].fetch_add(scan.as_micros() as u64, Ordering::Relaxed); - LOOK[8].fetch_add(upload.as_micros() as u64, Ordering::Relaxed); - LOOK[9].fetch_add(runs as u64, Ordering::Relaxed); +pub(super) fn note_watch(sample: &mut LookSample, t: std::time::Duration, pages: usize, watched: usize, ranges: usize) { + sample.add_time(WATCH_US, t); + sample.add(PAGES, pages as u64); + sample.add(WATCHED, watched as u64); + sample.add(RANGES, ranges as u64); } -pub fn look_counters() -> [u64; 10] { - std::array::from_fn(|i| LOOK[i].load(Ordering::Relaxed)) +pub(super) fn note_look(mut sample: LookSample, active: std::time::Duration, refresh_wait: std::time::Duration) { + sample.add_time(ACTIVE_US, active); + sample.add_time(REFRESH_WAIT_US, refresh_wait); + sample.add(LOOKS, 1); + let mut total = LOOK.lock().unwrap(); + merge_look(&mut total, sample.0); } -pub fn look_delta(now: [u64; 10], before: [u64; 10]) -> [u64; 10] { +pub fn look_counters() -> [u64; LOOK_FIELDS] { + *LOOK.lock().unwrap() +} + +pub fn look_delta(now: [u64; LOOK_FIELDS], before: [u64; LOOK_FIELDS]) -> [u64; LOOK_FIELDS] { std::array::from_fn(|i| now[i].wrapping_sub(before[i])) } -/// Foreground CPU cost of looks before title submits over one `XCL_ACTIVITY` interval. -pub fn look_line(d: [u64; 10], secs: u64) -> String { - let [all, watch, pages, looks, watched, ranges, lock, scan, upload, runs] = d; +/// Active foreground elapsed time and serialization wait before title submits in one interval. +pub fn look_line(d: [u64; LOOK_FIELDS], secs: u64) -> String { + let [active, refresh_wait, watch, pages, looks, watched, ranges, queue_wait, maintenance, scan, upload, runs, transfer_bytes] = d; let ms = |us: u64| us / 1000; - let copies = lock.saturating_add(scan).saturating_add(upload); + let sparse = queue_wait.saturating_add(maintenance).saturating_add(scan).saturating_add(upload); format!( - "looks before submits ({secs} s): {looks} looks took {} ms ({:.1} % of the time): write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); sparse copies lock/scan/upload {}/{}/{} ms ({runs} runs); the rest {} ms", - ms(all), - all as f64 / (secs.max(1) * 10_000) as f64, + "looks before submits ({secs} s): {looks} looks did {} ms active work ({:.1} % of the time) after {} ms waiting for the refresh turn: write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); sparse queue wait/fence+state/scan/upload {}/{}/{}/{} ms ({runs} runs, {:.1} MB zero/dirty bytes); other active work {} ms", + ms(active), + active as f64 / (secs.max(1) * 10_000) as f64, + ms(refresh_wait), ms(watch), watched as f64 / looks.max(1) as f64 / (1 << 20) as f64, ranges as f64 / looks.max(1) as f64, - ms(lock), + ms(queue_wait), + ms(maintenance), ms(scan), ms(upload), - ms(all.saturating_sub(watch.saturating_add(copies))) + transfer_bytes as f64 / (1 << 20) as f64, + ms(active.saturating_sub(watch.saturating_add(sparse))) ) } @@ -1994,14 +2020,21 @@ unsafe fn poll_retirement_fences() -> Vec<(ID3D12Fence, u64)> { /// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB /// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video /// memory, and `queue` GPU-waits for that and for new tile mappings. -pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize, measure: bool) { +pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize, mut look: Option<&mut LookSample>) { let q = queue.as_raw() as usize; - let t0 = measure.then(std::time::Instant::now); + let t0 = look.is_some().then(std::time::Instant::now); let queue_gate = WAIT_GATES.lock().unwrap().entry(q).or_default().clone(); let _queue_serial = queue_gate.lock().unwrap(); + let t_gated = t0.map(|_| std::time::Instant::now()); let observed = poll_retirement_fences(); let mut g = lock_state(); - let Some(s) = g.as_mut() else { return }; + let Some(s) = g.as_mut() else { + if let (Some(sample), Some(t0), Some(t_gated)) = (look.as_deref_mut(), t0, t_gated) { + sample.add_time(QUEUE_WAIT_US, t_gated.duration_since(t0)); + sample.add_time(MAINTENANCE_US, t_gated.elapsed()); + } + return; + }; // the title's work sees what was decommitted unmapped, as it was let flushed = s.flush_parked_with(Some(queue)); let drained = s.drain_quarantined_with(|fence| { @@ -2011,7 +2044,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: let sparse_done = observed_completion(&observed, &s.fence, |known, current| known.as_raw() == current.as_raw()); s.retire_free_pools_with(sparse_done); } - let t_locked = t0.map(|_| std::time::Instant::now()); + let t_maintained = t0.map(|_| std::time::Instant::now()); let zero_runs = std::mem::take(&mut s.to_zero); for &(a, n) in &zero_runs { s.clear_sent_range(a, n); @@ -2046,7 +2079,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: x = end; } } - let t_scanned = t_locked.map(|_| std::time::Instant::now()); + let t_scanned = t0.map(|_| std::time::Instant::now()); // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. if !zero_runs.is_empty() { if !s.upload_zeros(&zero_runs) { @@ -2056,14 +2089,17 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: if !dirty_runs.is_empty() { let _ = s.upload_dirty(&dirty_runs); } - if let (Some(t0), Some(t_locked), Some(t_scanned)) = (t0, t_locked, t_scanned) { + if let (Some(sample), Some(t0), Some(t_gated), Some(t_maintained), Some(t_scanned)) = + (look.as_deref_mut(), t0, t_gated, t_maintained, t_scanned) + { let t_uploaded = std::time::Instant::now(); - note_sparse_phases( - t_locked.duration_since(t0), - t_scanned.duration_since(t_locked), - t_uploaded.duration_since(t_scanned), - zero_runs.len() + dirty_runs.len(), - ); + sample.add_time(QUEUE_WAIT_US, t_gated.duration_since(t0)); + sample.add_time(MAINTENANCE_US, t_maintained.duration_since(t_gated)); + sample.add_time(SCAN_US, t_scanned.duration_since(t_maintained)); + sample.add_time(UPLOAD_US, t_uploaded.duration_since(t_scanned)); + sample.add(RUNS, (zero_runs.len() + dirty_runs.len()) as u64); + let bytes = zero_runs.iter().chain(&dirty_runs).fold(0usize, |sum, run| sum.saturating_add(run.1)); + sample.add(TRANSFER_BYTES, bytes as u64); } dirty_runs.clear(); s.scratch_runs = dirty_runs; @@ -2231,27 +2267,40 @@ mod tests { fn activity_look_line_splits_foreground_costs() { let line = look_line([ 830_000, + 120_000, 610_000, 4_800, 240, 240 * 1_641 << 20, 240 * 69, - 40_000, + 10_000, 30_000, - 50_000, + 40_000, + 40_000, 90, + 96 << 20, ], 2); - assert!(line.contains("240 looks took 830 ms (41.5 % of the time)"), "{line}"); + assert!(line.contains("240 looks did 830 ms active work (41.5 % of the time) after 120 ms waiting"), "{line}"); assert!(line.contains("write-watch 610 ms (1641.0 MB in 69.0 ranges/look, 4800 pages written)"), "{line}"); - assert!(line.contains("sparse copies lock/scan/upload 40/30/50 ms (90 runs); the rest 100 ms"), "{line}"); - let idle = look_line([0; 10], 2); - assert!(idle.contains("0 looks took 0 ms (0.0 % of the time)"), "{idle}"); + assert!(line.contains("sparse queue wait/fence+state/scan/upload 10/30/40/40 ms (90 runs, 96.0 MB zero/dirty bytes); other active work 100 ms"), "{line}"); + let idle = look_line([0; LOOK_FIELDS], 2); + assert!(idle.contains("0 looks did 0 ms active work (0.0 % of the time) after 0 ms waiting"), "{idle}"); assert!(idle.contains("0.0 MB in 0.0 ranges/look"), "{idle}"); } #[test] fn activity_look_counter_delta_survives_wrap() { - assert_eq!(look_delta([0; 10], [u64::MAX; 10]), [1; 10]); + assert_eq!(look_delta([0; LOOK_FIELDS], [u64::MAX; LOOK_FIELDS]), [1; LOOK_FIELDS]); + } + + #[test] + fn activity_look_publishes_one_complete_sample() { + let mut total = [10; LOOK_FIELDS]; + let sample = std::array::from_fn(|i| i as u64); + merge_look(&mut total, sample); + assert_eq!(total, std::array::from_fn(|i| 10 + i as u64)); + merge_look(&mut total, std::array::from_fn(|i| u64::MAX - 9 - i as u64)); + assert_eq!(total, [0; LOOK_FIELDS]); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 8419a7b5cd..7cfb4e1a29 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -880,11 +880,13 @@ pub(super) unsafe fn refresh(queue: *mut c_void) { return; } let measure = super::memory_report::enabled(); - let t0 = measure.then(std::time::Instant::now); + let wait_t0 = measure.then(std::time::Instant::now); let _refresh = REFRESH.lock().unwrap(); - own_work(|| refresh_once(queue, measure)); - if let Some(t0) = t0 { - super::sparse::note_look(t0.elapsed()); + let active_t0 = measure.then(std::time::Instant::now); + let mut look = measure.then(super::sparse::LookSample::default); + own_work(|| refresh_once(queue, look.as_mut())); + if let (Some(wait_t0), Some(active_t0), Some(look)) = (wait_t0, active_t0, look) { + super::sparse::note_look(look, active_t0.elapsed(), active_t0.duration_since(wait_t0)); } } @@ -908,7 +910,7 @@ unsafe fn take_written(base: usize, size: usize, buf: &mut [*mut c_void], dirty: } } -unsafe fn refresh_once(queue: *mut c_void, measure: bool) { +unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse::LookSample>) { let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); if !sparse && CPU_TEXTURES_LEN.load(Ordering::Relaxed) == 0 { @@ -917,7 +919,7 @@ unsafe fn refresh_once(queue: *mut c_void, measure: bool) { recheck_gpu_view_sources(); let mut page = 0x1000u32; let ranges = cached_watch_ranges(u); - let watch_t0 = measure.then(std::time::Instant::now); + let watch_t0 = look.is_some().then(std::time::Instant::now); let dirty_len = DIRTY_BUF.with(|dcell| { let mut dirty = dcell.borrow_mut(); dirty.clear(); @@ -933,8 +935,9 @@ unsafe fn refresh_once(queue: *mut c_void, measure: bool) { dirty.sort_unstable(); dirty.len() }); - if let Some(watch_t0) = watch_t0 { + if let (Some(sample), Some(watch_t0)) = (look.as_deref_mut(), watch_t0) { super::sparse::note_watch( + sample, watch_t0.elapsed(), dirty_len, ranges.iter().fold(0usize, |bytes, range| bytes.saturating_add(range.1)), @@ -974,7 +977,7 @@ unsafe fn refresh_once(queue: *mut c_void, measure: bool) { if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); - super::sparse::before_execute(q, &dirty, page as usize, measure); + super::sparse::before_execute(q, &dirty, page as usize, look.as_deref_mut()); super::vram::before_execute(q); }); } From 36d9ebb9d3e399c5aca7308ba6b2e8b9835c6586 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:45:26 -0800 Subject: [PATCH 188/265] D3D12.X: preserve tile allocation class invariants Keep shared pages keyed by title address so pinned and evictable resources preserve console aliasing. Treat heap classes only as fresh-allocation packing hints, retain one empty pool per class, and include lazy mip-group ownership in test mapping inspection. Checked with cargo check -p xcl --tests --target x86_64-pc-windows-gnu using the host GCC and ar; the library and test target compiled with pre-existing dead-code warnings. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/vram.rs | 113 +++++++++++++++++++++++++----- 1 file changed, 94 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 89a60beeab..3ca925100c 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -530,7 +530,8 @@ struct TilePool { free_by_heap: Vec<Vec<u32>>, /// Whether `free_by_heap[h]` must be sorted descending before popping. dirty_sort: Vec<bool>, - /// Whether heap `h` belongs to the evictable allocation class. + /// Fresh-allocation packing class for heap `h`. Shared address pages may give either class + /// live owners here, so this is never proof that a heap is safe to evict. heap_evictable: Vec<bool>, /// Total free tiles currently available across all heaps. free_total: usize, @@ -564,21 +565,21 @@ impl TilePool { } /// Reclaim completely empty cooled heaps (`free_by_heap[h].len() == pool_pages`), keeping up - /// to `keep_spare` empty heaps warm so steady-state streaming never thrashes `CreateHeap`. + /// to `keep_spare` empty heaps of each class warm so steady-state streaming never thrashes `CreateHeap`. /// Returns the reclaimed heap indices so the caller can drop their `ID3D12Heap`s. fn reclaim_empty_heaps(&mut self, keep_spare: usize, pool_pages: u32) -> Vec<u32> { let full = pool_pages as usize; - let mut empty: Vec<usize> = self - .free_by_heap - .iter() - .enumerate() - .filter_map(|(h, tiles)| (tiles.len() == full).then_some(h)) - .collect(); - if empty.len() <= keep_spare { - return Vec::new(); - } - let mut reclaimed = Vec::with_capacity(empty.len() - keep_spare); - for h in empty.drain(keep_spare..) { + let mut kept = [0usize; 2]; + let mut reclaimed = Vec::new(); + for h in 0..self.free_by_heap.len() { + if self.free_by_heap[h].len() != full { + continue; + } + let class = self.heap_evictable[h] as usize; + if kept[class] < keep_spare { + kept[class] += 1; + continue; + } self.free_by_heap[h].clear(); self.free_by_heap[h].shrink_to_fit(); self.dirty_sort[h] = false; @@ -1739,6 +1740,33 @@ pub(super) fn waited_for_test(dev: usize, queue: usize) -> u64 { /// Tile identities of one mapped resource: title pages, then extra pages. /// A device-wide byte count also falls when unrelated idle pages are swept. +#[cfg(test)] +fn target_page_keys(target: &Target) -> (Vec<usize>, Vec<(usize, usize)>) { + let mut used = target.used.clone(); + let mut extra = target.used_extra.clone(); + if let Some(levels) = &target.levels { + for (level_used, level_extra) in &levels.group_tiles { + used.extend(level_used); + extra.extend(level_extra); + } + } + (used, extra) +} + +#[cfg(test)] +fn target_tiles(pages: &Pages, target: &Target) -> Option<(Vec<Tile>, Vec<Tile>)> { + let (used, extra) = target_page_keys(target); + let used = used + .iter() + .map(|key| pages.pages.get(key).map(|page| page.tile)) + .collect::<Option<Vec<_>>>()?; + let extra = extra + .iter() + .map(|key| pages.extra_pages.get(key).map(|page| page.tile)) + .collect::<Option<Vec<_>>>()?; + (used.len() + extra.len() == target.total as usize).then_some((used, extra)) +} + #[cfg(test)] pub(super) fn mapped_tiles_for(device: usize, resource: usize) -> Option<(Vec<(u32, u32)>, Vec<(u32, u32)>)> { let g = PAGES.lock().unwrap(); @@ -1747,9 +1775,7 @@ pub(super) fn mapped_tiles_for(device: usize, resource: usize) -> Option<(Vec<(u if !target.mapped { return None; } - let used = target.used.iter().map(|key| p.pages.get(key).map(|page| page.tile)).collect::<Option<Vec<_>>>()?; - let extra = target.used_extra.iter().map(|key| p.extra_pages.get(key).map(|page| page.tile)).collect::<Option<Vec<_>>>()?; - (used.len() + extra.len() == target.total as usize).then_some((used, extra)) + target_tiles(p, target) } pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { @@ -1774,9 +1800,7 @@ pub(super) fn tile_mappings_for(device: usize, resource: usize) -> Option<(Vec<( let p = g.get(&device)?.as_ref()?; let target = p.targets.get(&resource)?; if !target.mapped { return None; } - let used = target.used.iter().map(|key| p.pages.get(key).map(|page| page.tile)).collect::<Option<Vec<_>>>()?; - let extra = target.used_extra.iter().map(|key| p.extra_pages.get(key).map(|page| page.tile)).collect::<Option<Vec<_>>>()?; - (used.len() + extra.len() == target.total as usize).then_some((used, extra)) + target_tiles(p, target) } /// (bytes of pages in use by tiled textures, bytes of pool heaps) – `XCL_ACTIVITY` @@ -2029,6 +2053,42 @@ mod tests { assert!(levels.group_tiles.iter().all(|(used, extra)| used.is_empty() && extra.is_empty())); } + #[test] + fn test_mapping_observation_includes_level_group_owners() { + let mut levels = Levels::new(&[(0, 1)], Some((1, 1)), 2, 2).unwrap(); + levels.group_tiles[0].0.push(0x1000); + levels.group_tiles[1].1.push((0x2000, 1)); + let target = Target { + va: 0x1000, + console_bytes: None, + total: 2, + mapped: true, + used: Vec::new(), + used_extra: Vec::new(), + levels: Some(levels), + texels: None, + }; + + assert_eq!(target_page_keys(&target), (vec![0x1000], vec![(0x2000, 1)])); + } + + #[test] + fn shared_page_identity_is_the_title_address_not_allocation_class() { + let mut pages = HashMap::new(); + for _evictable in [false, true] { + pages + .entry(0x1000) + .and_modify(|page: &mut Page| page.users += 1) + .or_insert(Page { tile: (0, 1), users: 1, idle_since: None }); + } + + // Both policies share one page. `heap_evictable` is only a packing hint for fresh tiles; + // future eviction must inspect live page owners rather than trusting the heap class. + assert_eq!(pages.len(), 1); + assert_eq!(pages[&0x1000].users, 2); + assert_eq!(pages[&0x1000].tile, (0, 1)); + } + #[test] fn packed_console_3d_mip_tails_use_the_detile_upload_path() { fn desc( @@ -2159,6 +2219,21 @@ mod tests { assert_ne!(evictable[0].0, pinned[0].0, "allocation classes must not share a pool heap"); } + #[test] + fn tile_pool_keeps_one_warm_spare_for_each_allocation_class() { + const P: u32 = 64; + let mut pool = TilePool::new(); + pool.add_heap_at(0, P, false); + pool.add_heap_at(1, P, false); + pool.add_heap_at(2, P, true); + pool.add_heap_at(3, P, true); + + assert_eq!(pool.reclaim_empty_heaps(1, P), [1, 3]); + assert_eq!(pool.free_total, 2 * P as usize); + assert_eq!(pool.pick_heap(P as usize, None, false), Some(0)); + assert_eq!(pool.pick_heap(P as usize, None, true), Some(2)); + } + /// Empty cooled pool heaps (above the warm spare count) are reclaimed cleanly back to VRAM and /// their slot indices can be reused without growing the heap table. #[test] From 3a42a19336fc2581dc93827b8e91c8c9cf0f012e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:53:36 -0800 Subject: [PATCH 189/265] D3D12.X: report retained pipeline age Measure completed background PSOs retained behind stand-ins and bucket them by frames since completion or last use. The activity-only bind path uses frame-counter atomics, while the two-second observer performs registry scans and deduplicates coalesced builds. Checked with cargo check -p xcl --tests --target x86_64-pc-windows-gnu using the host GCC and ar; the library and test target compiled with pre-existing dead-code warnings. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 4 +- crates/xcl/src/hle/d3d12x/pso_async.rs | 79 ++++++++++++++++++++++++++ crates/xcl/src/host.rs | 8 +++ 3 files changed, 90 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1399c3816a..d82e975104 100644 --- a/README.md +++ b/README.md @@ -328,7 +328,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder line with what the title did in that time (presents, submits, draws, dispatches, frame-event waits, DirectStorage requests), a `memory:` line with the process's commit and video memory in use, a `memory by owner` line splitting the known XCL allocations from `other`, and sampled - texture resident / SRV-addressable / virtual texel totals, and the active foreground time plus + texture resident / SRV-addressable / virtual texel totals. It also reports completed background + pipelines retained behind stand-ins and how many frames ago they were last used, and the + active foreground time plus serialization wait spent looking for CPU writes before submits (write-watch bytes/ranges/pages, sparse queue/fence-state/copy phases and zero/dirty volume, and other refresh work). A negative `other` exposes an overlapping or stale sample; unavailable diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 9b4fe25d95..52bd3e4ec4 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -54,6 +54,10 @@ struct Build { /// the real pipeline state (one owned raw pointer shared by all `Pending`s), 0 until built /// or when building failed real: AtomicUsize, + /// Last frame in which any owner resolved this build, for `XCL_ACTIVITY` retention ages. + last_use_frame: AtomicU64, + /// Frame in which `real` became retained; age never begins before the build completed. + completed_frame: AtomicU64, done: Mutex<bool>, cv: Condvar, /// every stand-in interested in this build was released before it finished @@ -185,6 +189,8 @@ impl Build { tracked: AtomicBool::new(false), queue_state: AtomicU8::new(QUEUE_IDLE), real: AtomicUsize::new(0), + last_use_frame: AtomicU64::new(super::present::presents()), + completed_frame: AtomicU64::new(0), done: Mutex::new(false), cv: Condvar::new(), orphan: Default::default(), @@ -258,6 +264,9 @@ fn mark_queue_done(state: &AtomicU8) -> bool { impl Pending { fn note_use(&self) { + if super::memory_report::enabled() { + self.build.last_use_frame.fetch_max(super::present::presents(), Ordering::Relaxed); + } if self.key != 0 && !self.used.swap(true, Ordering::Relaxed) { used::note(self.key); } @@ -367,6 +376,58 @@ pub fn compute_coalescing_stats() -> ComputeCoalescingStats { COALESCING.snapshot() } +/// Unique completed native pipelines retained behind title-visible stand-ins, by frames since +/// their last use. Measurement only: command lists do not retain bound D3D12 objects, so these +/// ages are not evidence that a pipeline is safe to release. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct RetentionStats { + pub retained_reals: usize, + pub unused_60_frames: usize, + pub unused_600_frames: usize, + pub oldest_unused_frames: u64, +} + +fn retention_stats_from( + now: u64, + builds: impl IntoIterator<Item = (usize, usize, u64, u64)>, +) -> RetentionStats { + let mut seen = std::collections::HashSet::new(); + let mut stats = RetentionStats::default(); + for (identity, real, last_use, completed) in builds { + if real == 0 || !seen.insert(identity) { + continue; + } + let age = now.saturating_sub(last_use.max(completed)); + stats.retained_reals += 1; + stats.unused_60_frames += (age >= 60) as usize; + stats.unused_600_frames += (age >= 600) as usize; + stats.oldest_unused_frames = stats.oldest_unused_frames.max(age); + } + stats +} + +/// Snapshot for the `XCL_ACTIVITY` thread. The registry locks are taken only by that observer; +/// bind-time tracking is a present counter load plus one relaxed atomic maximum. +pub fn retention_stats() -> RetentionStats { + if !super::memory_report::enabled() { + return RetentionStats::default(); + } + let mut builds = Vec::new(); + for shard in &PENDING.shards { + let entries = shard.lock().unwrap(); + builds.extend(entries.iter().flat_map(|map| map.values()).map(|pending| { + let build = &pending.build; + ( + Arc::as_ptr(build) as usize, + build.real.load(Ordering::Acquire), + build.last_use_frame.load(Ordering::Relaxed), + build.completed_frame.load(Ordering::Relaxed), + ) + })); + } + retention_stats_from(super::present::presents(), builds) +} + fn forget_in_flight(build: &Arc<Build>) { let Some(key) = &build.compute_key else { return }; let mut registry = IN_FLIGHT.lock().unwrap(); @@ -383,6 +444,7 @@ fn complete(build: &Arc<Build>, real: usize) { FAILED.fetch_add(1, Ordering::Relaxed); } else { BUILT.fetch_add(1, Ordering::Relaxed); + build.completed_frame.store(super::present::presents(), Ordering::Relaxed); } let orphan = { let mut done = build.done.lock().unwrap(); @@ -1148,6 +1210,23 @@ mod used_tests { assert_eq!(counters.snapshot().peak_in_flight, 2); } + #[test] + fn retention_age_counts_unique_reals_from_completion_or_last_use() { + let stats = retention_stats_from(1_000, [ + (1, 0x101, 200, 300), + (1, 0x101, 200, 300), // another stand-in sharing build 1 + (2, 0x202, 100, 995), + (3, 0, 0, 0), // failed or incomplete + (4, 0x404, 0, 0), + ]); + assert_eq!(stats, RetentionStats { + retained_reals: 3, + unused_60_frames: 2, + unused_600_frames: 2, + oldest_unused_frames: 1_000, + }); + } + fn compute_key(tag: u8) -> super::super::real::compute_build_key::ComputeBuildKey { super::super::real::compute_build_key::ComputeBuildKey::capture( 1, diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 01ac45823c..5cb34eb168 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -94,6 +94,14 @@ pub fn host_main(boot_path: &Path) -> i32 { mb(pools_mapped as u64) ); crate::xlog_info!("{}", owner.line()); + let pso = crate::hle::d3d12x::pso_async::retention_stats(); + crate::xlog_info!( + "pipeline retention: {} completed background PSOs behind stand-ins; {} unused for 60+ frames, {} for 600+ frames; oldest {} frames", + pso.retained_reals, + pso.unused_60_frames, + pso.unused_600_frames, + pso.oldest_unused_frames + ); let ts = crate::hle::d3d12x::vram::texel_stats(); if ts.sampled_textures > 0 { let pct = if ts.total_texels > 0 { ts.resident_texels.saturating_mul(100) / ts.total_texels } else { 0 }; From 054270ca732dc7142df72cdde7cc4501d8f89979 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:54:33 -0800 Subject: [PATCH 190/265] D3D12.X: preserve CPU writes during sparse copy-back A synchronous GPU copy-back previously replaced an entire committed page span and then accepted those bytes as sent state. If the CPU had changed one of its 64-byte chunks after the last upload, that newer value was lost. Land only chunks whose current hash still matches the last-sent hash; leave dirty chunks and hashes unchanged for the next upload look. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 104 ++++++++++++++++++---------- 1 file changed, 68 insertions(+), 36 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 9dcb2a8c6c..f2178abe3b 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -333,6 +333,30 @@ fn push_run(out: &mut Vec<(usize, usize)>, addr: usize, len: usize) { } } +/// Land GPU bytes in one CPU page, 64-byte chunk by chunk. A chunk still matching `sent` has +/// no newer CPU write and may be replaced; a changed chunk keeps its CPU bytes and its old hash, +/// so the next write-watch look uploads it. The hash check and copy are not atomic against a +/// concurrent CPU store: callers rely on the title's fence discipline to exclude stores to the +/// same chunk while its synchronous copy-back lands. +fn land_page(slot: &mut Option<Box<[u64; CHUNKS]>>, page: &mut [u8], at: usize, src: &[u8]) { + debug_assert_eq!(page.len(), PAGE); + debug_assert!(at + src.len() <= page.len()); + let sent = slot.get_or_insert_with(|| Box::new(ZERO_HASHES)); + let end = at + src.len(); + let mut offset = at; + while offset < end { + let chunk = offset / CHUNK; + let chunk_start = chunk * CHUNK; + let copy_end = ((chunk + 1) * CHUNK).min(end); + if chunk_hash(&page[chunk_start..chunk_start + CHUNK]) == sent[chunk] { + let source = offset - at; + page[offset..copy_end].copy_from_slice(&src[source..source + copy_end - offset]); + sent[chunk] = chunk_hash(&page[chunk_start..chunk_start + CHUNK]); + } + offset = copy_end; + } +} + /// Scan a 4 KiB page at `pg`, appending any changed 64-byte chunk runs directly to `out` /// (zero per-page heap allocation; skips allocating `slot` completely when a fresh zero page /// is still all zeros). @@ -1131,37 +1155,6 @@ impl State { } } - /// Update `sent` hashes for all 64-byte chunks overlapping `[va, va + len)` so the CPU - /// copy-back we just wrote to `va` is not re-uploaded by the next `before_execute`. - unsafe fn sync_sent_range(&mut self, va: usize, len: usize) { - if len == 0 { - return; - } - let mut pg = va & !(PAGE - 1); - let end = va + len; - while pg < end { - let t = pg & !(TILE - 1); - let tile_end = (t + TILE).min(end); - if let Some(entry) = self.mapped.get_mut(&t) { - let mut p = pg; - while p < tile_end { - let idx = (p - t) / PAGE; - if entry.holes & (1u16 << idx) == 0 { - let bytes = std::slice::from_raw_parts(p as *const u8, PAGE); - let sent = entry.sent[idx].get_or_insert_with(|| Box::new(ZERO_HASHES)); - let lo = va.saturating_sub(p) / CHUNK; - let hi = (end.min(p + PAGE) - p).div_ceil(CHUNK).min(CHUNKS); - for k in lo..hi { - sent[k] = chunk_hash(&bytes[k * CHUNK..(k + 1) * CHUNK]); - } - } - p += PAGE; - } - } - pg = tile_end; - } - } - /// Copy `ranges` (address, bytes) from sparse VRAM back into the CPU view and refresh /// `sent` hashes. Caller has already ordered `self.queue` after any GPU writes if needed. unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)]) { @@ -1196,13 +1189,16 @@ impl State { let t = pg & !(TILE - 1); let idx = (pg - t) / PAGE; let step = (pg + PAGE).min(end) - at; - if s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { - std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); + if let Some(entry) = s.mapped.get_mut(&t) { + if entry.holes & (1u16 << idx) == 0 { + let page = std::slice::from_raw_parts_mut(pg as *mut u8, PAGE); + let source = std::slice::from_raw_parts(p.add(src_off), step); + land_page(&mut entry.sent[idx], page, at - pg, source); + } } at += step; src_off += step; } - s.sync_sent_range(dst, len); } pending.clear(); *used = 0; @@ -2671,6 +2667,39 @@ mod tests { assert_eq!(changed_chunks(&page, &mut sent), vec![(192, 128)]); } + #[test] + fn clean_chunks_take_gpu_copy_back_bytes() { + let mut page = vec![0x11u8; PAGE]; + let mut sent = Box::new(ZERO_HASHES); + changed_chunks(&page, &mut sent); + let mut slot = Some(sent); + let gpu = vec![0x22u8; 2 * CHUNK]; + + land_page(&mut slot, &mut page, CHUNK, &gpu); + + assert!(page[..CHUNK].iter().all(|&byte| byte == 0x11)); + assert!(page[CHUNK..3 * CHUNK].iter().all(|&byte| byte == 0x22)); + assert!(changed_chunks(&page, slot.as_deref_mut().unwrap()).is_empty(), "landed bytes were left dirty"); + } + + #[test] + fn dirty_chunks_survive_gpu_copy_back_and_upload_next() { + let mut page = vec![0x11u8; PAGE]; + let mut sent = Box::new(ZERO_HASHES); + changed_chunks(&page, &mut sent); + let old_dirty_hash = sent[1]; + let mut slot = Some(sent); + page[CHUNK..2 * CHUNK].fill(0x33); + let gpu = vec![0x22u8; 2 * CHUNK]; + + land_page(&mut slot, &mut page, CHUNK, &gpu); + + assert!(page[CHUNK..2 * CHUNK].iter().all(|&byte| byte == 0x33), "copy-back overwrote newer CPU bytes"); + assert_eq!(slot.as_ref().unwrap()[1], old_dirty_hash, "dirty chunk lost its last-sent hash"); + assert!(page[2 * CHUNK..3 * CHUNK].iter().all(|&byte| byte == 0x22), "clean neighbour did not land"); + assert_eq!(changed_chunks(&page, slot.as_deref_mut().unwrap()), vec![(CHUNK, CHUNK)]); + } + /// `scan_page` skips allocating a hash box on all-zero pages, allocates on the first write, /// and coalesces adjacent dirty chunks across consecutive pages. #[test] @@ -2758,7 +2787,7 @@ mod tests { } /// Mapping tiles for a placed buffer over partially-committed/reserved memory must preserve - /// uncommitted hole bits so `readback_ranges` / `sync_sent_range` do not access-violate, + /// uncommitted hole bits so `readback_ranges` does not access-violate, /// and later commits clear those hole bits so subsequent writes scan cleanly. #[test] fn ensure_mapped_with_query_holes_skips_uncommitted_pages_on_readback() { @@ -3078,7 +3107,10 @@ mod tests { std::ptr::write_bytes(base as *mut u8, 0x5a, PAGE); s.commit_range(base, TILE); s.wait_for(s.value); - s.sync_sent_range(base, PAGE); + let page = std::slice::from_raw_parts(base as *const u8, PAGE); + let mut sent = Box::new(ZERO_HASHES); + changed_chunks(page, &mut sent); + s.mapped.get_mut(&base).unwrap().sent[0] = Some(sent); let before = *s.mapped[&base].sent[0].as_ref().unwrap().clone(); s.ring_write = STAGING as u64; From cf1d7f8632764d098e5228c6587d0f25c512a51a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 11:51:15 +0100 Subject: [PATCH 191/265] xcl run: XCL_THREAD_DUMP_AT also logs the fences and queue waits behind A retail title's world load can stop with no GPU-wait time-out: presents, submits and DirectStorage requests go to 0 and every thread waits. The watchdog's summaries of pending title fences and of XCL's own unmet queue waits are only logged at a time-out, so such a stop did not say whether a fence or a queue was behind. At each XCL_THREAD_DUMP_AT dump XCL now logs the two summaries and the number of armed GPU waits, on a thread of its own so that a lock the stall holds cannot hold up the next dump. On #2057's tree this showed every fence and queue caught up at 135, 200 and 300 s after a stop at 110 s (https://github.com/xcl-dev/xcl/pull/2057#issuecomment-7160090884). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XZrhsCAiLU1tTuEBwPLaRW --- crates/xcl/src/hle/d3d12x/list_x.rs | 12 ++++++++++++ crates/xcl/src/host.rs | 4 +++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 08eb066478..7e4ac008aa 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1676,6 +1676,18 @@ fn internal_waits_summary() -> String { unmet.into_iter().map(|(q, s)| format!("q{}: {s}", queue_id(q))).collect::<Vec<_>>().join(", ") } +/// What the GPU wait watchdog logs at a time-out, logged on request (`XCL_THREAD_DUMP_AT`), so a +/// title that stops with no time-out shows whether a fence or a queue is behind. On a thread of +/// its own: a lock the stall holds does not hold up the next thread dump. +pub fn log_sync_state(at: &str) { + let at = at.to_string(); + let _ = std::thread::Builder::new().name("xcl-sync-state".into()).spawn(move || { + crate::xlog_info!("D3D12.X: sync state at {at}: pending title ID3D12Fences: {}", super::fence_x::pending_summary()); + crate::xlog_info!("D3D12.X: sync state at {at}: XCL's own queue waits unmet: {}", internal_waits_summary()); + crate::xlog_info!("D3D12.X: sync state at {at}: {} GPU waits armed", ARMED_GPU_WAITS.load(Ordering::Acquire)); + }); +} + fn queue_id(q: usize) -> usize { let mut g = QUEUE_IDS.lock().unwrap(); if let Some(pos) = g.iter().position(|&x| x == q) { diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 5cb34eb168..c5251ca16d 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -120,7 +120,8 @@ pub fn host_main(boot_path: &Path) -> i32 { } }); } - // `XCL_THREAD_DUMP_AT=s1,s2…`: where every thread is at those seconds (a stalled title) + // `XCL_THREAD_DUMP_AT=s1,s2…`: where every thread is at those seconds (a stalled title), and + // which title fences and XCL queue waits are behind then if let Ok(v) = std::env::var("XCL_THREAD_DUMP_AT") { let at: Vec<f64> = v.split(',').filter_map(|s| s.trim().parse().ok()).collect(); let _ = std::thread::Builder::new().name("xcl-thread-dump".into()).spawn(move || { @@ -131,6 +132,7 @@ pub fn host_main(boot_path: &Path) -> i32 { std::thread::sleep(std::time::Duration::from_secs_f64(left)); } crate::eh::dump_threads(); + crate::hle::d3d12x::list_x::log_sync_state(&format!("{s} s")); } }); } From db2dee03b1b12ec9a0cccae26bd18f4bdf684f63 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 20:32:56 +0100 Subject: [PATCH 192/265] xcl run: XCL_THREAD_DUMP_AT also logs the Wait64 cells behind The three lines of the first commit read "none / none / 0" in runs where the title had stopped after its first #101: no fence and no queue was behind, yet nothing was presented. What showed the stop was a SYNC_GRAPH cell whose recorded value is above what was submitted and completed, with no GPU wait armed: a list that writes the value was recorded and never submitted, so the submitting thread is held (GreemSC's runs, RX 7900 XT; the thread dump then named that thread). cells_behind_summary lists such cells, and those with armed waits: memory, completed, submitted (and on which queue), recorded and CPU values, and the armed waits with their age. It takes the graph with try_lock, since a dump can come while a submitting thread holds it. The cell is read with ReadProcessMemory (dstorage::read_own), since the title can decommit its page at any time; an unreadable cell shows "mem unreadable" (bmjask's review). The function is GreemSC's, from the review of this PR. Co-authored-by: GreemSC <57862153+GreemSC@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XZrhsCAiLU1tTuEBwPLaRW --- crates/xcl/src/hle/d3d12x/list_x.rs | 82 ++++++++++++++++++++++++++++- crates/xcl/src/hle/dstorage.rs | 2 +- 2 files changed, 81 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 7e4ac008aa..659546ed11 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1676,15 +1676,53 @@ fn internal_waits_summary() -> String { unmet.into_iter().map(|(q, s)| format!("q{}: {s}", queue_id(q))).collect::<Vec<_>>().join(", ") } +/// The `Wait64BitValueX` cells not yet at their highest recorded value, or with armed GPU waits: +/// `rec` above `sub` with nothing armed is a list that writes the value, recorded and never +/// submitted (its submitting thread is held). `try_lock`: a dump can come while a submitting +/// thread holds the graph. (@GreemSC's diagnostic, from #2244's review.) +fn cells_behind_summary() -> String { + let mut parts = Vec::new(); + if let Ok(g) = SYNC_GRAPH.try_lock() { + for (&va, c) in g.iter().flat_map(|gr| gr.cells.iter()) { + let done = c.fence.as_ref().map_or(0, |f| unsafe { f.GetCompletedValue() }); + if c.armed_waits.is_empty() && done >= c.recorded_max { + continue; + } + // (the title can decommit the cell's page at any moment: a read that cannot fault) + let mut v = 0u64; + let mem = if unsafe { crate::hle::dstorage::read_own(va as usize, &mut v as *mut u64 as *mut u8, 8) } { format!("{v:#x}") } else { "unreadable".into() }; + let armed: Vec<String> = c.armed_waits.iter().map(|a| format!("{:#x}@q{} {} ms", a.val, queue_id(a.waiting_queue), a.armed_at.elapsed().as_millis())).collect(); + parts.push(format!( + "{va:#x}: mem {mem} done {done:#x} sub {:#x}@q{:?} rec {:#x} cpu {:#x}{} armed [{}]", + c.submitted_max, + c.submitted_queue.map(queue_id), + c.recorded_max, + c.cpu_signaled_max, + if c.non_monotonic { " non-monotonic" } else { "" }, + armed.join(", ") + )); + } + } else { + parts.push("(sync graph locked)".into()); + } + if parts.is_empty() { + "none".into() + } else { + parts.join("; ") + } +} + /// What the GPU wait watchdog logs at a time-out, logged on request (`XCL_THREAD_DUMP_AT`), so a -/// title that stops with no time-out shows whether a fence or a queue is behind. On a thread of -/// its own: a lock the stall holds does not hold up the next thread dump. +/// title that stops with no time-out shows whether a fence or a queue is behind, and which +/// `Wait64BitValueX` cells are behind what was recorded for them. On a thread of its own: a lock +/// the stall holds does not hold up the next thread dump. pub fn log_sync_state(at: &str) { let at = at.to_string(); let _ = std::thread::Builder::new().name("xcl-sync-state".into()).spawn(move || { crate::xlog_info!("D3D12.X: sync state at {at}: pending title ID3D12Fences: {}", super::fence_x::pending_summary()); crate::xlog_info!("D3D12.X: sync state at {at}: XCL's own queue waits unmet: {}", internal_waits_summary()); crate::xlog_info!("D3D12.X: sync state at {at}: {} GPU waits armed", ARMED_GPU_WAITS.load(Ordering::Acquire)); + crate::xlog_info!("D3D12.X: sync state at {at}: Wait64 cells behind: {}", cells_behind_summary()); }); } @@ -5409,6 +5447,46 @@ mod tests { assert_eq!(mirror_in(&cache.1, 550, 1), None, "ranges are half-open"); } + /// A recorded `Wait64` cell whose page the title decommitted, or made inaccessible, is listed + /// as unreadable by the sync-state dump, which does not fault on it. + #[test] + fn the_cells_behind_summary_reads_a_decommitted_or_protected_cell_without_faulting() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, VirtualProtect, MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + unsafe { + let mem = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(mem, 0); + let (decommitted, protected) = (mem as u64, (mem + 0x1000) as u64); + *(decommitted as *mut u64) = 7; + *(protected as *mut u64) = 7; + { + let mut g = SYNC_GRAPH.lock().unwrap(); + let gr = g.get_or_insert_with(Default::default); + for va in [decommitted, protected] { + gr.cells.insert(va, SyncCell { recorded_max: 9, ..Default::default() }); + } + } + assert_ne!(VirtualFree(mem as *mut c_void, 0x1000, MEM_DECOMMIT), 0); + let mut old = 0; + assert_ne!(VirtualProtect((mem + 0x1000) as *const c_void, 0x1000, PAGE_NOACCESS, &mut old), 0); + // (other tests take the graph too: the summary only tries the lock) + let mut s = cells_behind_summary(); + for _ in 0..200 { + if !s.contains("(sync graph locked)") { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + s = cells_behind_summary(); + } + if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { + gr.cells.remove(&decommitted); + gr.cells.remove(&protected); + } + VirtualFree(mem as *mut c_void, 0, MEM_RELEASE); + assert!(s.contains(&format!("{decommitted:#x}: mem unreadable done 0x0")), "{s}"); + assert!(s.contains(&format!("{protected:#x}: mem unreadable done 0x0")), "{s}"); + } + } + /// An internal wait shows in the watchdog's summary while its fence is short of the value, /// and is gone from it once the fence gets there. #[test] diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 3c48e6fedf..2a9d878708 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -805,7 +805,7 @@ unsafe fn snapshot_page_array(ptr: u64, offset: u16, byte_len: u32) -> Result<Ve Ok(pages) } -unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { +pub(crate) unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut done = 0usize; From 862cf611355f4c0abaece3126b4b7b31224bc95b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:43:28 -0500 Subject: [PATCH 193/265] xcl run: the sync-state dump names the list behind a Wait64 cell A cell recorded and never submitted (#1452: rec 0x619, sub 0x0@qNone) did not say which list recorded the value or what became of that list. Each cell now keeps the PC list and time of the recording that set its recorded_max, and each list that recorded a Write64 keeps its last execute, Reset and Release (signal_write64_fences, the KickoffX submit, reset_pc, clear_segment_state, on_release). The cell entry in cells_behind_summary prints them as their time after the recording, or "no": reset or released with no execute is a recording thrown away (#2691's address reuse shows as a release), executed is a miss on the submit side, and none of the three a list the title still holds. Part of #1452. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/xcl/src/hle/d3d12x/list_x.rs | 92 ++++++++++++++++++++++++++++- 1 file changed, 91 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 659546ed11..cb8444c9fc 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1286,6 +1286,7 @@ pub(super) unsafe fn on_create_with_backing(list: *mut c_void, alloc: usize, bac /// Clean up all tracked state when a command list is released for good. pub(super) fn on_release(list: usize) { + trace_list(list, ListEvent::Released); super::alloc_pool::forget_list(list); release_copy_scratch(list); super::real::dispatch_chain::list_reset(list); @@ -1308,6 +1309,7 @@ pub(super) fn on_release(list: usize) { /// Clear per-recording sync/write tracking on a split segment moved into `title_list`'s spare pool. pub(super) fn clear_segment_state(list: usize) { + trace_list(list, ListEvent::Reset); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { s.occlusion = Occlusion::default(); s.written_ranges.clear(); @@ -1568,6 +1570,8 @@ struct SyncCell { recorded_list_type: Option<D3D12_COMMAND_LIST_TYPE>, /// Last queue the recording list was executed on (if known). recorded_last_queue: Option<usize>, + /// The PC list of the recording that set `recorded_max`, and when (the sync-state dump). + recorded_by: Option<(usize, Instant)>, /// Highest value submitted via `queue.Signal(&fence, v)` or released on CPU. submitted_max: u64, /// Queue that issued the latest GPU `Signal` (`None` if released on CPU). @@ -1634,6 +1638,46 @@ impl SyncGraph { static SYNC_GRAPH: Mutex<Option<SyncGraph>> = Mutex::new(None); static ARMED_GPU_WAITS: AtomicUsize = AtomicUsize::new(0); + +/// What became of a PC list that recorded a `Write64BitValue*`: when it was last executed, reset +/// and released (the sync-state dump; a cell recorded and never submitted names its list). +#[derive(Default, Clone, Copy)] +struct ListTrace { + executed: Option<Instant>, + reset: Option<Instant>, + released: Option<Instant>, +} + +#[derive(Clone, Copy)] +enum ListEvent { + Executed, + Reset, + Released, +} + +static WRITE64_LISTS: Mutex<Option<HashMap<usize, ListTrace>>> = Mutex::new(None); + +/// Notes `event` on `list` when it ever recorded a `Write64BitValue*`. +fn trace_list(list: usize, event: ListEvent) { + let mut g = WRITE64_LISTS.lock().unwrap(); + if let Some(t) = g.as_mut().and_then(|m| m.get_mut(&list)) { + let at = Some(Instant::now()); + match event { + ListEvent::Executed => t.executed = at, + ListEvent::Reset => t.reset = at, + ListEvent::Released => t.released = at, + } + } +} + +/// `by <list> <age> ms ago (executed …, reset …, released …)`: each as its time after the +/// recording, or `no` when it has not come since. +fn recording_trace(list: usize, at: Instant) -> String { + let t = WRITE64_LISTS.try_lock().ok().and_then(|g| g.as_ref().and_then(|m| m.get(&list).copied())); + let Some(t) = t else { return format!("by {list:#x} {} ms ago", at.elapsed().as_millis()) }; + let after = |e: Option<Instant>| e.filter(|&e| e >= at).map_or("no".to_string(), |e| format!("+{} ms", (e - at).as_millis())); + format!("by {list:#x} {} ms ago (executed {}, reset {}, released {})", at.elapsed().as_millis(), after(t.executed), after(t.reset), after(t.released)) +} static SYNC_WATCHDOG_WAKE: OnceLock<(Mutex<()>, Condvar)> = OnceLock::new(); static QUEUE_IDS: Mutex<Vec<usize>> = Mutex::new(Vec::new()); @@ -1693,10 +1737,11 @@ fn cells_behind_summary() -> String { let mem = if unsafe { crate::hle::dstorage::read_own(va as usize, &mut v as *mut u64 as *mut u8, 8) } { format!("{v:#x}") } else { "unreadable".into() }; let armed: Vec<String> = c.armed_waits.iter().map(|a| format!("{:#x}@q{} {} ms", a.val, queue_id(a.waiting_queue), a.armed_at.elapsed().as_millis())).collect(); parts.push(format!( - "{va:#x}: mem {mem} done {done:#x} sub {:#x}@q{:?} rec {:#x} cpu {:#x}{} armed [{}]", + "{va:#x}: mem {mem} done {done:#x} sub {:#x}@q{:?} rec {:#x}{} cpu {:#x}{} armed [{}]", c.submitted_max, c.submitted_queue.map(queue_id), c.recorded_max, + c.recorded_by.map_or(String::new(), |(l, at)| format!(" {}", recording_trace(l, at))), c.cpu_signaled_max, if c.non_monotonic { " non-monotonic" } else { "" }, armed.join(", ") @@ -2202,6 +2247,7 @@ fn note_write64_recorded(list: *mut c_void, va: u64, value: u64) { s.push_write64_signal(va, value); (s.list_type, s.last_queue) }; + WRITE64_LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default(); let rescue: Option<(ID3D12Fence, u64, u64)> = { let mut g = SYNC_GRAPH.lock().unwrap(); let cell = g.get_or_insert_with(SyncGraph::default).cells.entry(va).or_default(); @@ -2225,6 +2271,7 @@ fn note_write64_recorded(list: *mut c_void, va: u64, value: u64) { } else { if value > cell.recorded_max { cell.recorded_max = value; + cell.recorded_by = Some((list as usize, Instant::now())); if lty.is_some() { cell.recorded_list_type = lty; } @@ -2374,6 +2421,9 @@ pub(super) unsafe fn signal_write64_fences(queue: *mut c_void, lists: &[*mut c_v if WRITE64_SIGNAL_LISTS.load(Ordering::Acquire) == 0 || queue.is_null() || lists.is_empty() { return; } + for &l in lists { + trace_list(l as usize, ListEvent::Executed); + } let pairs: Vec<(u64, u64)> = { let g = LISTS.lock().unwrap(); let Some(m) = g.as_ref() else { return }; @@ -4101,6 +4151,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let current_submitted = super::queue_submit::with(q_raw as usize, || { let submitted = gate.submit(q_raw, &one, || {}, || exec(q_raw, 1, one.as_ptr())); if submitted { + trace_list(this as usize, ListEvent::Executed); copy_scratch_submitted(q_raw, &one); super::title_textures::publish_submission_effects(queue_identity(q_raw as usize), &texture_writes, &texture_transitions); signal_write64_pairs(q_raw, &write64_signals); @@ -4869,6 +4920,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 if hr < 0 { return hr; } + trace_list(this as usize, ListEvent::Reset); reset_copy_scratch(this); reset_own_alloc(this); @@ -5487,6 +5539,44 @@ mod tests { } } + /// A cell recorded and never submitted names the list that recorded it, and what came to that + /// list after the recording: here a Reset and then a Release, and no execute. + #[test] + fn the_cells_behind_summary_names_the_recording_list_and_what_came_to_it() { + let cell = Box::new(AtomicU64::new(0)); + let va = &*cell as *const AtomicU64 as u64; + // (an address no real list has: the box's own) + let token = Box::new(0u64); + let list = &*token as *const u64 as usize; + let summary = || { + // (other tests take the graph too: the summary only tries the lock) + for _ in 0..200 { + let s = cells_behind_summary(); + if !s.contains("(sync graph locked)") { + return s; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the sync graph stayed locked"); + }; + let entry = |s: &str| s.split("; ").find(|p| p.starts_with(&format!("{va:#x}:"))).map(str::to_string).unwrap_or_else(|| panic!("{s}")); + + note_write64_recorded(list as *mut c_void, va, 0x619); + let s = entry(&summary()); + assert!(s.contains(&format!("rec 0x619 by {list:#x} ")), "{s}"); + assert!(s.contains("(executed no, reset no, released no)"), "{s}"); + trace_list(list, ListEvent::Reset); + on_release(list); + let s = entry(&summary()); + assert!(s.contains("(executed no, reset +"), "{s}"); + assert!(s.contains(", released +"), "{s}"); + + if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { + gr.cells.remove(&va); + } + WRITE64_LISTS.lock().unwrap().as_mut().map(|m| m.remove(&list)); + } + /// An internal wait shows in the watchdog's summary while its fence is short of the value, /// and is gone from it once the fence gets there. #[test] From 4f55fd85ba59aa1634ffb905463a466a25c8b51b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:49:06 -0500 Subject: [PATCH 194/265] xcl run: a Reset or Release ends the recording the Write64 trace follows The trace was kept per list address: after a Reset, or a Release and a new list at the same address, a later execute of another recording showed on the old cell as "executed", though its write was thrown away. Each recording that records a Write64 now has a trace of its own, which the cells it recorded hold; a Reset or Release ends it, and what comes to the list after belongs to the next one. The test adds both cases: Reset, an unrelated recording and its execute leave the old cell at "executed no", and so do a Release and a list at the same address that records and is executed. Part of #1452. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/xcl/src/hle/d3d12x/list_x.rs | 82 +++++++++++++++++++++-------- 1 file changed, 60 insertions(+), 22 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index cb8444c9fc..1526a8488f 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -21,7 +21,7 @@ use std::collections::{BTreeMap, HashMap}; use std::ffi::c_void; use std::mem::{transmute_copy, ManuallyDrop}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Condvar, LazyLock, Mutex, OnceLock}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, OnceLock}; use std::time::{Duration, Instant}; use windows::core::Interface; @@ -1570,8 +1570,9 @@ struct SyncCell { recorded_list_type: Option<D3D12_COMMAND_LIST_TYPE>, /// Last queue the recording list was executed on (if known). recorded_last_queue: Option<usize>, - /// The PC list of the recording that set `recorded_max`, and when (the sync-state dump). - recorded_by: Option<(usize, Instant)>, + /// The PC list of the recording that set `recorded_max`, when, and what came to that + /// recording (the sync-state dump). + recorded_by: Option<(usize, Instant, Arc<Mutex<ListTrace>>)>, /// Highest value submitted via `queue.Signal(&fence, v)` or released on CPU. submitted_max: u64, /// Queue that issued the latest GPU `Signal` (`None` if released on CPU). @@ -1639,8 +1640,9 @@ impl SyncGraph { static SYNC_GRAPH: Mutex<Option<SyncGraph>> = Mutex::new(None); static ARMED_GPU_WAITS: AtomicUsize = AtomicUsize::new(0); -/// What became of a PC list that recorded a `Write64BitValue*`: when it was last executed, reset -/// and released (the sync-state dump; a cell recorded and never submitted names its list). +/// What became of a recording of a PC list that recorded a `Write64BitValue*`: when it was last +/// executed, and the Reset or Release that ended it (the sync-state dump; a cell recorded and +/// never submitted names its list). #[derive(Default, Clone, Copy)] struct ListTrace { executed: Option<Instant>, @@ -1655,12 +1657,22 @@ enum ListEvent { Released, } -static WRITE64_LISTS: Mutex<Option<HashMap<usize, ListTrace>>> = Mutex::new(None); +/// the recording each PC list has open, when it recorded a `Write64BitValue*` +static WRITE64_LISTS: Mutex<Option<HashMap<usize, Arc<Mutex<ListTrace>>>>> = Mutex::new(None); -/// Notes `event` on `list` when it ever recorded a `Write64BitValue*`. +/// Notes `event` on the recording `list` has open, when it recorded a `Write64BitValue*`. A Reset +/// or a Release ends the recording: what comes to the list (or its address) after is another's. fn trace_list(list: usize, event: ListEvent) { - let mut g = WRITE64_LISTS.lock().unwrap(); - if let Some(t) = g.as_mut().and_then(|m| m.get_mut(&list)) { + let t = { + let mut g = WRITE64_LISTS.lock().unwrap(); + let Some(m) = g.as_mut() else { return }; + match event { + ListEvent::Executed => m.get(&list).cloned(), + ListEvent::Reset | ListEvent::Released => m.remove(&list), + } + }; + if let Some(t) = t { + let mut t = t.lock().unwrap(); let at = Some(Instant::now()); match event { ListEvent::Executed => t.executed = at, @@ -1671,11 +1683,10 @@ fn trace_list(list: usize, event: ListEvent) { } /// `by <list> <age> ms ago (executed …, reset …, released …)`: each as its time after the -/// recording, or `no` when it has not come since. -fn recording_trace(list: usize, at: Instant) -> String { - let t = WRITE64_LISTS.try_lock().ok().and_then(|g| g.as_ref().and_then(|m| m.get(&list).copied())); - let Some(t) = t else { return format!("by {list:#x} {} ms ago", at.elapsed().as_millis()) }; - let after = |e: Option<Instant>| e.filter(|&e| e >= at).map_or("no".to_string(), |e| format!("+{} ms", (e - at).as_millis())); +/// recording `t`, or `no` when it has not come to it. +fn recording_trace(list: usize, at: Instant, t: &Mutex<ListTrace>) -> String { + let Ok(t) = t.try_lock().map(|t| *t) else { return format!("by {list:#x} {} ms ago", at.elapsed().as_millis()) }; + let after = |e: Option<Instant>| e.map_or("no".to_string(), |e| format!("+{} ms", e.saturating_duration_since(at).as_millis())); format!("by {list:#x} {} ms ago (executed {}, reset {}, released {})", at.elapsed().as_millis(), after(t.executed), after(t.reset), after(t.released)) } static SYNC_WATCHDOG_WAKE: OnceLock<(Mutex<()>, Condvar)> = OnceLock::new(); @@ -1741,7 +1752,7 @@ fn cells_behind_summary() -> String { c.submitted_max, c.submitted_queue.map(queue_id), c.recorded_max, - c.recorded_by.map_or(String::new(), |(l, at)| format!(" {}", recording_trace(l, at))), + c.recorded_by.as_ref().map_or(String::new(), |(l, at, t)| format!(" {}", recording_trace(*l, *at, t))), c.cpu_signaled_max, if c.non_monotonic { " non-monotonic" } else { "" }, armed.join(", ") @@ -2247,7 +2258,7 @@ fn note_write64_recorded(list: *mut c_void, va: u64, value: u64) { s.push_write64_signal(va, value); (s.list_type, s.last_queue) }; - WRITE64_LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + let recording = WRITE64_LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default().clone(); let rescue: Option<(ID3D12Fence, u64, u64)> = { let mut g = SYNC_GRAPH.lock().unwrap(); let cell = g.get_or_insert_with(SyncGraph::default).cells.entry(va).or_default(); @@ -2271,7 +2282,7 @@ fn note_write64_recorded(list: *mut c_void, va: u64, value: u64) { } else { if value > cell.recorded_max { cell.recorded_max = value; - cell.recorded_by = Some((list as usize, Instant::now())); + cell.recorded_by = Some((list as usize, Instant::now(), recording)); if lty.is_some() { cell.recorded_list_type = lty; } @@ -5540,11 +5551,14 @@ mod tests { } /// A cell recorded and never submitted names the list that recorded it, and what came to that - /// list after the recording: here a Reset and then a Release, and no execute. + /// recording: here a Reset (which ends it: the Release after comes to none), and no execute. + /// A recording on the list after a Reset, or on a list made at its address after a Release, + /// is another one: its execute does not come to the cell. #[test] fn the_cells_behind_summary_names_the_recording_list_and_what_came_to_it() { - let cell = Box::new(AtomicU64::new(0)); - let va = &*cell as *const AtomicU64 as u64; + let cell = Box::new([AtomicU64::new(0), AtomicU64::new(0)]); + let va = &cell[0] as *const AtomicU64 as u64; + let other = &cell[1] as *const AtomicU64 as u64; // (an address no real list has: the box's own) let token = Box::new(0u64); let list = &*token as *const u64 as usize; @@ -5559,7 +5573,8 @@ mod tests { } panic!("the sync graph stayed locked"); }; - let entry = |s: &str| s.split("; ").find(|p| p.starts_with(&format!("{va:#x}:"))).map(str::to_string).unwrap_or_else(|| panic!("{s}")); + let entry_of = |va: u64, s: &str| s.split("; ").find(|p| p.starts_with(&format!("{va:#x}:"))).map(str::to_string).unwrap_or_else(|| panic!("{s}")); + let entry = |s: &str| entry_of(va, s); note_write64_recorded(list as *mut c_void, va, 0x619); let s = entry(&summary()); @@ -5569,10 +5584,33 @@ mod tests { on_release(list); let s = entry(&summary()); assert!(s.contains("(executed no, reset +"), "{s}"); - assert!(s.contains(", released +"), "{s}"); + assert!(s.contains(", released no)"), "{s}"); + + // a Reset, an unrelated recording on the list, and its execute + note_write64_recorded(list as *mut c_void, va, 0x61a); + trace_list(list, ListEvent::Reset); + note_write64_recorded(list as *mut c_void, other, 1); + trace_list(list, ListEvent::Executed); + let s = summary(); + assert!(entry(&s).contains("rec 0x61a by "), "{s}"); + assert!(entry(&s).contains("(executed no, reset +"), "{s}"); + assert!(entry_of(other, &s).contains("(executed +"), "{s}"); + + // a new recording (after the Reset that ends the executed one), a Release, and a list at + // the same address that records and is executed + trace_list(list, ListEvent::Reset); + note_write64_recorded(list as *mut c_void, va, 0x61b); + on_release(list); + note_write64_recorded(list as *mut c_void, other, 2); + trace_list(list, ListEvent::Executed); + let s = summary(); + assert!(entry(&s).contains("rec 0x61b by "), "{s}"); + assert!(entry(&s).contains("(executed no, reset no, released +"), "{s}"); + assert!(entry_of(other, &s).contains("(executed +"), "{s}"); if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { gr.cells.remove(&va); + gr.cells.remove(&other); } WRITE64_LISTS.lock().unwrap().as_mut().map(|m| m.remove(&list)); } From 05d0747fd4397dc38e57a7f3f818e2d384575006 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:05:03 -0800 Subject: [PATCH 195/265] xcl run: trace immutable submission generations The integrated execution path publishes captured SubmissionChunk effects instead of calling the legacy post-submit helpers. Capture each recording token with that immutable plan and mark it only after the exact chunk reaches the driver, so Reset, Release, address reuse, and split waits cannot redirect execution to another generation. Kickoff ends the actual reset target only after Reset succeeds. Recording-level tracing remains disabled unless XCL_THREAD_DUMP_AT schedules a dump. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 115 +++++++++++++++++++++------- crates/xcl/src/host.rs | 3 + 2 files changed, 92 insertions(+), 26 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 1526a8488f..8d3ce69137 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -756,6 +756,8 @@ struct ListState { /// so `ExecuteCommandLists` / `KickoffX` can signal per-address GPU fences for cross-queue /// `Wait64BitValueX` without blocking the submitter thread on the CPU. write64_signals: Vec<(u64, u64)>, + /// Causal dump token for this exact recording; absent unless scheduled dumps enabled tracing. + write64_trace: Option<Arc<Mutex<ListTrace>>>, /// External memory waits recorded on this list pending_waits: Vec<PendingWait>, /// bottom-of-pipe writes into memory the GPU does not see (`cpu_writes`) @@ -1042,6 +1044,8 @@ impl SegmentEffects { pub(super) struct SubmissionPlan { lists: Vec<*mut c_void>, effects: Vec<SegmentEffects>, + /// Exact recording tokens captured with `effects`; empty when causal dumps are disabled. + traces: Vec<Option<Arc<Mutex<ListTrace>>>>, /// Per-segment dependency on an earlier CPU-after-segment producer; empty on the no-wait fast path. waits_after_cpu_write: Vec<bool>, has_waits: bool, @@ -1050,7 +1054,7 @@ pub(super) struct SubmissionPlan { impl SubmissionPlan { fn capture(lists: &[*mut c_void]) -> Self { if lists.is_empty() { - return Self { lists: Vec::new(), effects: Vec::new(), waits_after_cpu_write: Vec::new(), has_waits: false }; + return Self { lists: Vec::new(), effects: Vec::new(), traces: Vec::new(), waits_after_cpu_write: Vec::new(), has_waits: false }; } let g = LISTS.lock().unwrap(); let effects: Vec<SegmentEffects> = lists @@ -1070,6 +1074,14 @@ impl SubmissionPlan { .unwrap_or_default() }) .collect(); + let traces = if sync_state_tracing() { + lists + .iter() + .map(|&list| g.as_ref().and_then(|m| m.get(&(list as usize))).and_then(|s| s.write64_trace.clone())) + .collect() + } else { + Vec::new() + }; drop(g); let has_waits = effects.iter().any(|e| !e.waits.is_empty()); let waits_after_cpu_write = if has_waits { @@ -1085,7 +1097,7 @@ impl SubmissionPlan { } else { Vec::new() }; - Self { lists: lists.to_vec(), effects, waits_after_cpu_write, has_waits } + Self { lists: lists.to_vec(), effects, traces, waits_after_cpu_write, has_waits } } fn cpu_producer_overlaps(&self, waits: &[PendingWait], before: usize) -> bool { @@ -1109,6 +1121,7 @@ impl SubmissionPlan { pub(super) struct SubmissionChunk<'a> { lists: &'a [*mut c_void], effects: &'a [SegmentEffects], + traces: &'a [Option<Arc<Mutex<ListTrace>>>], needs_cpu_completion: bool, } @@ -1122,6 +1135,13 @@ impl<'a> SubmissionChunk<'a> { } pub(super) unsafe fn submit_effects(self, queue: *mut c_void) -> Option<super::cpu_writes::Completion> { + // The immutable submission plan is now the production path, so record execution here + // after its caller has successfully submitted this exact chunk. The legacy + // `signal_write64_fences` path below remains useful to tests but is not reached by the + // title-facing submit path. + for trace in self.traces.iter().flatten() { + mark_trace(trace, ListEvent::Executed); + } submit_segment_effects(queue, self.effects, self.needs_cpu_completion) } } @@ -1639,6 +1659,17 @@ impl SyncGraph { static SYNC_GRAPH: Mutex<Option<SyncGraph>> = Mutex::new(None); static ARMED_GPU_WAITS: AtomicUsize = AtomicUsize::new(0); +static SYNC_STATE_TRACING: AtomicBool = AtomicBool::new(false); + +/// Enable recording-level causal detail only when at least one scheduled sync dump will use it. +pub fn enable_sync_state_tracing() { + SYNC_STATE_TRACING.store(true, Ordering::Release); +} + +#[inline] +fn sync_state_tracing() -> bool { + SYNC_STATE_TRACING.load(Ordering::Acquire) +} /// What became of a recording of a PC list that recorded a `Write64BitValue*`: when it was last /// executed, and the Reset or Release that ended it (the sync-state dump; a cell recorded and @@ -1657,28 +1688,32 @@ enum ListEvent { Released, } -/// the recording each PC list has open, when it recorded a `Write64BitValue*` -static WRITE64_LISTS: Mutex<Option<HashMap<usize, Arc<Mutex<ListTrace>>>>> = Mutex::new(None); - /// Notes `event` on the recording `list` has open, when it recorded a `Write64BitValue*`. A Reset /// or a Release ends the recording: what comes to the list (or its address) after is another's. fn trace_list(list: usize, event: ListEvent) { + if !sync_state_tracing() { + return; + } let t = { - let mut g = WRITE64_LISTS.lock().unwrap(); - let Some(m) = g.as_mut() else { return }; + let mut g = LISTS.lock().unwrap(); + let Some(state) = g.as_mut().and_then(|m| m.get_mut(&list)) else { return }; match event { - ListEvent::Executed => m.get(&list).cloned(), - ListEvent::Reset | ListEvent::Released => m.remove(&list), + ListEvent::Executed => state.write64_trace.clone(), + ListEvent::Reset | ListEvent::Released => state.write64_trace.take(), } }; if let Some(t) = t { - let mut t = t.lock().unwrap(); - let at = Some(Instant::now()); - match event { - ListEvent::Executed => t.executed = at, - ListEvent::Reset => t.reset = at, - ListEvent::Released => t.released = at, - } + mark_trace(&t, event); + } +} + +fn mark_trace(trace: &Mutex<ListTrace>, event: ListEvent) { + let mut trace = trace.lock().unwrap(); + let at = Some(Instant::now()); + match event { + ListEvent::Executed => trace.executed = at, + ListEvent::Reset => trace.reset = at, + ListEvent::Released => trace.released = at, } } @@ -2252,13 +2287,17 @@ fn note_write64_recorded(list: *mut c_void, va: u64, value: u64) { if value == 0 || !va.is_multiple_of(8) { return; } - let (lty, last_q) = { + let (lty, last_q, recording) = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); s.push_write64_signal(va, value); - (s.list_type, s.last_queue) + let recording = if sync_state_tracing() { + Some(s.write64_trace.get_or_insert_with(Default::default).clone()) + } else { + None + }; + (s.list_type, s.last_queue, recording) }; - let recording = WRITE64_LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default().clone(); let rescue: Option<(ID3D12Fence, u64, u64)> = { let mut g = SYNC_GRAPH.lock().unwrap(); let cell = g.get_or_insert_with(SyncGraph::default).cells.entry(va).or_default(); @@ -2282,7 +2321,7 @@ fn note_write64_recorded(list: *mut c_void, va: u64, value: u64) { } else { if value > cell.recorded_max { cell.recorded_max = value; - cell.recorded_by = Some((list as usize, Instant::now(), recording)); + cell.recorded_by = recording.map(|recording| (list as usize, Instant::now(), recording)); if lty.is_some() { cell.recorded_list_type = lty; } @@ -2710,6 +2749,7 @@ unsafe fn execute_submission_plan_with_completions( let chunk = |start, end| SubmissionChunk { lists: &plan.lists[start..end], effects: &plan.effects[start..end], + traces: if plan.traces.is_empty() { &[] } else { &plan.traces[start..end] }, needs_cpu_completion: plan.chunk_needs_cpu_completion(start, end, external_waits), }; if !plan.has_waits { @@ -4069,7 +4109,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } else { None }; - let (bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, preclose_effects) = { + let (bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, preclose_effects, current_trace) = { let mut g = LISTS.lock().unwrap(); let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { if let Some((wrapper, standby)) = standby { @@ -4081,7 +4121,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let preclose_effects = take_kickoff_effects_before_close(s, standby.is_some()); 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.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, preclose_effects) + let current_trace = sync_state_tracing().then(|| s.write64_trace.clone()).flatten(); + (s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, preclose_effects, current_trace) }; // End any active occlusion query before Close (PC forbids closing with an open query). @@ -4162,7 +4203,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let current_submitted = super::queue_submit::with(q_raw as usize, || { let submitted = gate.submit(q_raw, &one, || {}, || exec(q_raw, 1, one.as_ptr())); if submitted { - trace_list(this as usize, ListEvent::Executed); + if let Some(trace) = ¤t_trace { + mark_trace(trace, ListEvent::Executed); + } copy_scratch_submitted(q_raw, &one); super::title_textures::publish_submission_effects(queue_identity(q_raw as usize), &texture_writes, &texture_transitions); signal_write64_pairs(q_raw, &write64_signals); @@ -4236,6 +4279,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if reset_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); } + trace_list(target as usize, ListEvent::Reset); reset_copy_scratch(target); let bindings = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(target as usize))).map(|s| s.bindings.clone()); if let Some(b) = bindings { @@ -5556,6 +5600,7 @@ mod tests { /// is another one: its execute does not come to the cell. #[test] fn the_cells_behind_summary_names_the_recording_list_and_what_came_to_it() { + enable_sync_state_tracing(); let cell = Box::new([AtomicU64::new(0), AtomicU64::new(0)]); let va = &cell[0] as *const AtomicU64 as u64; let other = &cell[1] as *const AtomicU64 as u64; @@ -5590,7 +5635,9 @@ mod tests { note_write64_recorded(list as *mut c_void, va, 0x61a); trace_list(list, ListEvent::Reset); note_write64_recorded(list as *mut c_void, other, 1); - trace_list(list, ListEvent::Executed); + let lists = [list as *mut c_void]; + let plan = submission_plan(&lists); + unsafe { execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| drop(chunk.submit_effects(std::ptr::null_mut()))) }; let s = summary(); assert!(entry(&s).contains("rec 0x61a by "), "{s}"); assert!(entry(&s).contains("(executed no, reset +"), "{s}"); @@ -5602,17 +5649,32 @@ mod tests { note_write64_recorded(list as *mut c_void, va, 0x61b); on_release(list); note_write64_recorded(list as *mut c_void, other, 2); - trace_list(list, ListEvent::Executed); + let plan = submission_plan(&lists); + unsafe { execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| drop(chunk.submit_effects(std::ptr::null_mut()))) }; let s = summary(); assert!(entry(&s).contains("rec 0x61b by "), "{s}"); assert!(entry(&s).contains("(executed no, reset no, released +"), "{s}"); assert!(entry_of(other, &s).contains("(executed +"), "{s}"); + // Planning snapshots the exact generation. A Reset and new recording before publication + // must not redirect the old submission's Executed event to the new recording. + trace_list(list, ListEvent::Reset); + note_write64_recorded(list as *mut c_void, va, 0x61c); + let captured = submission_plan(&lists); + trace_list(list, ListEvent::Reset); + note_write64_recorded(list as *mut c_void, other, 3); + unsafe { execute_submission_plan_on(std::ptr::null_mut(), &captured, |chunk| drop(chunk.submit_effects(std::ptr::null_mut()))) }; + let s = summary(); + assert!(entry(&s).contains("rec 0x61c by "), "{s}"); + assert!(entry(&s).contains("(executed +") && entry(&s).contains(", reset +"), "{s}"); + assert!(entry_of(other, &s).contains("rec 0x3 by "), "{s}"); + assert!(entry_of(other, &s).contains("(executed no, reset no, released no)"), "{s}"); + if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { gr.cells.remove(&va); gr.cells.remove(&other); } - WRITE64_LISTS.lock().unwrap().as_mut().map(|m| m.remove(&list)); + on_release(list); } /// An internal wait shows in the watchdog's summary while its fence is short of the value, @@ -6326,6 +6388,7 @@ mod tests { assert!(!SubmissionPlan { lists: vec![producer], effects: vec![plan.effects[0].clone()], + traces: Vec::new(), waits_after_cpu_write: Vec::new(), has_waits: false, } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index c5251ca16d..243873926d 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -124,6 +124,9 @@ pub fn host_main(boot_path: &Path) -> i32 { // which title fences and XCL queue waits are behind then if let Ok(v) = std::env::var("XCL_THREAD_DUMP_AT") { let at: Vec<f64> = v.split(',').filter_map(|s| s.trim().parse().ok()).collect(); + if !at.is_empty() { + crate::hle::d3d12x::list_x::enable_sync_state_tracing(); + } let _ = std::thread::Builder::new().name("xcl-thread-dump".into()).spawn(move || { let t0 = std::time::Instant::now(); for s in at { From 08662496e1af515969d39b2f1bd699ce3427a195 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:03:52 -0800 Subject: [PATCH 196/265] D3D12.X: retain opt-in pipeline rebuild recipes Pipeline jobs normally consume their owned descriptors on the first build. Preserve that one-shot path without an extra device reference or retained shader storage, while allowing XCL_PSO_REBUILD_RECIPES=1 to keep immutable, fully owned inputs for future residency work. Clear borrowed root signatures and unused pointer members, and reject stream-output arrays that are not owned. The opt-in recipe owns its device and can run repeatedly; no rebuild or eviction is activated yet. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 123 +++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 104 +++++++++++++++++---- 2 files changed, 201 insertions(+), 26 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 52bd3e4ec4..d4d5411157 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -44,6 +44,9 @@ struct Pending { /// A pipeline build independent of the title-visible stand-ins that requested it. struct Build { compute_key: Option<Arc<super::real::compute_build_key::ComputeBuildKey>>, + /// Immutable inputs for rebuilding this pipeline after its first job has been consumed. + #[allow(dead_code)] // retained for the later opt-in eviction/rebuild stage + recipe: Option<Recipe>, /// the build, until a worker takes it job: Mutex<Option<Job>>, /// the build went to the workers (a lazy one goes on its first `resolve`) @@ -178,12 +181,18 @@ fn run_build(build: &Arc<Build>, job: Job) { impl Build { fn new(job: Job, sent: bool) -> Self { - Self::new_keyed(job, sent, None) + Self::new_keyed(job, sent, None, None) } - fn new_keyed(job: Job, sent: bool, compute_key: Option<Arc<super::real::compute_build_key::ComputeBuildKey>>) -> Self { + fn new_keyed( + job: Job, + sent: bool, + compute_key: Option<Arc<super::real::compute_build_key::ComputeBuildKey>>, + recipe: Option<Recipe>, + ) -> Self { Self { compute_key, + recipe, job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(sent), tracked: AtomicBool::new(false), @@ -589,9 +598,47 @@ pub fn enabled() -> bool { std::env::var("XCL_ASYNC_PSO").map_or(true, |v| v != "0") } +fn recipe_gate_value(value: Option<&str>) -> bool { + value.is_some_and(|value| value.trim() == "1") +} + +/// Whether background builds retain their immutable inputs after the initial one-shot job. +/// This is preparation for a future eviction policy only; it does not rebuild or evict PSOs. +pub(super) fn rebuild_recipes_enabled() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + let value = std::env::var("XCL_PSO_REBUILD_RECIPES").ok(); + let on = recipe_gate_value(value.as_deref()); + if on { + crate::xlog_info!("D3D12.X: XCL_PSO_REBUILD_RECIPES=1 - retaining pipeline rebuild inputs only; pipelines are not evicted or rebuilt"); + } + on + }) +} + /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box<dyn FnOnce() -> usize + Send>; +/// Rebuildable immutable inputs for one pipeline. The first build and any later rebuild use the +/// same operation; retaining it does not by itself schedule or run more work. +#[derive(Clone)] +pub(super) struct Recipe(Arc<dyn Fn() -> usize + Send + Sync>); + +impl Recipe { + pub(super) fn new(build: impl Fn() -> usize + Send + Sync + 'static) -> Self { + Self(Arc::new(build)) + } + + fn run(&self) -> usize { + (self.0)() + } + + fn initial_job(&self) -> Job { + let recipe = self.clone(); + Box::new(move || recipe.run()) + } +} + /// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. fn drop_unstarted_job(build: &Arc<Build>) { let job = build.job.lock().unwrap().take(); @@ -875,7 +922,7 @@ pub(super) fn submit_keyed( job: Job, compute_key: Option<super::real::compute_build_key::ComputeBuildKey>, ) { - submit_as(standin, compute, job, true, 0, compute_key); + submit_as(standin, compute, job, None, true, 0, compute_key); } /// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get @@ -901,10 +948,30 @@ pub(super) fn submit_lazy_keyed( key: u64, compute_key: Option<super::real::compute_build_key::ComputeBuildKey>, ) { - submit_as(standin, compute, job, false, key, compute_key); + submit_as(standin, compute, job, None, false, key, compute_key); } -fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, compute_key: Option<super::real::compute_build_key::ComputeBuildKey>) { +pub(super) fn submit_recipe_keyed( + standin: usize, + compute: bool, + recipe: Recipe, + send: bool, + key: u64, + compute_key: Option<super::real::compute_build_key::ComputeBuildKey>, +) { + let job = recipe.initial_job(); + submit_as(standin, compute, job, Some(recipe), send, key, compute_key); +} + +fn submit_as( + standin: usize, + compute: bool, + job: Job, + recipe: Option<Recipe>, + send: bool, + key: u64, + compute_key: Option<super::real::compute_build_key::ComputeBuildKey>, +) { debug_assert!(compute || compute_key.is_none()); let build = if let Some(compute_key) = compute_key { let mut registry = IN_FLIGHT.lock().unwrap(); @@ -924,20 +991,20 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, comp COALESCING.finished(1); } let compute_key = Arc::new(compute_key); - let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()))); + let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()), recipe)); builds.insert(compute_key, Arc::downgrade(&build)); COALESCING.unique(); build } } else { let compute_key = Arc::new(compute_key); - let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()))); + let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()), recipe)); builds.insert(compute_key, Arc::downgrade(&build)); COALESCING.unique(); build } } else { - Arc::new(Build::new(job, false)) + Arc::new(Build::new_keyed(job, false, None, recipe)) }; let p = Arc::new(Pending { build: build.clone(), @@ -1075,6 +1142,31 @@ fn preload_enabled() -> bool { mod used_tests { use super::*; + #[test] + fn rebuild_recipe_gate_requires_exact_one() { + assert!(recipe_gate_value(Some("1"))); + assert!(recipe_gate_value(Some(" 1\t"))); + for value in [None, Some(""), Some("0"), Some("true"), Some("2")] { + assert!(!recipe_gate_value(value)); + } + } + + #[test] + fn build_retains_a_reusable_recipe_after_its_initial_job_is_consumed() { + let calls = Arc::new(AtomicUsize::new(0)); + let recipe_calls = calls.clone(); + let recipe = Recipe::new(move || { + recipe_calls.fetch_add(1, Ordering::Relaxed) + 0x5100 + }); + let build = Build::new_keyed(recipe.initial_job(), false, None, Some(recipe)); + + let initial = build.job.lock().unwrap().take().unwrap(); + assert_eq!(initial(), 0x5100); + assert!(build.job.lock().unwrap().is_none()); + assert_eq!(build.recipe.as_ref().unwrap().run(), 0x5101); + assert_eq!(calls.load(Ordering::Relaxed), 2); + } + #[test] fn a_panicking_pipeline_job_completes_failed_and_wakes_its_waiter() { let build = Arc::new(Build::new(Box::new(|| panic!("simulated pipeline panic")), false)); @@ -1240,6 +1332,21 @@ mod used_tests { submit_lazy_keyed(standin, true, job, 0, Some(compute_key(tag))); } + #[test] + fn coalesced_compute_owners_retain_the_winning_recipe() { + let standins = [0x7E57_C091usize, 0x7E57_C092]; + let winner = Recipe::new(|| 0xC091); + let duplicate = Recipe::new(|| panic!("duplicate recipe ran")); + submit_recipe_keyed(standins[0], true, winner, false, 0, Some(compute_key(0x91))); + submit_recipe_keyed(standins[1], true, duplicate, false, 0, Some(compute_key(0x91))); + + let (a, b) = (entry(standins[0]).unwrap(), entry(standins[1]).unwrap()); + assert!(Arc::ptr_eq(&a.build, &b.build)); + assert_eq!(a.build.recipe.as_ref().unwrap().run(), 0xC091); + assert_eq!(released(standins[0]), 0); + assert_eq!(released(standins[1]), 0); + } + #[test] fn concurrent_equal_compute_submissions_run_one_job() { let standins = [0x7E57_C101usize, 0x7E57_C102]; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 8b526dc511..be1d1d919e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6643,7 +6643,7 @@ pub(in crate::hle::d3d12x) mod compute_build_key; /// A pipeline description that owns what it points to (shader blobs, input layout and its /// semantic names), so a worker can build the pipeline after the title's memory is gone. -/// The root signature pointer is kept as is (the translated paths replace it). +/// The title's borrowed root signature is cleared; translated paths install XCL's ABI signature. #[allow(dead_code)] // the vectors only keep the copies alive enum OwnedDesc { Compute(Box<D3D12_COMPUTE_PIPELINE_STATE_DESC>, Vec<Arc<[u8]>>), @@ -6652,6 +6652,9 @@ enum OwnedDesc { } unsafe impl Send for OwnedDesc {} +// Every pointer in an `OwnedDesc` refers to immutable backing storage owned by the same value. +// The translated builders only read it, so one retained recipe may safely be shared. +unsafe impl Sync for OwnedDesc {} /// A hash of a pipeline's shaders in their order (never 0): what `pso_async` knows a used /// pipeline by in the next run. @@ -6712,6 +6715,8 @@ unsafe fn own_compute(desc: *const c_void) -> Option<OwnedDesc> { let mut d: Box<D3D12_COMPUTE_PIPELINE_STATE_DESC> = Box::new(std::ptr::read(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC)); let mut blobs = Vec::new(); own_shader(&mut d.CS, &mut blobs); + // Console translation installs its ABI root signature. Do not retain the title's borrowed one. + d.pRootSignature = std::mem::ManuallyDrop::new(None); d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); Some(OwnedDesc::Compute(d, blobs)) } @@ -6719,13 +6724,18 @@ unsafe fn own_compute(desc: *const c_void) -> Option<OwnedDesc> { /// None with stream output (not copied; such pipelines are built in the call). unsafe fn own_graphics(desc: *const c_void) -> Option<OwnedDesc> { let mut d: Box<D3D12_GRAPHICS_PIPELINE_STATE_DESC> = Box::new(std::ptr::read(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC)); - if d.StreamOutput.NumEntries > 0 { + if d.StreamOutput.NumEntries > 0 || d.StreamOutput.NumStrides > 0 { return None; } + // Counts are zero, so the pointers are semantically unused; clear them rather than retain + // borrowed title addresses in an object declared safe to share and possibly reuse. + d.StreamOutput = D3D12_STREAM_OUTPUT_DESC::default(); let mut blobs = Vec::new(); for b in [&mut d.VS, &mut d.PS, &mut d.DS, &mut d.HS, &mut d.GS] { own_shader(b, &mut blobs); } + // Console translation installs its ABI root signature. Do not retain the title's borrowed one. + d.pRootSignature = std::mem::ManuallyDrop::new(None); let n = d.InputLayout.NumElements as usize; let mut elems = Vec::new(); let mut names = Vec::new(); @@ -6765,6 +6775,8 @@ unsafe fn own_stream(desc: *const c_void) -> Option<OwnedDesc> { } let word = |buf: &[u8], k: usize| u64::from_le_bytes(buf[at + 8 * k..at + 8 * k + 8].try_into().unwrap()); match ty { + // Translated streams install XCL's ABI root signature. + 0 => buf[at..end].fill(0), 1..=6 | 24 | 25 => { let (p, n) = (word(&buf, 0) as usize, word(&buf, 1) as usize); if p == 0 || n == 0 { @@ -6786,11 +6798,44 @@ unsafe fn own_stream(desc: *const c_void) -> Option<OwnedDesc> { Some(OwnedDesc::Stream(d, buf, blobs)) } -/// Raw pointers a worker needs (the device lives for the process). +#[cfg(test)] +mod owned_desc_tests { + use super::*; + + #[test] + fn graphics_recipe_rejects_buffer_strides_without_declarations() { + let stride = 16u32; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + desc.StreamOutput.pBufferStrides = &stride; + desc.StreamOutput.NumStrides = 1; + desc.StreamOutput.NumEntries = 0; + assert!(unsafe { own_graphics((&desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC).cast()) }.is_none()); + } + + #[test] + fn graphics_recipe_clears_unused_stream_output_pointers() { + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + desc.StreamOutput.pSODeclaration = std::ptr::NonNull::dangling().as_ptr(); + desc.StreamOutput.pBufferStrides = std::ptr::NonNull::dangling().as_ptr(); + let Some(OwnedDesc::Graphics(owned, ..)) = (unsafe { + own_graphics((&desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC).cast()) + }) else { + panic!("zero-count stream output must be accepted") + }; + assert!(owned.StreamOutput.pSODeclaration.is_null()); + assert!(owned.StreamOutput.pBufferStrides.is_null()); + } +} + +/// Raw pointers a one-shot worker needs (the existing process-lifetime device invariant). #[derive(Clone, Copy)] -struct Dev(usize, usize); +struct Dev(usize, PsoFn); unsafe impl Send for Dev {} +/// A gated rebuild recipe owns a device reference independently of the title's references. +#[derive(Clone)] +struct RecipeDev(ID3D12Device, PsoFn); + /// The stand-in for a pipeline with dummy shaders (draws / computes nothing). unsafe fn standin_graphics(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let d = dummy(); @@ -6909,7 +6954,7 @@ unsafe fn go_background( } return None; } - let dev = Dev(this as usize, f as usize); + let dev = Dev(this as usize, f); let key = owned.shaders_key(); let build_key = match &owned { OwnedDesc::Compute(desc, shaders) => shaders.first().map(|shader| { @@ -6919,18 +6964,21 @@ unsafe fn go_background( }; // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); - let job: super::pso_async::Job = Box::new(move || { - let mut out: *mut c_void = std::ptr::null_mut(); - if unsafe { build(dev, &owned, &mut out) } && !out.is_null() { - out as usize + let lazy = super::pso_async::lazy(); + if super::pso_async::rebuild_recipes_enabled() { + let recipe_dev = RecipeDev(ID3D12Device::from_raw_borrowed(&this)?.clone(), f); + let recipe = super::pso_async::Recipe::new(move || { + let dev = Dev(recipe_dev.0.as_raw() as usize, recipe_dev.1); + run_owned_build(dev, &owned, build) + }); + super::pso_async::submit_recipe_keyed(*ppv as usize, compute, recipe, !lazy, if lazy { key } else { 0 }, build_key); + } else { + let job: super::pso_async::Job = Box::new(move || run_owned_build(dev, &owned, build)); + if lazy { + super::pso_async::submit_lazy_keyed(*ppv as usize, compute, job, key, build_key); } else { - 0 + super::pso_async::submit_keyed(*ppv as usize, compute, job, build_key); } - }); - if super::pso_async::lazy() { - super::pso_async::submit_lazy_keyed(*ppv as usize, compute, job, key, build_key); - } else { - super::pso_async::submit_keyed(*ppv as usize, compute, job, build_key); } if driver != 0 { super::pso_async::shared(*ppv as usize, driver); @@ -6941,19 +6989,24 @@ unsafe fn go_background( Some(hr) } +fn run_owned_build(dev: Dev, owned: &OwnedDesc, build: unsafe fn(Dev, &OwnedDesc, *mut *mut c_void) -> bool) -> usize { + let mut out: *mut c_void = std::ptr::null_mut(); + if unsafe { build(dev, owned, &mut out) } && !out.is_null() { out as usize } else { 0 } +} + unsafe fn build_graphics(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); - matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::<usize, PsoFn>(dev.1), d.ptr(), &iid, out, true), Some(hr) if hr >= 0) + matches!(translated_graphics_pso(dev.0 as *mut c_void, dev.1, d.ptr(), &iid, out, true), Some(hr) if hr >= 0) } unsafe fn build_graphics_uncacheable(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); - matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::<usize, PsoFn>(dev.1), d.ptr(), &iid, out, false), Some(hr) if hr >= 0) + matches!(translated_graphics_pso(dev.0 as *mut c_void, dev.1, d.ptr(), &iid, out, false), Some(hr) if hr >= 0) } unsafe fn build_compute(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); - matches!(translated_compute_pso(dev.0 as *mut c_void, std::mem::transmute::<usize, PsoFn>(dev.1), d.ptr(), &iid, out), Some(Ok(hr)) if hr >= 0) + matches!(translated_compute_pso(dev.0 as *mut c_void, dev.1, d.ptr(), &iid, out), Some(Ok(hr)) if hr >= 0) } unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { @@ -10379,6 +10432,21 @@ mod mesh_stream_tests { assert_ne!(rebased, shader.as_ptr() as usize); assert_eq!(&buf[32..48], &[0u8; 16], "zero-len shader entry cleared"); assert_eq!(&buf[56..72], &[0u8; 16], "cached PSO cleared"); + + // A retained stream must not extend the title's root-signature lifetime. Translation + // replaces it, while the shader payload remains rebased to recipe-owned bytes. + let mut rooted = [0u8; 40]; + rooted[0..4].copy_from_slice(&0u32.to_le_bytes()); + rooted[8..16].copy_from_slice(&0xDEAD_BEEFu64.to_le_bytes()); + rooted[16..20].copy_from_slice(&25u32.to_le_bytes()); + rooted[24..32].copy_from_slice(&(shader.as_ptr() as u64).to_le_bytes()); + rooted[32..40].copy_from_slice(&(shader.len() as u64).to_le_bytes()); + let rooted_desc = [rooted.len(), rooted.as_ptr() as usize]; + let OwnedDesc::Stream(_, rooted_buf, rooted_blobs) = own_stream(rooted_desc.as_ptr().cast()).unwrap() else { + panic!("expected Stream") + }; + assert_eq!(&rooted_buf[8..16], &[0; 8]); + assert_eq!(u64::from_le_bytes(rooted_buf[24..32].try_into().unwrap()) as usize, rooted_blobs[0].as_ptr() as usize); } } From 0ce5f0eb8aa62cf3ebbf48fdea3f1f9d6db7680b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:13:58 -0800 Subject: [PATCH 197/265] D3D12.X: count sampled array slices in residency metrics SRV coverage previously deduplicated only mip levels, so a one-slice view counted every slice in an array and later distinct slice views added nothing. Retain disjoint slice intervals per mip and add only newly addressable texels. The accounting remains restricted to XCL_ACTIVITY runs. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/vram.rs | 162 +++++++++++++++++++++++------- 1 file changed, 126 insertions(+), 36 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 3ca925100c..9f1b1655b2 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -374,17 +374,6 @@ fn range_texels(width: u64, height: u32, depth: u16, dim: i32, mips: std::ops::R mips.fold(0u64, |acc, m| acc.saturating_add(mip_texels(width, height, depth, dim, m))) } -fn mip_mask(mips: std::ops::Range<u32>, max_mips: u32) -> u32 { - let cap = max_mips.min(32); - let lo = mips.start.min(cap); - let hi = mips.end.min(cap); - let mut mask = 0u32; - for m in lo..hi { - mask |= 1u32 << m; - } - mask -} - fn srv_mip_range(res_mips: u32, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> std::ops::Range<u32> { let Some(v) = desc else { return 0..res_mips }; // SAFETY: each branch reads only the union field named by `v.ViewDimension`. @@ -402,6 +391,7 @@ fn srv_mip_range(res_mips: u32, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) let s = &v.Anonymous.Texture2D; (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) } + D3D12_SRV_DIMENSION_TEXTURE2DMS | D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY => (0, 1, 0.0), D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { let s = &v.Anonymous.Texture2DArray; (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) @@ -435,6 +425,65 @@ fn srv_mip_range(res_mips: u32, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) start..end } +fn srv_slice_range(res_slices: u32, dim: i32, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> std::ops::Range<u32> { + if dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { + return 0..1; + } + let limit = res_slices.max(1); + let Some(v) = desc else { return 0..limit }; + // SAFETY: each branch reads only the union field named by `v.ViewDimension`. + let (first, count) = unsafe { + match v.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE1D | D3D12_SRV_DIMENSION_TEXTURE2D | D3D12_SRV_DIMENSION_TEXTURE2DMS => (0, 1), + D3D12_SRV_DIMENSION_TEXTURE1DARRAY => { + let s = &v.Anonymous.Texture1DArray; + (s.FirstArraySlice, s.ArraySize) + } + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { + let s = &v.Anonymous.Texture2DArray; + (s.FirstArraySlice, s.ArraySize) + } + D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY => { + let s = &v.Anonymous.Texture2DMSArray; + (s.FirstArraySlice, s.ArraySize) + } + D3D12_SRV_DIMENSION_TEXTURECUBE => (0, 6), + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY => { + let s = &v.Anonymous.TextureCubeArray; + (s.First2DArrayFace, s.NumCubes.saturating_mul(6)) + } + D3D12_SRV_DIMENSION_TEXTURE3D => (0, 1), + _ => return 0..0, + } + }; + let start = first.min(limit); + start..first.saturating_add(count).min(limit) +} + +/// Add `new` to sorted, disjoint half-open ranges and return how many indices were new. +fn union_range(ranges: &mut Vec<std::ops::Range<u32>>, new: std::ops::Range<u32>) -> u32 { + if new.is_empty() { + return 0; + } + let before = ranges.iter().map(|r| r.end - r.start).sum::<u32>(); + let first = ranges.partition_point(|range| range.end < new.start); + let mut end = first; + let mut merged = new; + while end < ranges.len() && ranges[end].start <= merged.end { + merged.start = merged.start.min(ranges[end].start); + merged.end = merged.end.max(ranges[end].end); + end += 1; + } + if first == end { + ranges.insert(first, merged); + } else { + ranges[first] = merged; + ranges.drain(first + 1..end); + } + let after = ranges.iter().map(|r| r.end - r.start).sum::<u32>(); + after - before +} + struct TexelMeta { width: u64, height: u32, @@ -443,7 +492,8 @@ struct TexelMeta { dim: i32, total_texels: u64, resident_texels: u64, - srv_mask: u32, + srv_slices: Vec<Vec<std::ops::Range<u32>>>, + srv_sampled_texels: u64, } impl TexelMeta { @@ -458,29 +508,30 @@ impl TexelMeta { dim: desc.Dimension.0, total_texels, resident_texels: if resident { total_texels } else { 0 }, - srv_mask: 0, - } - } - - fn mask_texels(&self, mask: u32) -> u64 { - let cap = (self.mips as u32).min(32); - let mut total = 0u64; - for m in 0..cap { - if mask & (1u32 << m) != 0 { - total = total.saturating_add(mip_texels(self.width, self.height, self.depth, self.dim, m)); - } + srv_slices: vec![Vec::new(); mips as usize], + srv_sampled_texels: 0, } - total } fn record_srv(&mut self, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> (bool, u64) { - let first_srv = self.srv_mask == 0; - let add = mip_mask(srv_mip_range(self.mips as u32, desc), self.mips as u32) & !self.srv_mask; - if add == 0 { - return (false, 0); + let first_srv = self.srv_sampled_texels == 0; + let mips = srv_mip_range(self.mips as u32, desc); + let slices = srv_slice_range(self.depth as u32, self.dim, desc); + let mut added = 0u64; + for mip in mips { + let new_slices = union_range(&mut self.srv_slices[mip as usize], slices.clone()) as u64; + if new_slices == 0 { + continue; + } + let per_slice = if self.dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { + mip_texels(self.width, self.height, self.depth, self.dim, mip) + } else { + mip_texels(self.width, self.height, 1, self.dim, mip) + }; + added = added.saturating_add(per_slice.saturating_mul(new_slices)); } - self.srv_mask |= add; - (first_srv, self.mask_texels(add)) + self.srv_sampled_texels = self.srv_sampled_texels.saturating_add(added); + (first_srv && added != 0, added) } } @@ -1484,12 +1535,9 @@ fn forget_pages(resource: usize) { } if let Some(tm) = &t.texels { TEXEL_STATS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); - if tm.srv_mask != 0 { + if tm.srv_sampled_texels != 0 { TEXEL_STATS[1].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); - let sampled = tm.mask_texels(tm.srv_mask); - if sampled > 0 { - TEXEL_STATS[4].fetch_sub(sampled, std::sync::atomic::Ordering::Relaxed); - } + TEXEL_STATS[4].fetch_sub(tm.srv_sampled_texels, std::sync::atomic::Ordering::Relaxed); } if tm.total_texels > 0 { TEXEL_STATS[2].fetch_sub(tm.total_texels, std::sync::atomic::Ordering::Relaxed); @@ -3103,6 +3151,48 @@ mod tests { }; assert_eq!(tm.record_srv(Some(&srv_all)), (false, 64 + 1)); assert_eq!(tm.record_srv(Some(&srv_all)), (false, 0)); - assert_eq!(tm.mask_texels(tm.srv_mask), tm.total_texels); + assert_eq!(tm.srv_sampled_texels, tm.total_texels); + } + + #[test] + fn texel_meta_unions_array_slices_without_counting_the_whole_mip() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 6, + MipLevels: 1, + ..Default::default() + }; + let mut tm = TexelMeta::from_desc(&desc, false); + let view = |first| D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: 0, + MipLevels: 1, + FirstArraySlice: first, + ArraySize: 1, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + ..Default::default() + }; + assert_eq!(tm.record_srv(Some(&view(0))), (true, 4096)); + assert_eq!(tm.record_srv(Some(&view(0))), (false, 0)); + assert_eq!(tm.record_srv(Some(&view(1))), (false, 4096)); + assert_eq!(tm.srv_sampled_texels, 8192); + assert_eq!(tm.total_texels, 6 * 4096); + + let ms = D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DMSArray: D3D12_TEX2DMS_ARRAY_SRV { FirstArraySlice: 4, ArraySize: 1 }, + }, + ..Default::default() + }; + assert_eq!(tm.record_srv(Some(&ms)), (false, 4096)); + assert_eq!(tm.srv_sampled_texels, 3 * 4096); } } From f882575889192468362726f118a52c509d45f799 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:27:10 -0800 Subject: [PATCH 198/265] D3D12.X: expose exact submission retirement receipts Future generation-pinned resources need the exact queue progress after native execution, including a fail-closed distinction when execution may have happened but its marker could not be published. Reuse the allocator pool queue marker and keep the existing submission path unchanged. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 195 ++++++++++++++++++++++-- 1 file changed, 186 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index d878fda894..58c93bb7f6 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -434,6 +434,32 @@ pub(super) struct PendingSubmit { entries: Vec<SubmitEntry>, } +/// Exact queue progress after a native submission. Keeping the fence owner makes this receipt +/// independent of a command queue raw address being released and reused for another generation. +#[derive(Clone)] +#[allow(dead_code)] // consumed by the later opt-in generation-pin stage +pub(super) struct SubmissionReceipt { + fence: ID3D12Fence, + value: u64, +} + +#[allow(dead_code)] // consumed by the later opt-in generation-pin stage +impl SubmissionReceipt { + /// Whether the GPU is past the native submission represented by this receipt. + pub(super) fn is_complete(&self) -> bool { + unsafe { self.fence.GetCompletedValue() >= self.value } + } +} + +/// Result of a receipt-requesting submission. Once execution begins, failure to mark it cannot +/// be turned back into `NotExecuted`: callers must retain dependent objects indefinitely. +#[allow(dead_code)] // consumed by the later opt-in generation-pin stage +pub(super) enum ReceiptedSubmission { + NotExecuted, + Executed(SubmissionReceipt), + ExecutedUntracked, +} + fn release_submit_pins(s: &mut State, entries: &[SubmitEntry]) { for entry in entries { let key = (entry.list, entry.lifetime); @@ -558,27 +584,71 @@ impl PendingSubmit { )) } + /// Mark a submission and return its exact queue fence/value. Unlike `finish`, this also makes + /// a marker when allocator swapping is disabled and therefore `entries` is empty. + #[allow(dead_code)] // consumed through `submit_receipted` by the later generation-pin stage + unsafe fn finish_receipted(self, queue: *mut c_void) -> Option<SubmissionReceipt> { + let q = ID3D12CommandQueue::from_raw_borrowed(&queue)?; + let key = queue as usize; + super::queue_submit::with(key, || self.finish_with_queue_ops_receipted( + key, + || { + let mut dev: Option<ID3D12Device> = None; + q.GetDevice(&mut dev).ok()?; + dev?.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok() + }, + |fence, value| super::real::native_queue_signal(q, fence, value).is_ok(), + )) + } + /// The queue turn excludes another thread while the state lock is released around driver /// calls. An `Arc` keeps the exact marker alive; replacement means the queue generation was /// invalidated, so the submitted work deliberately remains pinned. fn finish_with_queue_ops( - mut self, + self, key: usize, create: impl FnOnce() -> Option<ID3D12Fence>, signal: impl FnOnce(&ID3D12Fence, u64) -> bool, ) -> bool { + if self.entries.is_empty() { + return true; + } + self.finish_with_queue_ops_inner(key, create, signal).is_some() + } + + #[allow(dead_code)] // production consumer lands with the generation-pin stage + fn finish_with_queue_ops_receipted( + self, + key: usize, + create: impl FnOnce() -> Option<ID3D12Fence>, + signal: impl FnOnce(&ID3D12Fence, u64) -> bool, + ) -> Option<SubmissionReceipt> { + // `begin_submit` intentionally does not initialize allocator state when swapping is off; + // a requested receipt still needs the shared queue-generation marker namespace. + if self.entries.is_empty() { + STATE.lock().unwrap().get_or_insert_with(State::default); + } + self.finish_with_queue_ops_inner(key, create, signal) + } + + fn finish_with_queue_ops_inner( + mut self, + key: usize, + create: impl FnOnce() -> Option<ID3D12Fence>, + signal: impl FnOnce(&ID3D12Fence, u64) -> bool, + ) -> Option<SubmissionReceipt> { let marker = { let g = lock_for_submit(); - let Some(s) = g.as_ref() else { return false }; + let s = g.as_ref()?; s.fences.get(&key).cloned() }; let marker = match marker { Some(marker) => marker, None => { - let Some(fence) = create() else { return false }; + let fence = create()?; let made = Arc::new(QueueFence::new(fence)); let mut g = lock_for_submit(); - let Some(s) = g.as_mut() else { return false }; + let s = g.as_mut()?; let (marker, unused) = match s.fences.entry(key) { Entry::Occupied(entry) => (Arc::clone(entry.get()), Some(made)), Entry::Vacant(entry) => { @@ -596,19 +666,19 @@ impl PendingSubmit { // atomic reservation lets intentional same-thread re-entry take a distinct later value. // A failed Signal burns its value; its submit remains pinned and a gap is harmless. let Ok(value) = marker.next_value.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| v.checked_add(1)) else { - return false; + return None; }; let value = value + 1; SUBMIT.signal_attempts.fetch_add(1, Ordering::Relaxed); if !signal(&marker.fence, value) { SUBMIT.signal_failures.fetch_add(1, Ordering::Relaxed); - return false; + return None; } let fence = marker.fence.clone(); let mut g = lock_for_submit(); - let Some(s) = g.as_mut() else { return false }; + let s = g.as_mut()?; if s.fences.get(&key).is_none_or(|current| !Arc::ptr_eq(current, &marker)) { - return false; + return None; } let (backing_mark_writes, replaced) = record_submit(s, &self.entries, key, &fence, value); SUBMIT.lists_marked.fetch_add(self.entries.len() as u64, Ordering::Relaxed); @@ -617,7 +687,7 @@ impl PendingSubmit { drop(g); drop(replaced); sweep_release_owners(); - true + Some(SubmissionReceipt { fence, value }) } #[cfg(test)] @@ -676,6 +746,35 @@ impl SubmissionGate { ) } + /// Submit and request an exact retirement receipt. The existing `submit` path remains the + /// zero-extra-marker path; this variant is for future resources that need queue-fenced pins. + #[allow(dead_code)] // production consumer lands with the generation-pin stage + pub(super) unsafe fn submit_receipted( + &mut self, + queue: *mut c_void, + lists: &[*mut c_void], + prepare: impl FnOnce(), + execute: impl FnOnce(), + ) -> ReceiptedSubmission { + if self.failed { + return ReceiptedSubmission::NotExecuted; + } + let Some(begin) = begin_submit(lists) else { + self.failed = true; + return ReceiptedSubmission::NotExecuted; + }; + prepare(); + let pending = begin.execution_possible(); + execute(); + match pending.finish_receipted(queue) { + Some(receipt) => ReceiptedSubmission::Executed(receipt), + None => { + self.failed = true; + ReceiptedSubmission::ExecutedUntracked + } + } + } + pub(super) fn failed(&self) -> bool { self.failed } @@ -1610,6 +1709,84 @@ mod tests { assert_eq!((first_object.refs.get(), old_object.refs.get(), new_object.refs.get()), (0, 0, 0)); } + #[test] + fn submission_receipt_keeps_exact_marker_and_failure_is_untracked() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + + #[repr(C)] + struct Fence { + vtable: *const usize, + value: Cell<u64>, + refs: Cell<u32>, + } + unsafe extern "system" fn completed(this: *mut c_void) -> u64 { + (*this.cast::<Fence>()).value.get() + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let f = &*this.cast::<Fence>(); + f.refs.set(f.refs.get() + 1); + f.refs.get() + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let f = &*this.cast::<Fence>(); + f.refs.set(f.refs.get() - 1); + f.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + + const SLOT: usize = size_of::<usize>(); + let mut vtable = [unexpected_call as usize; size_of::<ID3D12Fence_Vtbl>() / SLOT]; + vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + let mut old_object = Fence { vtable: vtable.as_ptr(), value: Cell::new(0), refs: Cell::new(1) }; + let mut new_object = Fence { vtable: vtable.as_ptr(), value: Cell::new(1), refs: Cell::new(1) }; + let old_fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut old_object).cast()) }; + let new_fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut new_object).cast()) }; + let (list, failed_list, queue) = (0x7ffe_6c01usize, 0x7ffe_6c02usize, 0x7ffe_6c03usize); + + let receipt = begin_submit(&[list as *mut c_void]) + .unwrap() + .execution_possible() + .finish_with_queue_ops_receipted(queue, || Some(old_fence.clone()), |_, value| value == 1) + .expect("the successful Signal has an exact receipt"); + assert!(!receipt.is_complete()); + + let old_marker = STATE.lock().unwrap().as_mut().unwrap().fences.insert( + queue, + Arc::new(QueueFence::new(new_fence.clone())), + ); + drop(old_marker); + assert!(!receipt.is_complete(), "a complete replacement marker cannot satisfy an old receipt"); + old_object.value.set(1); + assert!(receipt.is_complete()); + + let failed = begin_submit(&[failed_list as *mut c_void]).unwrap().execution_possible(); + assert!(failed + .finish_with_queue_ops_receipted(queue, || unreachable!(), |_, value| { + assert_eq!(value, 1); + false + }) + .is_none()); + let (marker, submit) = { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let lifetime = s.list_lifetimes[&failed_list]; + assert_eq!(s.submit_pins.get(&(failed_list, lifetime)), Some(&1), "untracked execution remains pinned"); + s.submit_pins.remove(&(failed_list, lifetime)); + s.list_lifetimes.remove(&failed_list); + s.list_lifetimes.remove(&list); + (s.fences.remove(&queue), s.last_submit.remove(&list)) + }; + drop(marker); + drop(submit); + drop(receipt); + drop(old_fence); + drop(new_fence); + assert_eq!((old_object.refs.get(), new_object.refs.get()), (0, 0)); + } + #[test] fn released_namespace_keeps_busy_made_backing_until_retirement() { let (alloc, made) = (0x7ffe_6100usize, 0x7ffe_6200usize); From bf0db1adc5b5bd957c606bde5f04ea141c72977f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:00:53 -0800 Subject: [PATCH 199/265] D3D12.X: track live texture SRV metadata Texture residency cannot safely replace descriptors until recorded command lists and queue fences carry descriptor generations. Retain only the current CPU-side logical state, keyed by heap generation and slot, so later work has exact resource, device, descriptor, and publication identities without holding COM objects alive. The opt-in tracker serializes complete hooked descriptor mutations, mirrors overwrites and range copies, stores all eight console descriptor words, and provides an unused on-demand generation-checked snapshot that discards raw-memory rewrites. Untrackable fallback sources clear destinations. It does not scan submissions, rewrite descriptors, or change texture mappings. Measured with a Windows GNU cross-target check including tests; executable tests were not run because this Linux host cannot run the Windows target. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/console_heap.rs | 43 ++- crates/xcl/src/hle/d3d12x/real.rs | 31 ++- crates/xcl/src/hle/d3d12x/vram.rs | 307 ++++++++++++++++++++++ 3 files changed, 376 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 718ceaa3e9..15cb8a4361 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -497,7 +497,14 @@ pub struct Taken(Heap); /// Stop finding a heap by object address without freeing memory the object may still use. pub fn take(obj: usize) -> Option<Taken> { let mut heaps = HEAPS.lock().unwrap(); - heaps.iter().position(|h| h.obj == obj).map(|i| Taken(heaps.swap_remove(i))) + let heap = heaps.iter().position(|h| h.obj == obj).map(|i| heaps.swap_remove(i)); + drop(heaps); + if let Some(heap) = heap { + super::vram::forget_srv_heap(heap.generation); + Some(Taken(heap)) + } else { + None + } } /// Return a taken heap's slots and shadow memory after its native object is gone. @@ -763,6 +770,19 @@ pub fn copy_words(src: &Slot, dst: &Slot) { } } +/// The tracking-only form of `copy_words`, retaining the exact source and destination bytes. +pub fn copy_words_captured(src: &Slot, dst: &Slot) -> ([u32; 8], [u32; 8]) { + let mut source = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping(src.at as *const u32, source.as_mut_ptr(), 8) }; + let mut destination = source; + if destination[3] >> 28 >= 8 { + destination[0] = dst.index; + } + write(dst, &destination); + note_resource(dst, resource_at(src.at).unwrap_or(0)); + (source, destination) +} + /// `XCL_TRACE_FRAME`: what the slots of each shader-visible view heap hold – images whose /// PC index is the slot's own (made or copied through the device) or another (copied by the /// title itself, as memory), buffers, empty. @@ -835,6 +855,27 @@ pub fn words_at(addr32: u32) -> Option<[u32; 8]> { Some(w) } +/// Exact console words currently in view slots identified by heap generation and slot number. +/// Build the generation index once so validating S tracked slots across H heaps is O(S + H), and +/// keep `HEAPS` held while reading so the backing storage cannot be freed underneath us. +pub(super) fn view_slot_words(slots: &[(u64, u32)]) -> Vec<Option<[u32; 8]>> { + let heaps = HEAPS.lock().unwrap(); + let by_generation: std::collections::HashMap<_, _> = heaps + .iter() + .filter(|heap| !heap.sampler) + .map(|heap| (heap.generation, heap)) + .collect(); + slots + .iter() + .map(|&(generation, k)| { + let h = by_generation.get(&generation).filter(|heap| k < heap.n)?; + let mut words = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping((h.shadow + (k * SLOT) as usize) as *const u32, words.as_mut_ptr(), 8) }; + Some(words) + }) + .collect() +} + // --------------------------------------------------------------------------------------- // Shared shader-visible PC sampler heap (`GLOBAL_SAMPLER`, up to D3D12's 2048 limit): // allows 16-byte S# descriptors copied via raw CPU `memcpy` between CPU-only and diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index be1d1d919e..0ebbda85b6 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2053,12 +2053,14 @@ unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12 let f: unsafe extern "system" fn(*mut c_void, *const D3D12_CONSTANT_BUFFER_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 17)); return f(this, desc, cpu); }; + let _tracked_write_lock = super::vram::lock_tracked_srv_write(); let (va, size) = desc.as_ref().map_or((0, 0), |d| (d.BufferLocation, d.SizeInBytes)); let in_uma = crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)); if !in_uma { note_buffer_view(); } let (va, size) = if in_uma { (va, size) } else { (0, 0) }; + super::vram::clear_tracked_srv(&slot); super::console_heap::write(&slot, &crate::gpu::desc::cbv_words(va, size)); } @@ -2076,21 +2078,31 @@ pub(super) unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, des /// Copy `n` console slots from `src` to `dst` (both in console heaps of one kind): the PC /// descriptors (2 per view slot) and the slots. False: not two console ranges. unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) -> bool { - use super::console_heap::{copy_words, slot, SAMPLER_SLOT, SLOT}; + use super::console_heap::{copy_words, copy_words_captured, slot, SAMPLER_SLOT, SLOT}; let (Some(d0), Some(s0)) = (slot(dst), slot(src)) else { return false }; if d0.sampler != s0.sampler { return false; } + let _tracked_write_lock = (!d0.sampler).then(super::vram::lock_tracked_srv_write).flatten(); + let step = if d0.sampler { SAMPLER_SLOT } else { SLOT } as u64; let ty = pc_heap_type(ty); let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, if d0.sampler { n } else { 2 * n }, d0.pc_srv, s0.pc_srv, ty); super::console_heap::publish_range(&d0, n); - let step = if d0.sampler { SAMPLER_SLOT } else { SLOT } as u64; + let mut tracked_copies = (!d0.sampler && super::vram::srv_tracking_enabled()).then(Vec::new); for k in 0..n as u64 { if let (Some(d), Some(s)) = (slot(dst + k * step), slot(src + k * step)) { - copy_words(&s, &d); + if let Some(copies) = tracked_copies.as_mut() { + let (source_words, destination_words) = copy_words_captured(&s, &d); + copies.push((s, d, source_words, destination_words)); + } else { + copy_words(&s, &d); + } } } + if let Some(copies) = tracked_copies { + super::vram::copy_tracked_srvs(this as usize, &copies); + } true } @@ -2389,6 +2401,8 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } let desc = copy.as_ref().map_or(desc, |c| c as *const _); let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; + let _tracked_write_lock = super::vram::lock_tracked_srv_write(); + super::vram::clear_tracked_srv(&slot); // Raytracing acceleration structure SRV (pResource == NULL, Location == console GPU VA): // translated shaders read BVH nodes from UMA (`bvh_intersect`), never from a PC DXR SRV, // so write the RDNA2 BVH descriptor directly and skip forwarding the console VA to PC. @@ -2462,7 +2476,10 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } let rdesc = r.GetDesc(); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { - Some(t) => super::console_heap::write(&slot, &t), + Some(t) => { + super::console_heap::write(&slot, &t); + super::vram::track_srv(this as usize, res as usize, &slot, desc.as_ref().copied(), t); + } None => { note_buffer_view(); super::console_heap::write(&slot, &[0; 8]); @@ -2530,6 +2547,8 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u if v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let Some(slot) = super::console_heap::slot(cpu) else { return }; + let _tracked_write_lock = super::vram::lock_tracked_srv_write(); + super::vram::clear_tracked_srv(&slot); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); @@ -2549,6 +2568,8 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); if v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER { let Some(slot) = super::console_heap::slot(cpu) else { return }; + let _tracked_write_lock = super::vram::lock_tracked_srv_write(); + super::vram::clear_tracked_srv(&slot); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); @@ -2804,6 +2825,8 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } }; let Some(slot) = super::console_heap::slot(cpu) else { return pc_uav(cpu) }; + let _tracked_write_lock = super::vram::lock_tracked_srv_write(); + super::vram::clear_tracked_srv(&slot); pc_uav(slot.pc_uav); super::console_heap::publish(&slot, true); super::console_heap::note_resource(&slot, res as usize); diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 9f1b1655b2..26d0b39306 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -132,12 +132,227 @@ pub(super) fn arena_bytes_for(device: usize) -> usize { } static PLACED_TEXTURES: Mutex<Option<HashSet<usize>>> = Mutex::new(None); +/// `XCL_TEXTURE_BUDGET_EVICT=1`: retain CPU-side identities for live texture SRVs. This is +/// preparation only: recorded command lists can still name older descriptor contents, so these +/// records do not make descriptor replacement or texture eviction GPU-safe. +pub(super) fn srv_tracking_enabled() -> bool { + #[cfg(test)] + if SRV_TRACKING_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) { + return true; + } + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_TEXTURE_BUDGET_EVICT").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("D3D12.X: XCL_TEXTURE_BUDGET_EVICT=1 - tracking live texture SRV metadata only; texture mappings and descriptors are unchanged"); + } + on + }) +} + +#[cfg(test)] +static SRV_TRACKING_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub(super) struct SrvSlot { + heap_generation: u64, + slot: u32, +} + +impl SrvSlot { + fn of(slot: &super::console_heap::Slot) -> Self { + Self { heap_generation: slot.generation, slot: slot.k } + } +} + +/// Numeric COM identities are never dereferenced here. Resource and heap lifetime hooks remove +/// them; a later descriptor-generation design must still prove queue-fence safety before use. +#[derive(Clone, Copy)] +#[cfg_attr(not(test), allow(dead_code))] +struct TrackedSrv { + generation: u64, + device: usize, + resource: usize, + pc_srv: u64, + shared_srv: u64, + index: u32, + desc: Option<D3D12_SHADER_RESOURCE_VIEW_DESC>, + /// Exact XCL ABI descriptor bytes written for this logical generation. Only shared-heap slots + /// are tracked: their global word-0 index makes an unhooked raw overwrite observable. + words: [u32; 8], +} + +#[derive(Default)] +struct TrackedSrvs { + next_generation: u64, + by_slot: HashMap<SrvSlot, TrackedSrv>, +} + +impl TrackedSrvs { + fn write(&mut self, slot: SrvSlot, entry: Option<TrackedSrv>) { + self.by_slot.remove(&slot); + if let Some(mut entry) = entry { + self.next_generation = self.next_generation.wrapping_add(1).max(1); + entry.generation = self.next_generation; + self.by_slot.insert(slot, entry); + } + } + + fn copy_range( + &mut self, + device: usize, + copies: &[(SrvSlot, u64, u64, u32, SrvSlot, bool, [u32; 8], [u32; 8])], + ) { + let sources: Vec<_> = copies.iter().map(|(src, _, _, _, _, track_source, ..)| + track_source.then(|| self.by_slot.get(src).copied()).flatten()).collect(); + for ((_, pc_srv, shared_srv, index, dst, _, source_words, destination_words), source) in copies.iter().zip(sources) { + let entry = source.filter(|entry| entry.words == *source_words).map(|mut entry| { + entry.device = device; + entry.pc_srv = *pc_srv; + entry.shared_srv = *shared_srv; + entry.index = *index; + entry.words = *destination_words; + entry + }); + self.write(*dst, entry); + } + } + + fn forget_heap(&mut self, generation: u64) { + self.by_slot.retain(|slot, _| slot.heap_generation != generation); + } + + fn forget_resource(&mut self, resource: usize) { + self.by_slot.retain(|_, entry| entry.resource != resource); + } + + /// Apply raw-memory observations made without this lock. A concurrent tracked overwrite has + /// another logical generation and is omitted from this snapshot rather than judged against + /// words observed for its predecessor. + fn reconcile_observed(&mut self, observed: &[(SrvSlot, u64, Option<[u32; 8]>)]) -> Vec<(SrvSlot, TrackedSrv)> { + let mut snapshot = Vec::new(); + for &(slot, generation, words) in observed { + let Some(entry) = self.by_slot.get(&slot).copied().filter(|entry| entry.generation == generation) else { continue }; + if words == Some(entry.words) { + snapshot.push((slot, entry)); + } else { + self.by_slot.remove(&slot); + } + } + snapshot + } +} + +static TRACKED_SRVS: Mutex<Option<TrackedSrvs>> = Mutex::new(None); +static TRACKED_SRV_WRITES: Mutex<()> = Mutex::new(()); + +/// Serialize an entire hooked descriptor mutation while tracking is enabled. Operation tokens +/// alone order hook starts, not native/console writes that complete in the opposite order. +pub(super) fn lock_tracked_srv_write() -> Option<std::sync::MutexGuard<'static, ()>> { + srv_tracking_enabled().then(|| TRACKED_SRV_WRITES.lock().unwrap()) +} + +/// Record the descriptor currently in `slot`. `None` clears an SRV overwritten by another view. +pub(super) fn track_srv( + device: usize, + resource: usize, + slot: &super::console_heap::Slot, + desc: Option<D3D12_SHADER_RESOURCE_VIEW_DESC>, + words: [u32; 8], +) { + if !srv_tracking_enabled() || slot.shared_srv == 0 { + return; + } + let texture_view = desc.is_none_or(|v| { + v.ViewDimension != D3D12_SRV_DIMENSION_BUFFER && v.ViewDimension != D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE + }); + let entry = (resource != 0 && texture_view && is_placed_texture(resource)).then_some(TrackedSrv { + generation: 0, + device, + resource, + pc_srv: slot.pc_srv, + shared_srv: slot.shared_srv, + index: slot.index, + desc, + words, + }); + TRACKED_SRVS.lock().unwrap().get_or_insert_with(Default::default).write(SrvSlot::of(slot), entry); +} + +pub(super) fn clear_tracked_srv(slot: &super::console_heap::Slot) { + if srv_tracking_enabled() { + TRACKED_SRVS.lock().unwrap().get_or_insert_with(Default::default).write(SrvSlot::of(slot), None); + } +} + +pub(super) fn copy_tracked_srvs( + device: usize, + copies: &[(super::console_heap::Slot, super::console_heap::Slot, [u32; 8], [u32; 8])], +) { + if !srv_tracking_enabled() || copies.is_empty() { + return; + } + let copies: Vec<_> = copies + .iter() + .map(|(src, dst, source_words, destination_words)| + (SrvSlot::of(src), dst.pc_srv, dst.shared_srv, dst.index, SrvSlot::of(dst), + src.shared_srv != 0 && dst.shared_srv != 0, *source_words, *destination_words)) + .collect(); + TRACKED_SRVS.lock().unwrap().get_or_insert_with(Default::default).copy_range(device, &copies); +} + +pub(super) fn forget_srv_heap(generation: u64) { + if !srv_tracking_enabled() { + return; + } + let _write = lock_tracked_srv_write(); + if let Some(tracked) = TRACKED_SRVS.lock().unwrap().as_mut() { + tracked.forget_heap(generation); + } +} + +fn forget_tracked_srvs(resource: usize) { + if !srv_tracking_enabled() { + return; + } + let _write = lock_tracked_srv_write(); + if let Some(tracked) = TRACKED_SRVS.lock().unwrap().as_mut() { + tracked.forget_resource(resource); + } +} + +/// An exact, on-demand snapshot for a future residency consumer. It is deliberately not on the +/// submit path: scanning every live SRV there would turn descriptor count into foreground cost. +/// A consumer must still capture descriptor generations with recorded lists and queue fences; +/// title code can raw-write descriptor memory immediately after this point-in-time snapshot. +#[allow(dead_code)] +fn reconciled_tracked_srvs() -> Vec<(SrvSlot, TrackedSrv)> { + if !srv_tracking_enabled() { + return Vec::new(); + } + let candidates: Vec<_> = TRACKED_SRVS + .lock() + .unwrap() + .as_ref() + .map(|tracked| tracked.by_slot.iter().map(|(&slot, entry)| (slot, entry.generation)).collect()) + .unwrap_or_default(); + let slots: Vec<_> = candidates.iter().map(|(slot, _)| (slot.heap_generation, slot.slot)).collect(); + let words = super::console_heap::view_slot_words(&slots); + let observed: Vec<_> = candidates + .into_iter() + .zip(words) + .map(|((slot, generation), words)| (slot, generation, words)) + .collect(); + TRACKED_SRVS.lock().unwrap().as_mut().map_or_else(Vec::new, |tracked| tracked.reconcile_observed(&observed)) +} + /// A texture backed by one of the aliasable D3D12 heaps. pub(super) fn is_placed_texture(resource: usize) -> bool { PLACED_TEXTURES.lock().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) } pub(super) fn forget(resource: usize) { + forget_tracked_srvs(resource); let placed = PLACED_TEXTURES.lock().unwrap().as_mut().is_some_and(|textures| textures.remove(&resource)); if placed { forget_pages(resource); @@ -2032,6 +2247,98 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st mod tests { use super::*; + fn tracked_entry(resource: usize, pc_srv: u64) -> TrackedSrv { + let mut words = [0u32; 8]; + words[0] = pc_srv as u32; + words[1] = resource as u32; + words[3] = 9 << 28; + TrackedSrv { + generation: 0, device: 7, resource, pc_srv, shared_srv: pc_srv + 1, + index: pc_srv as u32, desc: Some(D3D12_SHADER_RESOURCE_VIEW_DESC::default()), words, + } + } + + fn srv_slot(heap_generation: u64, slot: u32) -> SrvSlot { + SrvSlot { heap_generation, slot } + } + + #[test] + fn tracked_srv_copy_requires_exact_source_words() { + let mut tracked = TrackedSrvs::default(); + let (source, copied, raw_changed) = (srv_slot(1, 0), srv_slot(2, 0), srv_slot(2, 1)); + tracked.write(source, Some(tracked_entry(10, 100))); + let source_words = tracked.by_slot[&source].words; + let mut copied_words = source_words; + copied_words[0] = 21; + tracked.copy_range(8, &[(source, 201, 202, 21, copied, true, source_words, copied_words)]); + assert_eq!(tracked.by_slot[&copied].resource, 10); + + let mut changed_words = source_words; + changed_words[1] ^= 1; + tracked.copy_range(8, &[(source, 301, 302, 31, raw_changed, true, changed_words, copied_words)]); + assert!(!tracked.by_slot.contains_key(&raw_changed)); + tracked.write(raw_changed, Some(tracked_entry(30, 300))); + tracked.copy_range(8, &[(source, 301, 302, 31, raw_changed, false, source_words, copied_words)]); + assert!(!tracked.by_slot.contains_key(&raw_changed), "an untrackable source clears the destination"); + } + + #[test] + fn tracked_srv_reconciliation_invalidates_same_index_word_change() { + let mut tracked = TrackedSrvs::default(); + let slot = srv_slot(1, 0); + tracked.write(slot, Some(tracked_entry(10, 100))); + let generation = tracked.by_slot[&slot].generation; + let mut changed = tracked.by_slot[&slot].words; + changed[1] ^= 1; + assert_eq!(changed[0], tracked.by_slot[&slot].words[0], "the PC descriptor index is unchanged"); + assert!(tracked.reconcile_observed(&[(slot, generation, Some(changed))]).is_empty()); + assert!(tracked.by_slot.is_empty(), "all eight console words identify the logical descriptor"); + } + + #[test] + fn tracked_srv_reconciliation_rejects_cross_heap_local_index_collision() { + let mut tracked = TrackedSrvs::default(); + let (source, destination) = (srv_slot(1, 3), srv_slot(2, 3)); + tracked.write(source, Some(tracked_entry(10, 6))); + tracked.write(destination, Some(tracked_entry(20, 6))); + let generation = tracked.by_slot[&destination].generation; + let copied_words = tracked.by_slot[&source].words; + assert_eq!(copied_words[0], tracked.by_slot[&destination].words[0], "fallback heaps repeat local index 2*k"); + assert!(tracked.reconcile_observed(&[(destination, generation, Some(copied_words))]).is_empty()); + assert!(!tracked.by_slot.contains_key(&destination)); + assert!(tracked.by_slot.contains_key(&source)); + } + + #[test] + fn tracked_srv_reconciliation_does_not_remove_a_newer_generation() { + let mut tracked = TrackedSrvs::default(); + let slot = srv_slot(1, 4); + tracked.write(slot, Some(tracked_entry(10, 8))); + let observed_generation = tracked.by_slot[&slot].generation; + tracked.write(slot, Some(tracked_entry(20, 8))); + let stale_words = tracked_entry(10, 8).words; + assert!(tracked.reconcile_observed(&[(slot, observed_generation, Some(stale_words))]).is_empty()); + assert_eq!(tracked.by_slot[&slot].resource, 20); + } + + #[test] + fn tracked_srv_global_cleanup_hooks_are_gated_and_exact() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).extend([10, 20]); + let (heap_40, heap_41) = (srv_slot(40, 0), srv_slot(41, 0)); + let mut tracked = TrackedSrvs::default(); + tracked.write(heap_40, Some(tracked_entry(10, 100))); + tracked.write(heap_41, Some(tracked_entry(20, 200))); + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + forget_srv_heap(40); + forget(20); + assert!(TRACKED_SRVS.lock().unwrap().as_ref().is_some_and(|tracked| tracked.by_slot.is_empty())); + PLACED_TEXTURES.lock().unwrap().as_mut().unwrap().remove(&10); + TRACKED_SRVS.lock().unwrap().take(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + #[test] fn title_queue_mapping_wait_reservation_is_monotonic_and_per_queue() { let mut waited = HashMap::new(); From 41a369ee4afe40fa34646594c85f53090fdeaada Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:25:16 -0800 Subject: [PATCH 200/265] D3D12.X: publish sparse upload hashes after queue receipt Dirty scanning used to mark chunks sent before command-list close, execution, and queue signalling established that the bytes had a durable ordering receipt. Capture hashes from each bounded staging batch and publish them only after that batch is signalled. Keep a signal-failed generation alive because its GPU completion cannot be proven. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 299 +++++++++++++++++++--------- 1 file changed, 200 insertions(+), 99 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index f2178abe3b..61358b4f76 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -202,6 +202,13 @@ struct UploadSlot { fence_val: u64, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum SubmitResult { + Submitted, + NotSubmitted, + Unordered, +} + struct RetiredTiles { tiles: Vec<(u32, u32)>, /// Fence marks on `self.queue` and every known title queue (`None` = signal failed, keep held). @@ -254,6 +261,9 @@ struct State { ring_free: u64, /// submitted ring chunks awaiting GPU completion: `(fence_val, ring_end_pos)` inflight: VecDeque<(u64, u64)>, + /// false after ExecuteCommandLists succeeded but its ordering Signal failed: no upload + /// allocator or staging byte may be reused because completion can no longer be proved. + uploads_ordered: bool, /// dedicated 1 MiB pre-zeroed buffer for tile/hole clears (zero staging bandwidth) zero_buf: Option<ID3D12Resource>, /// ring of async upload command allocators + lists @@ -357,18 +367,34 @@ fn land_page(slot: &mut Option<Box<[u64; CHUNKS]>>, page: &mut [u8], at: usize, } } -/// Scan a 4 KiB page at `pg`, appending any changed 64-byte chunk runs directly to `out` -/// (zero per-page heap allocation; skips allocating `slot` completely when a fresh zero page -/// is still all zeros). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct HashUpdate { + at: usize, + hash: u64, +} + +const MAX_BATCH_HASH_UPDATES: usize = STAGING / CHUNK; + +fn batch_hash_plan_would_overflow(current: usize, bytes: usize) -> bool { + bytes / CHUNK > MAX_BATCH_HASH_UPDATES.saturating_sub(current) +} + +/// Plan changed 64-byte chunk runs in a 4 KiB page without publishing their hashes. The hashes +/// become `sent` only after the corresponding upload has a durable queue-fence receipt. +/// This keeps the fresh-zero-page fast path allocation-free. #[inline] -fn scan_page(page: &[u8], pg: usize, slot: &mut Option<Box<[u64; CHUNKS]>>, out: &mut Vec<(usize, usize)>) { - if let Some(sent) = slot.as_deref_mut() { +fn scan_page( + page: &[u8], + pg: usize, + slot: &Option<Box<[u64; CHUNKS]>>, + out: &mut Vec<(usize, usize)>, +) { + if let Some(sent) = slot.as_deref() { for (k, c) in page.chunks_exact(CHUNK).enumerate() { let h = chunk_hash(c); if h == sent[k] { continue; } - sent[k] = h; push_run(out, pg + k * CHUNK, CHUNK); } return; @@ -385,21 +411,45 @@ fn scan_page(page: &[u8], pg: usize, slot: &mut Option<Box<[u64; CHUNKS]>>, out: if h == ZERO_HASH { continue; } - let sent = slot.insert(Box::new(ZERO_HASHES)); - sent[k] = h; push_run(out, pg + k * CHUNK, CHUNK); for (k2, c2) in chunks { let h2 = chunk_hash(c2); if h2 == ZERO_HASH { continue; } - sent[k2] = h2; push_run(out, pg + k2 * CHUNK, CHUNK); } break; } } +fn append_hash_updates(at: usize, bytes: &[u8], updates: &mut Vec<HashUpdate>) { + debug_assert_eq!(at % CHUNK, 0); + debug_assert_eq!(bytes.len() % CHUNK, 0); + debug_assert!(updates.len() + bytes.len() / CHUNK <= MAX_BATCH_HASH_UPDATES); + updates.extend(bytes.chunks_exact(CHUNK).enumerate().map(|(i, chunk)| HashUpdate { + at: at + i * CHUNK, + hash: chunk_hash(chunk), + })); +} + +fn publish_hash_updates(mapped: &mut FxHashMap<usize, TileEntry>, updates: &[HashUpdate]) { + for update in updates { + let tile = update.at & !(TILE - 1); + let Some(entry) = mapped.get_mut(&tile) else { continue }; + let page = update.at & !(PAGE - 1); + let index = (page - tile) / PAGE; + let chunk = (update.at - page) / CHUNK; + if entry.holes & (1u16 << index) != 0 { + continue; + } + if update.hash == ZERO_HASH && entry.sent[index].is_none() { + continue; + } + entry.sent[index].get_or_insert_with(|| Box::new(ZERO_HASHES))[chunk] = update.hash; + } +} + /// The byte ranges (offset, length) of `page` whose 64-byte chunks differ from `sent` /// (updated to the page's chunks). pub fn changed_chunks(page: &[u8], sent: &mut [u64; CHUNKS]) -> Vec<(usize, usize)> { @@ -676,6 +726,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { ring_submitted: 0, ring_free: 0, inflight: VecDeque::new(), + uploads_ordered: true, zero_buf: None, slots, next_slot: 0, @@ -706,7 +757,15 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { mark_protection(&mut s.mapped, a, b - a, false); } drop(state); - drop(old); + if old.as_ref().is_some_and(|state| !state.uploads_ordered) { + // ExecuteCommandLists was accepted but no fence can prove when its allocator, + // staging source, or destination windows become unused. Keep that generation + // alive until process exit rather than release memory the GPU may still touch. + crate::xlog_warn!("sparse: retaining an unordered upload generation after its queue Signal failed"); + std::mem::forget(old); + } else { + drop(old); + } drop(old_queue); out } @@ -1017,21 +1076,29 @@ impl State { /// Close and submit upload slot `idx` asynchronously (NO CPU wait — callers order GPU work /// via `queue.Wait(&self.fence, self.value)`). - unsafe fn submit_slot(&mut self, idx: usize) { - let closed = self.slots[idx].list.Close().is_ok(); - if closed { - if let Ok(l) = self.slots[idx].list.cast::<ID3D12CommandList>() { - super::title_textures::own_work(|| { - super::real::native_queue_execute(&self.queue, &l); - }); - } + unsafe fn submit_slot(&mut self, idx: usize) -> SubmitResult { + if self.slots[idx].list.Close().is_err() { + return SubmitResult::NotSubmitted; } - self.signal(); - self.slots[idx].fence_val = self.value; + let Ok(l) = self.slots[idx].list.cast::<ID3D12CommandList>() else { + return SubmitResult::NotSubmitted; + }; + super::title_textures::own_work(|| { + super::real::native_queue_execute(&self.queue, &l); + }); + let value = self.value + 1; + if super::real::native_queue_signal(&self.queue, &self.fence, value).is_err() { + self.uploads_ordered = false; + self.slots[idx].fence_val = u64::MAX; + return SubmitResult::Unordered; + } + self.value = value; + self.slots[idx].fence_val = value; if self.ring_write > self.ring_submitted { - self.inflight.push_back((self.value, self.ring_write)); + self.inflight.push_back((value, self.ring_write)); self.ring_submitted = self.ring_write; } + SubmitResult::Submitted } unsafe fn staging_ptr(&mut self) -> Option<*mut u8> { @@ -1129,30 +1196,8 @@ impl State { } } - /// Make only the chunks overlapping `[a, a + n)` differ from their recorded hashes, so a - /// partial upload failure does not also resend earlier chunks in the same CPU page. - unsafe fn retry_sent_range(&mut self, a: usize, n: usize) { - let end = a + n; - let mut at = a; - while at < end { - let page = at & !(PAGE - 1); - let tile = page & !(TILE - 1); - let page_end = (page + PAGE).min(end); - if let Some(entry) = self.mapped.get_mut(&tile) { - let index = (page - tile) / PAGE; - let Some(sent) = entry.sent[index].as_mut() else { - at = page_end; - continue; - }; - let first = (at - page) / CHUNK; - let last = (page_end - page).div_ceil(CHUNK); - let bytes = std::slice::from_raw_parts(page as *const u8, PAGE); - for chunk in first..last { - sent[chunk] = chunk_hash(&bytes[chunk * CHUNK..(chunk + 1) * CHUNK]) ^ 1; - } - } - at = page_end; - } + fn publish_hashes(&mut self, updates: &[HashUpdate]) { + publish_hash_updates(&mut self.mapped, updates); } /// Copy `ranges` (address, bytes) from sparse VRAM back into the CPU view and refresh @@ -1249,7 +1294,7 @@ impl State { if runs.is_empty() { return true; } - if !self.ensure_zero_buf() { + if !self.uploads_ordered || !self.ensure_zero_buf() { return false; } let Some(slot_idx) = self.begin_slot() else { return false }; @@ -1277,8 +1322,7 @@ impl State { done += chunk; } } - self.submit_slot(slot_idx); - true + self.submit_slot(slot_idx) == SubmitResult::Submitted } /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via @@ -1287,21 +1331,21 @@ impl State { self.upload_dirty_with_timeout(runs, 5000) } - fn retry_dirty_from(&mut self, runs: &[(usize, usize)], index: usize, done: usize) { - visit_unsubmitted_dirty(runs, index, done, |a, n| unsafe { self.retry_sent_range(a, n) }); - } - unsafe fn upload_dirty_with_timeout(&mut self, runs: &[(usize, usize)], wait_ms: u32) -> bool { if runs.is_empty() { return true; } + if !self.uploads_ordered { + return false; + } let Some(p) = self.staging_ptr() else { - self.retry_dirty_from(runs, 0, 0); return false; }; let mut open_slot: Option<usize> = None; + let mut batch_start = self.ring_write; + let mut batch_updates = Vec::new(); let mut last_wi: Option<usize> = None; - for (run_index, &(a, n)) in runs.iter().enumerate() { + for &(a, n) in runs { let mut done = 0usize; while done < n { let cur = a + done; @@ -1313,7 +1357,9 @@ impl State { i } None => { - self.retry_dirty_from(runs, run_index, done); + if open_slot.is_some() { + self.ring_write = batch_start; + } return false; } }, @@ -1325,19 +1371,27 @@ impl State { self.reclaim_ring(); if (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { if let Some(slot_idx) = open_slot.take() { - self.submit_slot(slot_idx); + match self.submit_slot(slot_idx) { + SubmitResult::Submitted => { + self.publish_hashes(&batch_updates); + batch_updates.clear(); + } + SubmitResult::NotSubmitted => { + self.ring_write = batch_start; + return false; + } + SubmitResult::Unordered => return false, + } self.reclaim_ring(); } while (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { let Some(&(fv, _)) = self.inflight.front() else { - self.retry_dirty_from(runs, run_index, done); crate::xlog_warn!("sparse: the staging ring is full without a retirement fence; the unsubmitted CPU writes will be retried"); return false; }; let reached = self.wait_for_ms(fv, wait_ms); self.reclaim_ring(); if !reached { - self.retry_dirty_from(runs, run_index, done); static RING_STALLS: AtomicU64 = AtomicU64::new(0); let stalls = RING_STALLS.fetch_add(1, Ordering::Relaxed) + 1; if stalls <= 4 || stalls.is_power_of_two() { @@ -1348,19 +1402,35 @@ impl State { } } } + if open_slot.is_some() && batch_hash_plan_would_overflow(batch_updates.len(), chunk) { + let slot_idx = open_slot.take().unwrap(); + match self.submit_slot(slot_idx) { + SubmitResult::Submitted => { + self.publish_hashes(&batch_updates); + batch_updates.clear(); + self.reclaim_ring(); + } + SubmitResult::NotSubmitted => { + self.ring_write = batch_start; + return false; + } + SubmitResult::Unordered => return false, + } + } let slot_idx = match open_slot { Some(idx) => idx, None => { let Some(idx) = self.begin_slot() else { - self.retry_dirty_from(runs, run_index, done); return false; }; + batch_start = self.ring_write; open_slot = Some(idx); idx } }; let dst_off = (aligned as usize) % STAGING; std::ptr::copy_nonoverlapping(cur as *const u8, p.add(dst_off), chunk); + append_hash_updates(cur, std::slice::from_raw_parts(p.add(dst_off), chunk), &mut batch_updates); let staging_res = &self.staging.as_ref().unwrap().0; self.slots[slot_idx].list.CopyBufferRegion(&self.windows[wi].1, (cur - b) as u64, staging_res, dst_off as u64, chunk as u64); self.ring_write = aligned + chunk as u64; @@ -1368,7 +1438,14 @@ impl State { } } if let Some(slot_idx) = open_slot { - self.submit_slot(slot_idx); + match self.submit_slot(slot_idx) { + SubmitResult::Submitted => self.publish_hashes(&batch_updates), + SubmitResult::NotSubmitted => { + self.ring_write = batch_start; + return false; + } + SubmitResult::Unordered => return false, + } } true } @@ -1490,7 +1567,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { let idx = (p - t) / PAGE; if entry.holes & (1u16 << idx) == 0 { let bytes = std::slice::from_raw_parts(p as *const u8, PAGE); - scan_page(bytes, p, &mut entry.sent[idx], &mut dirty_runs); + scan_page(bytes, p, &entry.sent[idx], &mut dirty_runs); } p += PAGE; } @@ -1981,16 +2058,6 @@ fn observed_completion<F>(observed: &[(F, u64)], fence: &F, same: impl Fn(&F, &F observed.iter().find_map(|(known, value)| same(known, fence).then_some(*value)).unwrap_or(0) } -fn visit_unsubmitted_dirty(runs: &[(usize, usize)], index: usize, done: usize, mut visit: impl FnMut(usize, usize)) { - let (a, n) = runs[index]; - if done < n { - visit(a + done, n - done); - } - for &(a, n) in &runs[index + 1..] { - visit(a, n); - } -} - fn reserve_queue_wait(waited: &mut FxHashMap<usize, u64>, queue: usize, value: u64) -> bool { if value == 0 || waited.get(&queue).copied().unwrap_or(0) >= value { return false; @@ -2067,7 +2134,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], let idx = (pg - t) / PAGE; if entry.holes & (1u16 << idx) == 0 { let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); - scan_page(bytes, pg, &mut entry.sent[idx], &mut dirty_runs); + scan_page(bytes, pg, &entry.sent[idx], &mut dirty_runs); } pg += PAGE; } @@ -2444,18 +2511,6 @@ mod tests { assert_eq!(waited, FxHashMap::from_iter([(1, 5), (2, 3)])); } - #[test] - fn a_stalled_ring_retries_only_the_unsubmitted_dirty_suffix() { - let runs = [(0x1000, 0x180), (0x3000, 0x80), (0x5000, 0x40)]; - let mut retry = Vec::new(); - visit_unsubmitted_dirty(&runs, 0, 0x100, |a, n| retry.push((a, n))); - assert_eq!(retry, [(0x1100, 0x80), (0x3000, 0x80), (0x5000, 0x40)]); - - retry.clear(); - visit_unsubmitted_dirty(&runs, 1, 0x80, |a, n| retry.push((a, n))); - assert_eq!(retry, [(0x5000, 0x40)], "a fully submitted run is not made stale again"); - } - #[test] fn quarantine_uses_installed_retirement_marks_and_fails_closed_without_one() { use std::sync::Arc; @@ -2574,6 +2629,7 @@ mod tests { ring_submitted: 0, ring_free: 0, inflight: VecDeque::new(), + uploads_ordered: true, zero_buf: None, slots: Vec::new(), next_slot: 0, @@ -2700,30 +2756,75 @@ mod tests { assert_eq!(changed_chunks(&page, slot.as_deref_mut().unwrap()), vec![(CHUNK, CHUNK)]); } - /// `scan_page` skips allocating a hash box on all-zero pages, allocates on the first write, - /// and coalesces adjacent dirty chunks across consecutive pages. + /// `scan_page` leaves published hashes unchanged, skips allocation for zero pages, and + /// coalesces adjacent dirty chunks. #[test] - fn scan_page_lazy_alloc_and_coalesce() { + fn scan_page_plans_without_publishing_and_coalesces() { let mut page = vec![0u8; PAGE]; - let mut slot: Option<Box<[u64; CHUNKS]>> = None; + let slot: Option<Box<[u64; CHUNKS]>> = None; let mut out = Vec::new(); - scan_page(&page, 0x1_0000, &mut slot, &mut out); + scan_page(&page, 0x1_0000, &slot, &mut out); assert!(slot.is_none(), "all-zero page must not allocate hash box"); assert!(out.is_empty()); page[PAGE - 64] = 0xAA; - scan_page(&page, 0x1_0000, &mut slot, &mut out); - assert!(slot.is_some()); + scan_page(&page, 0x1_0000, &slot, &mut out); + assert!(slot.is_none(), "planning must not publish a last-sent hash"); assert_eq!(out, vec![(0x1_0FC0, 64)]); // Adjacent chunk at the start of the next page coalesces into a single run. let mut next = vec![0u8; PAGE]; next[0] = 0xBB; - let mut next_slot: Option<Box<[u64; CHUNKS]>> = None; - scan_page(&next, 0x1_1000, &mut next_slot, &mut out); + let next_slot: Option<Box<[u64; CHUNKS]>> = None; + scan_page(&next, 0x1_1000, &next_slot, &mut out); assert_eq!(out, vec![(0x1_0FC0, 128)]); } + #[test] + fn hash_plan_is_published_only_when_applied() { + let base = 0x2_0000; + let mut mapped = FxHashMap::default(); + mapped.insert(base, TileEntry::with_holes((0, 0), 0)); + let mut prefix = Vec::new(); + append_hash_updates(base + CHUNK, &[1; CHUNK], &mut prefix); + let mut suffix = Vec::new(); + append_hash_updates(base + PAGE + 2 * CHUNK, &[2; CHUNK], &mut suffix); + assert!(mapped[&base].sent[0].is_none()); + assert!(mapped[&base].sent[1].is_none()); + publish_hash_updates(&mut mapped, &prefix); + assert_eq!(mapped[&base].sent[0].as_ref().unwrap()[1], chunk_hash(&[1; CHUNK])); + assert!(mapped[&base].sent[1].is_none(), "an unacknowledged suffix was published"); + publish_hash_updates(&mut mapped, &suffix); + assert_eq!(mapped[&base].sent[1].as_ref().unwrap()[2], chunk_hash(&[2; CHUNK])); + } + + #[test] + fn cpu_write_after_planning_is_dirty_after_receipt_publication() { + let base = 0x3_0000; + let mut mapped = FxHashMap::default(); + mapped.insert(base, TileEntry::with_holes((0, 0), 0)); + let mut page = vec![0u8; PAGE]; + page[0] = 1; + let staged = page[..CHUNK].to_vec(); + let mut planned = Vec::new(); + append_hash_updates(base, &staged, &mut planned); + page[0] = 2; + publish_hash_updates(&mut mapped, &planned); + + let mut runs = Vec::new(); + scan_page(&page, base, &mapped[&base].sent[0], &mut runs); + assert_eq!(runs, [(base, CHUNK)]); + } + + #[test] + fn batch_hash_plan_is_bounded_by_staging() { + assert_eq!(MAX_BATCH_HASH_UPDATES, STAGING / CHUNK); + assert_eq!(MAX_BATCH_HASH_UPDATES * std::mem::size_of::<HashUpdate>(), STAGING / 4); + assert!(!batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES - 1, CHUNK)); + assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES, CHUNK)); + assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES / 2 + 1, STAGING / 2)); + } + /// Ring-buffer planner keeps every chunk contiguous, 64-byte aligned, <= cap/2, and splits /// cleanly across the end of the ring buffer without wrapping mid-copy. #[test] @@ -2847,6 +2948,7 @@ mod tests { ring_submitted: 0, ring_free: 0, inflight: VecDeque::new(), + uploads_ordered: true, zero_buf: None, slots: Vec::new(), next_slot: 0, @@ -2882,7 +2984,7 @@ mod tests { *(base as *mut u8) = 0x5A; let mut dirty = Vec::new(); let page0 = std::slice::from_raw_parts(base as *const u8, PAGE); - scan_page(page0, base, &mut entry.sent[0], &mut dirty); + scan_page(page0, base, &entry.sent[0], &mut dirty); assert_eq!(dirty, vec![(base, CHUNK)]); s.wait_for(s.value); @@ -2947,6 +3049,7 @@ mod tests { ring_submitted: 0, ring_free: 0, inflight: VecDeque::new(), + uploads_ordered: true, zero_buf: None, slots: Vec::new(), next_slot: 0, @@ -3083,6 +3186,7 @@ mod tests { ring_submitted: 0, ring_free: 0, inflight: VecDeque::new(), + uploads_ordered: true, zero_buf: None, slots: Vec::new(), next_slot: 0, @@ -3098,7 +3202,7 @@ mod tests { } #[test] - fn a_stalled_upload_ring_returns_and_retries_exact_chunks() { + fn a_stalled_upload_ring_returns_without_publishing_hashes() { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; unsafe { @@ -3121,10 +3225,7 @@ mod tests { assert!(!s.upload_dirty_with_timeout(&[(base + CHUNK, 2 * CHUNK)], 20)); assert!(started.elapsed() < std::time::Duration::from_secs(2), "a stalled fence kept upload_dirty in its ring loop"); let after = s.mapped[&base].sent[0].as_ref().unwrap(); - assert_eq!(after[0], before[0], "an already submitted chunk was made dirty again"); - assert_ne!(after[1], before[1]); - assert_ne!(after[2], before[2]); - assert_eq!(after[3], before[3]); + assert_eq!(after.as_ref(), &before, "a failed upload changed the published hash state"); let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); From 729dac6f6370758acd13712fc4fd7c0c34b3a78e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:36:34 -0800 Subject: [PATCH 201/265] D3D12.X: own immutable native pipeline generations Retained rebuild recipes now publish a monotonic native generation with one strong pipeline owner before the raw result becomes visible. A future recording path can resolve and pin that exact generation under the same lock used by completion and release, without a raw-pointer AddRef race. The ordinary one-shot path keeps its existing allocation and AddRef behavior. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 153 +++++++++++++++++++++++-- 1 file changed, 146 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index d4d5411157..a8e4a52cc2 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -11,6 +11,9 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock, Weak}; +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::ID3D12PipelineState; + use super::build_queue::{BuildQueue, JobHandle, Priority}; const QUEUE_IDLE: u8 = 0; @@ -455,18 +458,25 @@ fn complete(build: &Arc<Build>, real: usize) { BUILT.fetch_add(1, Ordering::Relaxed); build.completed_frame.store(super::present::presents(), Ordering::Relaxed); } - let orphan = { + let (orphan, replaced_generation) = { let mut done = build.done.lock().unwrap(); let orphan = build.orphan.load(Ordering::Acquire); + let mut replaced_generation = None; if !orphan { + if real != 0 { + if let Some(recipe) = &build.recipe { + replaced_generation = recipe.publish(real); + } + } build.real.store(real, Ordering::Release); } *done = true; build.finish_queued(); build.cv.notify_all(); - orphan + (orphan, replaced_generation) }; - // outside `done`: the Release override can re-enter pipeline bookkeeping + // outside `done`: a pipeline Release override can re-enter pipeline bookkeeping + drop(replaced_generation); if orphan { release(real); } @@ -619,18 +629,76 @@ pub(super) fn rebuild_recipes_enabled() -> bool { /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box<dyn FnOnce() -> usize + Send>; +struct Generation<T> { + id: u64, + raw: usize, + _owner: T, +} + +struct GenerationSlot<T> { + next: u64, + resident: Option<Arc<Generation<T>>>, +} + +impl<T> Default for GenerationSlot<T> { + fn default() -> Self { Self { next: 0, resident: None } } +} + +impl<T> GenerationSlot<T> { + fn publish(&mut self, raw: usize, owner: T) -> (Arc<Generation<T>>, Option<Arc<Generation<T>>>) { + self.next = self.next.checked_add(1).expect("pipeline generation id exhausted"); + let generation = Arc::new(Generation { id: self.next, raw, _owner: owner }); + let replaced = self.resident.replace(generation.clone()); + (generation, replaced) + } + + fn pin(&self, raw: usize) -> Option<Arc<Generation<T>>> { + self.resident.as_ref().filter(|generation| generation.raw == raw).cloned() + } +} + +struct RecipeInner { + build: Box<dyn Fn() -> usize + Send + Sync>, + generation: Mutex<GenerationSlot<ID3D12PipelineState>>, +} + +/// One immutable native pipeline generation. Its strong owner keeps the exact object alive even +/// after the title releases its stand-in or a later rebuild publishes the same raw address. +#[derive(Clone)] +#[allow(dead_code)] // recorded-list generation pins are the next opt-in stage +pub(super) struct NativeGeneration(Arc<Generation<ID3D12PipelineState>>); + +#[allow(dead_code)] // recorded-list generation pins are the next opt-in stage +impl NativeGeneration { + pub(super) fn id(&self) -> u64 { self.0.id } + pub(super) fn raw(&self) -> usize { self.0.raw } +} + /// Rebuildable immutable inputs for one pipeline. The first build and any later rebuild use the -/// same operation; retaining it does not by itself schedule or run more work. +/// same operation; retaining it does not by itself schedule or run more work. Its existing opt-in +/// allocation also owns the native generation, so ordinary one-shot builds allocate no new state. #[derive(Clone)] -pub(super) struct Recipe(Arc<dyn Fn() -> usize + Send + Sync>); +pub(super) struct Recipe(Arc<RecipeInner>); impl Recipe { pub(super) fn new(build: impl Fn() -> usize + Send + Sync + 'static) -> Self { - Self(Arc::new(build)) + Self(Arc::new(RecipeInner { build: Box::new(build), generation: Mutex::new(GenerationSlot::default()) })) } fn run(&self) -> usize { - (self.0)() + (self.0.build)() + } + + /// Publish before `Build.real` becomes visible. The returned generation owns one independent + /// COM reference; the raw result remains the existing `Build.real` owner. + fn publish(&self, raw: usize) -> Option<NativeGeneration> { + let p = raw as *mut std::ffi::c_void; + let owner = unsafe { ID3D12PipelineState::from_raw_borrowed(&p) }.expect("non-null pipeline result").clone(); + self.0.generation.lock().unwrap().publish(raw, owner).1.map(NativeGeneration) + } + + fn pin(&self, raw: usize) -> Option<NativeGeneration> { + self.0.generation.lock().unwrap().pin(raw).map(NativeGeneration) } fn initial_job(&self) -> Job { @@ -1167,6 +1235,51 @@ mod used_tests { assert_eq!(calls.load(Ordering::Relaxed), 2); } + #[test] + fn native_generation_slot_pins_exact_aba_owner_and_ids_publications() { + struct Owner(Arc<AtomicUsize>); + impl Drop for Owner { + fn drop(&mut self) { self.0.fetch_add(1, Ordering::Relaxed); } + } + + let drops = Arc::new(AtomicUsize::new(0)); + let mut slot = GenerationSlot::default(); + let (first, replaced) = slot.publish(0x7E57_ABA0, Owner(drops.clone())); + assert!(replaced.is_none()); + let pinned = slot.pin(0x7E57_ABA0).unwrap(); + assert_eq!(first.id, 1); + let (second, replaced) = slot.publish(0x7E57_ABA0, Owner(drops.clone())); + assert_eq!(second.id, 2); + assert!(!Arc::ptr_eq(&pinned, &second), "a reused raw address aliased its older generation"); + drop(first); + drop(replaced); + assert_eq!(drops.load(Ordering::Relaxed), 0, "the old generation died while a pin held it"); + drop(pinned); + assert_eq!(drops.load(Ordering::Relaxed), 1); + drop(second); + drop(slot); + assert_eq!(drops.load(Ordering::Relaxed), 2); + } + + #[test] + fn concurrent_generation_publications_are_monotonic() { + let slot = Arc::new(Mutex::new(GenerationSlot::default())); + std::thread::scope(|scope| { + for thread in 0..4usize { + let slot = slot.clone(); + scope.spawn(move || { + for k in 0..100usize { + let (_, replaced) = slot.lock().unwrap().publish(thread * 100 + k + 1, ()); + drop(replaced); + } + }); + } + }); + let slot = slot.lock().unwrap(); + assert_eq!(slot.next, 400); + assert_eq!(slot.resident.as_ref().unwrap().id, 400); + } + #[test] fn a_panicking_pipeline_job_completes_failed_and_wakes_its_waiter() { let build = Arc::new(Build::new(Box::new(|| panic!("simulated pipeline panic")), false)); @@ -2381,6 +2494,32 @@ pub fn resolve_for_bind(pso: usize) -> usize { } } +/// Resolve and strongly pin the exact recipe-backed native generation as one operation. The +/// generation is chosen while holding `Build.done`, the same lock that publishes it and that +/// `released` uses before giving up the original raw owner. Ordinary one-shot builds keep their +/// existing resolution path and return no generation pin. +#[allow(dead_code)] // command-list generation capture is the next opt-in stage +pub(super) fn resolve_and_pin_for_bind(pso: usize) -> (usize, Option<NativeGeneration>) { + let Some(p) = entry(pso) else { return (pso, None) }; + let Some(recipe) = p.build.recipe.as_ref() else { return (resolve_for_bind(pso), None) }; + p.note_use(); + if p.compute { + let _ = resolve_wait_pending(&p, pso, wait_budget()); + } else if p.build.real.load(Ordering::Acquire) == 0 { + schedule(&p.build, Priority::BoundSoon, false, None); + p.build.promote(Priority::Foreground); + } + let _done = p.build.done.lock().unwrap(); + let real = p.build.real.load(Ordering::Acquire); + if real == 0 { + return (p.stand(pso), None); + } + match recipe.pin(real) { + Some(generation) => (generation.raw(), Some(generation)), + None => (p.stand(pso), None), + } +} + /// The title released stand-in `pso` for good: forget it (its address may come back for /// another object) and return its real pipeline to release when this is its last owner /// (0: another `Pending` owns the build, none, or still being built – the worker's result is From 3cd053e4250b0f054548e8d6c3c6274aeaa279b3 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:38:52 -0800 Subject: [PATCH 202/265] D3D12.X: fail title submits closed on sparse upload loss Write-watch bits are reset before sparse uploads have a durable ordering receipt. Preserve failed pages in the sparse state, retry preparation against the same dirty snapshot, and roll back failed title-queue waits. A void title submission can only proceed after preparation is ready; an untracked or repeatedly failed upload stops the title instead of silently running stale GPU work. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 2 +- crates/xcl/src/hle/d3d12x/real.rs | 23 ++- crates/xcl/src/hle/d3d12x/sparse.rs | 207 +++++++++++++++----- crates/xcl/src/hle/d3d12x/title_textures.rs | 34 +++- 4 files changed, 203 insertions(+), 63 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 8d3ce69137..9b6708ec67 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4156,7 +4156,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } let q_raw = queue_pin.as_raw(); - super::title_textures::refresh(q_raw); + real::prepare_title_submission(q_raw); type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 0ebbda85b6..bf1de79daf 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9039,7 +9039,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis let _in_pc = super::pso_async::pc_call(); let mut preparation_stall = crate::stall::span(crate::stall::StallKind::SubmitPreparation); // textures in title memory the CPU wrote since: uploaded again first - super::title_textures::refresh(this); + prepare_title_submission(this); // console-shaped lists run as the PC lists they were translated into (split title lists expand // into all of their recorded PC segments in exact chronological order) let mut mapped: Vec<*mut c_void> = Vec::with_capacity(n as usize); @@ -9086,6 +9086,27 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis stop_if_device_removed(); } +/// Complete correctness-critical uploads before any native title list executes. The D3D12 +/// submission API is void, so returning after preparation failure would silently lose the +/// title's exact submission; an unorderable failure must end the title instead. +pub(super) unsafe fn prepare_title_submission(queue: *mut c_void) { + use super::sparse::PreparationOutcome; + let outcome = super::title_textures::refresh(queue); + if outcome == PreparationOutcome::Ready { + return; + } + stop_if_device_removed(); + let reason = match outcome { + PreparationOutcome::RetryRequired => "sparse upload preparation still failed after bounded retries", + PreparationOutcome::ExecutedUntracked => "a sparse upload executed without a retirement signal", + PreparationOutcome::Ready => unreachable!(), + }; + let message = format!("{reason} – the title is stopped before its GPU submission"); + crate::xlog_error!("{message}"); + crate::report::write_final(Some(message)); + end_title(0x8000_4005); +} + /// Wait (up to 10 s) until the GPU has finished the work submitted to the queues console code /// used (before the process ends on purpose). pub fn drain_gpu() { diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 61358b4f76..ae89913cdb 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -209,6 +209,23 @@ enum SubmitResult { Unordered, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum PreparationOutcome { + Ready, + RetryRequired, + ExecutedUntracked, +} + +impl From<SubmitResult> for PreparationOutcome { + fn from(result: SubmitResult) -> Self { + match result { + SubmitResult::Submitted => Self::Ready, + SubmitResult::NotSubmitted => Self::RetryRequired, + SubmitResult::Unordered => Self::ExecutedUntracked, + } + } +} + struct RetiredTiles { tiles: Vec<(u32, u32)>, /// Fence marks on `self.queue` and every known title queue (`None` = signal failed, keep held). @@ -280,6 +297,8 @@ struct State { runs: Option<Vec<(usize, usize)>>, /// reusable buffer for dirty runs in `before_execute` (avoids per-submit heap alloc) scratch_runs: Vec<(usize, usize)>, + /// Dirty CPU pages whose write-watch bits were reset before an upload failed. + retry_pages: Vec<usize>, } impl Drop for State { @@ -737,6 +756,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }) })(); match made { @@ -1290,14 +1310,17 @@ impl State { /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` /// (zero staging ring bytes consumed, zero CPU stall). - unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) -> bool { + unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) -> PreparationOutcome { if runs.is_empty() { - return true; + return PreparationOutcome::Ready; } - if !self.uploads_ordered || !self.ensure_zero_buf() { - return false; + if !self.uploads_ordered { + return PreparationOutcome::ExecutedUntracked; } - let Some(slot_idx) = self.begin_slot() else { return false }; + if !self.ensure_zero_buf() { + return PreparationOutcome::RetryRequired; + } + let Some(slot_idx) = self.begin_slot() else { return PreparationOutcome::RetryRequired }; let mut last_wi: Option<usize> = None; let zero_buf = self.zero_buf.as_ref().unwrap(); let list = &self.slots[slot_idx].list; @@ -1322,24 +1345,24 @@ impl State { done += chunk; } } - self.submit_slot(slot_idx) == SubmitResult::Submitted + self.submit_slot(slot_idx).into() } /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via /// the 64 MiB ring staging buffer (zero CPU stall on the common path). - unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) -> bool { + unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) -> PreparationOutcome { self.upload_dirty_with_timeout(runs, 5000) } - unsafe fn upload_dirty_with_timeout(&mut self, runs: &[(usize, usize)], wait_ms: u32) -> bool { + unsafe fn upload_dirty_with_timeout(&mut self, runs: &[(usize, usize)], wait_ms: u32) -> PreparationOutcome { if runs.is_empty() { - return true; + return PreparationOutcome::Ready; } if !self.uploads_ordered { - return false; + return PreparationOutcome::ExecutedUntracked; } let Some(p) = self.staging_ptr() else { - return false; + return PreparationOutcome::RetryRequired; }; let mut open_slot: Option<usize> = None; let mut batch_start = self.ring_write; @@ -1360,7 +1383,7 @@ impl State { if open_slot.is_some() { self.ring_write = batch_start; } - return false; + return PreparationOutcome::RetryRequired; } }, }; @@ -1378,16 +1401,16 @@ impl State { } SubmitResult::NotSubmitted => { self.ring_write = batch_start; - return false; + return PreparationOutcome::RetryRequired; } - SubmitResult::Unordered => return false, + SubmitResult::Unordered => return PreparationOutcome::ExecutedUntracked, } self.reclaim_ring(); } while (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { let Some(&(fv, _)) = self.inflight.front() else { crate::xlog_warn!("sparse: the staging ring is full without a retirement fence; the unsubmitted CPU writes will be retried"); - return false; + return PreparationOutcome::RetryRequired; }; let reached = self.wait_for_ms(fv, wait_ms); self.reclaim_ring(); @@ -1397,7 +1420,7 @@ impl State { if stalls <= 4 || stalls.is_power_of_two() { crate::xlog_warn!("sparse: staging ring reclaim timed out at fence {fv}; the unsubmitted CPU writes will be retried ({stalls} stalls)"); } - return false; + return PreparationOutcome::RetryRequired; } } } @@ -1412,16 +1435,16 @@ impl State { } SubmitResult::NotSubmitted => { self.ring_write = batch_start; - return false; + return PreparationOutcome::RetryRequired; } - SubmitResult::Unordered => return false, + SubmitResult::Unordered => return PreparationOutcome::ExecutedUntracked, } } let slot_idx = match open_slot { Some(idx) => idx, None => { let Some(idx) = self.begin_slot() else { - return false; + return PreparationOutcome::RetryRequired; }; batch_start = self.ring_write; open_slot = Some(idx); @@ -1442,12 +1465,12 @@ impl State { SubmitResult::Submitted => self.publish_hashes(&batch_updates), SubmitResult::NotSubmitted => { self.ring_write = batch_start; - return false; + return PreparationOutcome::RetryRequired; } - SubmitResult::Unordered => return false, + SubmitResult::Unordered => return PreparationOutcome::ExecutedUntracked, } } - true + PreparationOutcome::Ready } } @@ -1549,7 +1572,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { for &(a, n) in &zeroed { s.clear_sent_range(a, n); } - if !s.upload_zeros(&zeroed) { + if s.upload_zeros(&zeroed) != PreparationOutcome::Ready { s.to_zero.extend(zeroed); return; } @@ -1575,7 +1598,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { pg = tile_end; } if !dirty_runs.is_empty() { - if !s.upload_dirty(&dirty_runs) { + if s.upload_dirty(&dirty_runs) != PreparationOutcome::Ready { return; } } @@ -2066,6 +2089,32 @@ fn reserve_queue_wait(waited: &mut FxHashMap<usize, u64>, queue: usize, value: u true } +fn retry_journal(outcome: PreparationOutcome, mut deferred: Vec<usize>, runs: &[(usize, usize)]) -> Vec<usize> { + if outcome != PreparationOutcome::Ready { + for &(a, n) in runs { + let mut pg = a & !(PAGE - 1); + let end = a.saturating_add(n); + while pg < end { + deferred.push(pg); + pg += PAGE; + } + } + } + deferred.sort_unstable(); + deferred.dedup(); + deferred +} + +fn rollback_queue_wait(waited: &mut FxHashMap<usize, u64>, queue: usize, value: u64, previous: Option<u64>) { + if waited.get(&queue) != Some(&value) { + return; + } + match previous { + Some(previous) => { waited.insert(queue, previous); } + None => { waited.remove(&queue); } + } +} + /// Snapshot strong fence owners under `STATE`, then query them without it. A batch or a higher /// mark added while polling is checked against the same observation; a new fence has no /// observation and therefore remains quarantined. @@ -2083,7 +2132,7 @@ unsafe fn poll_retirement_fences() -> Vec<(ID3D12Fence, u64)> { /// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB /// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video /// memory, and `queue` GPU-waits for that and for new tile mappings. -pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize, mut look: Option<&mut LookSample>) { +pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize, mut look: Option<&mut LookSample>) -> PreparationOutcome { let q = queue.as_raw() as usize; let t0 = look.is_some().then(std::time::Instant::now); let queue_gate = WAIT_GATES.lock().unwrap().entry(q).or_default().clone(); @@ -2096,7 +2145,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], sample.add_time(QUEUE_WAIT_US, t_gated.duration_since(t0)); sample.add_time(MAINTENANCE_US, t_gated.elapsed()); } - return; + return PreparationOutcome::Ready; }; // the title's work sees what was decommitted unmapped, as it was let flushed = s.flush_parked_with(Some(queue)); @@ -2114,44 +2163,65 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], } let mut dirty_runs = std::mem::take(&mut s.scratch_runs); dirty_runs.clear(); - let mut i = 0; - while i < dirty.len() { - let a = dirty[i]; - let mut n = page; - i += 1; - while i < dirty.len() && dirty[i] == a + n { - n += page; + let mut deferred = Vec::new(); + let retry_pages = std::mem::take(&mut s.retry_pages); + if retry_pages.is_empty() { + let mut i = 0; + while i < dirty.len() { + let a = dirty[i]; + let mut n = page; i += 1; - } - // only what has video memory (committed tiles of a sparse window) - let mut x = a; - while x < a + n { - let t = x & !(TILE - 1); - let end = (t + TILE).min(a + n); - if let Some(entry) = s.mapped.get_mut(&t) { - let mut pg = x & !(PAGE - 1); - while pg < end { + while i < dirty.len() && dirty[i] == a + n { + n += page; + i += 1; + } + let mut pg = a & !(PAGE - 1); + while pg < a + n { + let t = pg & !(TILE - 1); + if let Some(entry) = s.mapped.get_mut(&t) { let idx = (pg - t) / PAGE; if entry.holes & (1u16 << idx) == 0 { let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); scan_page(bytes, pg, &entry.sent[idx], &mut dirty_runs); } - pg += PAGE; } + pg += PAGE; + } + } + } else { + let mut pages = retry_pages; + let prior = pages.clone(); + pages.extend(dirty.iter().flat_map(|&a| (a..a.saturating_add(page)).step_by(PAGE))); + pages.sort_unstable(); + pages.dedup(); + for pg in pages { + let t = pg & !(TILE - 1); + let Some(entry) = s.mapped.get_mut(&t) else { + if prior.binary_search(&pg).is_ok() { deferred.push(pg) } + continue; + }; + let idx = (pg - t) / PAGE; + if entry.holes & (1u16 << idx) != 0 { + if prior.binary_search(&pg).is_ok() { deferred.push(pg) } + continue; } - x = end; + let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); + scan_page(bytes, pg, &entry.sent[idx], &mut dirty_runs); } } let t_scanned = t0.map(|_| std::time::Instant::now()); // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. + let mut outcome = PreparationOutcome::Ready; if !zero_runs.is_empty() { - if !s.upload_zeros(&zero_runs) { + outcome = s.upload_zeros(&zero_runs); + if outcome != PreparationOutcome::Ready { s.to_zero.extend(zero_runs.iter().copied()); } } - if !dirty_runs.is_empty() { - let _ = s.upload_dirty(&dirty_runs); + if outcome == PreparationOutcome::Ready && !dirty_runs.is_empty() { + outcome = s.upload_dirty(&dirty_runs); } + s.retry_pages = retry_journal(outcome, deferred, &dirty_runs); if let (Some(sample), Some(t0), Some(t_gated), Some(t_maintained), Some(t_scanned)) = (look.as_deref_mut(), t0, t_gated, t_maintained, t_scanned) { @@ -2166,14 +2236,27 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], } dirty_runs.clear(); s.scratch_runs = dirty_runs; + if outcome != PreparationOutcome::Ready { + drop(g); + drop(observed); + return outcome; + } let value = s.value; - let wait = reserve_queue_wait(&mut s.waited, q, value).then(|| (s.fence.clone(), value)); + let previous = s.waited.get(&q).copied(); + let wait = reserve_queue_wait(&mut s.waited, q, value).then(|| (s.fence.clone(), value, previous)); drop(g); drop(observed); - if let Some((fence, value)) = wait { - let _ = super::real::native_queue_wait(queue, &fence, value); + if let Some((fence, value, previous)) = wait { + if super::real::native_queue_wait(queue, &fence, value).is_err() { + let mut g = lock_state(); + if let Some(s) = g.as_mut().filter(|s| s.fence.as_raw() == fence.as_raw() && s.waited.get(&q) == Some(&value)) { + rollback_queue_wait(&mut s.waited, q, value, previous); + } + return PreparationOutcome::RetryRequired; + } super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &fence, value); } + PreparationOutcome::Ready } /// A buffer the title places at `va` in a sparse window (`bytes` long, `desc` the PC @@ -2511,6 +2594,24 @@ mod tests { assert_eq!(waited, FxHashMap::from_iter([(1, 5), (2, 3)])); } + #[test] + fn failed_write_watch_pages_survive_until_a_ready_retry() { + let runs = [(0x1040, PAGE), (0x2000, CHUNK)]; + assert_eq!(retry_journal(PreparationOutcome::RetryRequired, vec![], &runs), [0x1000, 0x2000]); + assert!(retry_journal(PreparationOutcome::Ready, vec![], &runs).is_empty()); + assert_eq!(retry_journal(PreparationOutcome::ExecutedUntracked, vec![0x3000], &runs), [0x1000, 0x2000, 0x3000]); + } + + #[test] + fn a_failed_title_queue_wait_rolls_back_only_its_reservation() { + let mut waited = FxHashMap::from_iter([(1, 4), (2, 7)]); + assert!(reserve_queue_wait(&mut waited, 1, 5)); + rollback_queue_wait(&mut waited, 1, 5, Some(4)); + assert_eq!(waited, FxHashMap::from_iter([(1, 4), (2, 7)])); + rollback_queue_wait(&mut waited, 1, 9, None); + assert_eq!(waited.get(&1), Some(&4), "a stale failure changed a newer reservation"); + } + #[test] fn quarantine_uses_installed_retirement_marks_and_fails_closed_without_one() { use std::sync::Arc; @@ -2640,6 +2741,7 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; let (first, reused) = s.take_tile().expect("a tile from a new pool"); @@ -2959,6 +3061,7 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; // Mirrors `place_buffer`: map both tiles probing real OS page commitment. @@ -3060,6 +3163,7 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; s.commit_range(base, TILE); @@ -3197,6 +3301,7 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; (base, s) } @@ -3222,7 +3327,7 @@ mod tests { s.ring_free = 0; s.inflight.push_back((s.value + 1, STAGING as u64)); let started = std::time::Instant::now(); - assert!(!s.upload_dirty_with_timeout(&[(base + CHUNK, 2 * CHUNK)], 20)); + assert_eq!(s.upload_dirty_with_timeout(&[(base + CHUNK, 2 * CHUNK)], 20), PreparationOutcome::RetryRequired); assert!(started.elapsed() < std::time::Duration::from_secs(2), "a stalled fence kept upload_dirty in its ring loop"); let after = s.mapped[&base].sent[0].as_ref().unwrap(); assert_eq!(after.as_ref(), &before, "a failed upload changed the published hash state"); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 7cfb4e1a29..d521acf720 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -874,20 +874,21 @@ pub(super) fn is_own_work() -> bool { /// Before the title's GPU work: textures whose memory the CPU wrote since the last look are /// uploaded again. -pub(super) unsafe fn refresh(queue: *mut c_void) { +pub(super) unsafe fn refresh(queue: *mut c_void) -> super::sparse::PreparationOutcome { // the uploads' own ExecuteCommandLists come back here if BUSY.with(|b| b.get()) { - return; + return super::sparse::PreparationOutcome::Ready; } let measure = super::memory_report::enabled(); let wait_t0 = measure.then(std::time::Instant::now); let _refresh = REFRESH.lock().unwrap(); let active_t0 = measure.then(std::time::Instant::now); let mut look = measure.then(super::sparse::LookSample::default); - own_work(|| refresh_once(queue, look.as_mut())); + let outcome = own_work(|| refresh_once(queue, look.as_mut())); if let (Some(wait_t0), Some(active_t0), Some(look)) = (wait_t0, active_t0, look) { super::sparse::note_look(look, active_t0.elapsed(), active_t0.duration_since(wait_t0)); } + outcome } /// The pages of `[base, base + size)` written since the last look, added to `dirty` and reset @@ -910,11 +911,11 @@ unsafe fn take_written(base: usize, size: usize, buf: &mut [*mut c_void], dirty: } } -unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse::LookSample>) { - let Some(u) = crate::gpu::uma::get() else { return }; +unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse::LookSample>) -> super::sparse::PreparationOutcome { + let Some(u) = crate::gpu::uma::get() else { return super::sparse::PreparationOutcome::Ready }; let sparse = u.has_sparse(); if !sparse && CPU_TEXTURES_LEN.load(Ordering::Relaxed) == 0 { - return; + return super::sparse::PreparationOutcome::Ready; } recheck_gpu_view_sources(); let mut page = 0x1000u32; @@ -975,11 +976,23 @@ unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse:: } // the title's own memory: what the CPU wrote goes to its video memory first if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { - DIRTY_BUF.with(|dcell| { + let outcome = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); - super::sparse::before_execute(q, &dirty, page as usize, look.as_deref_mut()); - super::vram::before_execute(q); + let mut outcome = super::sparse::PreparationOutcome::RetryRequired; + for _ in 0..3 { + outcome = super::sparse::before_execute(q, &dirty, page as usize, look.as_deref_mut()); + if outcome != super::sparse::PreparationOutcome::RetryRequired { + break; + } + super::real::stop_if_device_removed(); + std::thread::yield_now(); + } + outcome }); + if outcome != super::sparse::PreparationOutcome::Ready { + return outcome; + } + super::vram::before_execute(q); } let recheck_frame = { let (p, b) = super::present::counters(); @@ -987,7 +1000,7 @@ unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse:: }; recheck_streamed_unwatched(&ranges, recheck_frame); if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 { - return; + return super::sparse::PreparationOutcome::Ready; } // textures made since the last submit and those with a written page; a reference each // while they are uploaded @@ -1022,6 +1035,7 @@ unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse:: }); seed_stream_recheck(&todo, &ranges, recheck_frame); upload_all(todo, ID3D12CommandQueue::from_raw_borrowed(&queue)); + super::sparse::PreparationOutcome::Ready } /// texture → `content_hash` of its memory at its last upload From d7e64381ea7373ef9054c3ed28e8954e57ab0f9c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:37:45 -0800 Subject: [PATCH 203/265] D3D12.X: capture shared descriptor heap use Record shared view-heap use on each physical command-list segment after translated ABI binding succeeds. Preserve bundle use in the parent recording and carry immutable use through submission planning without changing default behavior. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 5 +- crates/xcl/src/hle/d3d12x/console_list.rs | 21 ++- crates/xcl/src/hle/d3d12x/list_x.rs | 153 ++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 2 + crates/xcl/src/hle/d3d12x/vram.rs | 1 + 5 files changed, 169 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 80569779f8..e6718c62da 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1187,7 +1187,7 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi unsafe fn bind_abi_with_root( this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, root: usize, ) -> Result<(), String> { - super::list_x::ensure_view_heap(this); + let shared_view_bound = super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; @@ -1242,6 +1242,9 @@ unsafe fn bind_abi_with_root( let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; list.SetPipelineState(pc); } + if shared_view_bound && super::vram::srv_tracking_enabled() { + super::list_x::note_shared_view_heap_use(this); + } Ok(()) } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index c675e58e97..3878989669 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -714,8 +714,10 @@ unsafe fn ensure_dispatch_heaps_with(list: &ID3D12GraphicsCommandList, bound: &m true } -unsafe fn ensure_dispatch_heaps(list: &ID3D12GraphicsCommandList, bound: &mut Vec<ID3D12DescriptorHeap>, has_sampler: &mut bool) { - if bound.len() >= 2 { return; } +unsafe fn ensure_dispatch_heaps( + list: &ID3D12GraphicsCommandList, bound: &mut Vec<ID3D12DescriptorHeap>, has_sampler: &mut bool, shared_view_bound: bool, +) -> bool { + if bound.len() >= 2 { return shared_view_bound; } let mut dev: Option<ID3D12Device> = None; let _ = list.GetDevice(&mut dev); let sampler = super::console_heap::global_sampler_heap().or_else(|| { @@ -727,7 +729,9 @@ unsafe fn ensure_dispatch_heaps(list: &ID3D12GraphicsCommandList, bound: &mut Ve Some(dev_raw) => (heap_on_device(view, dev_raw), heap_on_device(sampler, dev_raw)), None => (view, sampler), }; + let view_raw = view.as_ref().map(|h| h.as_raw() as usize); ensure_dispatch_heaps_with(list, bound, has_sampler, view, sampler); + shared_view_bound || view_raw.is_some_and(|view| bound.iter().any(|heap| heap.as_raw() as usize == view)) } /// Turn the recorded console commands into commands on the PC list and close it. @@ -759,6 +763,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> { // tracked PC descriptor heaps bound on `list` (for `heap_windows` + `SAMPLER_HEAP_DIRECTLY_INDEXED`) let mut bound_heaps: Vec<ID3D12DescriptorHeap> = Vec::new(); let mut has_sampler_heap = false; + let track_shared_view = super::vram::srv_tracking_enabled(); + let mut shared_view_bound = false; + let mut recording_uses_shared_view = false; let chunks: Vec<Vec<u32>> = st.chunks.iter().map(|(c, used)| c[..*used].chunks(4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).collect()).collect(); 'chunks: for words in &chunks { let mut at = 0usize; @@ -786,11 +793,13 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> { list.SetDescriptorHeaps(&[]); bound_heaps.clear(); has_sampler_heap = false; + shared_view_bound = false; } else { - let heaps = super::list_x::pc_heaps(n as u32, named.as_ptr()); + let (heaps, uses_shared_view) = super::list_x::pc_heaps_with_shared(n as u32, named.as_ptr()); list.SetDescriptorHeaps(&heaps); bound_heaps = heaps.into_iter().flatten().collect(); has_sampler_heap = bound_heaps.iter().any(|h| h.GetDesc().Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + shared_view_bound = uses_shared_view; } at += 2 + 2 * n; } else if w0 == TRANSITIONS_MARKER { @@ -903,7 +912,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> { Some(r) => list.SetComputeRootSignature(r), None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?), } - ensure_dispatch_heaps(&list, &mut bound_heaps, &mut has_sampler_heap); + shared_view_bound = ensure_dispatch_heaps(&list, &mut bound_heaps, &mut has_sampler_heap, shared_view_bound); list.SetComputeRootUnorderedAccessView(0, va(io_at)); list.SetComputeRootUnorderedAccessView(1, va(res_at)); for k in 0..4 { @@ -913,6 +922,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> { let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?; list.SetPipelineState(pc); super::real::dispatch_chain::dispatch(&list, real, st.allocator, [x, y, z])?; + recording_uses_shared_view |= track_shared_view && shared_view_bound; out.dispatches += 1; } _ => out.skipped_dispatches += 1, @@ -958,6 +968,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> { } } drop(guard); + if recording_uses_shared_view { + super::list_x::note_shared_view_heap_use(list.as_raw()); + } if std::env::var_os("XCL_CONSOLE_LISTS_LOG").is_some() { crate::xlog_info!( "console list: {} dispatches, {} skipped (PSO without a translation), {} barriers, {} clears, {} copies, {} skipped records", diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 9b6708ec67..d987a95dd1 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -326,6 +326,7 @@ struct RenderTargets { struct Bindings { heaps: Vec<usize>, has_sampler_heap: bool, + shared_view_heap: bool, topology: Option<u32>, viewports: Vec<D3D12_VIEWPORT>, scissors: Vec<windows::Win32::Foundation::RECT>, @@ -752,6 +753,8 @@ struct ListState { texture_writes: Vec<super::title_textures::GpuWrite>, /// Ordered state transitions of tracked textures in this physical segment. texture_transitions: Vec<super::title_textures::Transition>, + /// A translated draw/dispatch in this physical segment successfully bound the shared view heap. + uses_shared_view_heap: bool, /// Non-timestamp 64-bit `(va, value)` writes recorded by `Write64BitValue{Bottom,Top}OfPipeX` /// so `ExecuteCommandLists` / `KickoffX` can signal per-address GPU fences for cross-queue /// `Wait64BitValueX` without blocking the submitter thread on the CPU. @@ -871,6 +874,36 @@ impl ListState { } } +/// Record that a successfully bound translated draw/dispatch can address the shared view heap. +/// Callers gate this with `srv_tracking_enabled` and the heap-binding result. +pub(super) fn note_shared_view_heap_use(list: *mut c_void) { + if list.is_null() { + return; + } + if let Some(state) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + state.uses_shared_view_heap = true; + } +} + +fn propagate_bundle_shared_view_use(states: &mut HashMap<usize, ListState>, parent: usize, bundle: usize) { + let uses_shared = states.get(&bundle).is_some_and(|state| state.uses_shared_view_heap); + if uses_shared { + if let Some(state) = states.get_mut(&parent) { + state.uses_shared_view_heap = true; + } + } +} + +/// Snapshot bundle descriptor use into the parent recording before the bundle may be reset. +pub(super) unsafe extern "system" fn execute_bundle(this: *mut c_void, bundle: *mut c_void) { + if super::vram::srv_tracking_enabled() { + if let Some(states) = LISTS.lock().unwrap().as_mut() { + propagate_bundle_shared_view_use(states, this as usize, bundle as usize); + } + } + pc::<unsafe extern "system" fn(*mut c_void, *mut c_void)>(this, 27)(this, bundle); +} + /// Record immutable tracked-texture transitions on the physical segment that contains them. pub(super) fn note_texture_transitions(list: usize, transitions: &[(usize, u32, D3D12_RESOURCE_STATES)]) { let captured = super::title_textures::capture_transitions(transitions); @@ -894,6 +927,7 @@ struct KickoffEffects { sparse_writes: Vec<(usize, usize)>, texture_writes: Vec<super::title_textures::GpuWrite>, texture_transitions: Vec<super::title_textures::Transition>, + uses_shared_view_heap: bool, write64_signals: Vec<(u64, u64)>, cpu_writes: Vec<super::cpu_writes::Write>, } @@ -904,6 +938,7 @@ fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { sparse_writes: state.clear_sparse_writes(), texture_writes: std::mem::take(&mut state.texture_writes), texture_transitions: std::mem::take(&mut state.texture_transitions), + uses_shared_view_heap: std::mem::take(&mut state.uses_shared_view_heap), write64_signals: state.clear_write64_signals(), cpu_writes: std::mem::take(&mut state.cpu_writes), }; @@ -1031,6 +1066,7 @@ pub(super) struct SegmentEffects { sparse_writes: Vec<(usize, usize)>, texture_writes: Vec<super::title_textures::GpuWrite>, texture_transitions: Vec<super::title_textures::Transition>, + uses_shared_view_heap: bool, cpu_writes: Vec<super::cpu_writes::Write>, } @@ -1069,6 +1105,7 @@ impl SubmissionPlan { sparse_writes: s.sparse_writes.clone(), texture_writes: s.texture_writes.clone(), texture_transitions: s.texture_transitions.clone(), + uses_shared_view_heap: s.uses_shared_view_heap, cpu_writes: s.cpu_writes.clone(), }) .unwrap_or_default() @@ -1134,6 +1171,10 @@ impl<'a> SubmissionChunk<'a> { self.needs_cpu_completion } + pub(super) fn uses_shared_view_heap(self) -> bool { + self.effects.iter().any(|effects| effects.uses_shared_view_heap) + } + pub(super) unsafe fn submit_effects(self, queue: *mut c_void) -> Option<super::cpu_writes::Completion> { // The immutable submission plan is now the production path, so record execution here // after its caller has successfully submitted this exact chunk. The legacy @@ -1262,6 +1303,12 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C on_create_with_backing(list, alloc, alloc, pso, ty) } +/// Register the exact PC list owned by a console-shaped list. Its adopted Reset and final Release +/// use the normal hooks below, so this state has the same recording and object lifetime as `list`. +pub(super) unsafe fn on_console_list_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_COMMAND_LIST_TYPE) { + on_create(list, alloc, pso, ty) +} + /// Record a newly created command list's logical title allocator and native recording backing. /// /// # Safety @@ -1339,6 +1386,7 @@ pub(super) fn clear_segment_state(list: usize) { s.clear_waits(); s.texture_writes.clear(); s.texture_transitions.clear(); + s.uses_shared_view_heap = false; s.cpu_writes.clear(); s.predication = None; s.pred_in_state = false; @@ -3543,7 +3591,12 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - match prepare_deferred_segment(wrapper, list, ty) { Some(seg) => Some((seg, ListState { list_type: Some(ty), - bindings: Bindings { heaps: bindings.heaps.clone(), ..Default::default() }, + bindings: Bindings { + heaps: bindings.heaps.clone(), + has_sampler_heap: bindings.has_sampler_heap, + shared_view_heap: bindings.shared_view_heap, + ..Default::default() + }, deferred: Some(what), ..Default::default() })), @@ -4147,10 +4200,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let effects = match preclose_effects { Some(effects) => effects, None => LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).map(take_kickoff_effects).unwrap_or(KickoffEffects { - waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), write64_signals: Vec::new(), cpu_writes: Vec::new(), + waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), uses_shared_view_heap: false, write64_signals: Vec::new(), cpu_writes: Vec::new(), }), }; - let KickoffEffects { waits, sparse_writes, texture_writes, texture_transitions, write64_signals, cpu_writes } = effects; + let KickoffEffects { waits, sparse_writes, texture_writes, texture_transitions, uses_shared_view_heap: _uses_shared_view_heap, write64_signals, cpu_writes } = effects; if let Some(wrapper) = super::title_list::wrapper_of(this) { record_deferred(wrapper); } @@ -4741,8 +4794,9 @@ fn default_bound_heaps(view: Option<usize>, sampler: Option<usize>, current: &[u /// (a console descriptor table may be copied via raw CPU memcpy from any heap); heaps that /// kept their own shader-visible PC heap bind themselves for their local indices. Heaps whose /// own PC backing was downgraded to CPU-only cannot be bound directly. -pub(super) unsafe fn pc_heaps(n: u32, heaps: *const usize) -> Vec<Option<ID3D12DescriptorHeap>> { +pub(super) unsafe fn pc_heaps_with_shared(n: u32, heaps: *const usize) -> (Vec<Option<ID3D12DescriptorHeap>>, bool) { let mut view_heap = super::console_heap::global_heap(); + let shared_view = view_heap.as_ref().map(|heap| heap.as_raw() as usize); let mut sampler_heap = ensure_global_sampler_heap(); let mut out = Vec::new(); for k in 0..n as usize { @@ -4764,16 +4818,17 @@ pub(super) unsafe fn pc_heaps(n: u32, heaps: *const usize) -> Vec<Option<ID3D12D out.push(Some(h.clone())); } } + let uses_shared_view = shared_view.is_some_and(|shared| view_heap.as_ref().is_some_and(|heap| heap.as_raw() as usize == shared)); out.extend(view_heap.map(Some)); out.extend(sampler_heap.map(Some)); - out + (out, uses_shared_view) } /// Translated shaders with directly-indexed root signatures (`CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` /// / `SAMPLER_HEAP_DIRECTLY_INDEXED`) and heap windows (`pso::heap_windows`) require valid /// shader-visible view and sampler heaps to be bound even if the title bound 0 heaps (or only a /// view heap with 0 sampler heaps). -pub(super) unsafe fn ensure_view_heap(this: *mut c_void) { +pub(super) unsafe fn ensure_view_heap(this: *mut c_void) -> bool { let view = if crate::gpu::recomp::pso::heap_windows() { super::console_heap::global_heap() } else { @@ -4783,19 +4838,23 @@ pub(super) unsafe fn ensure_view_heap(this: *mut c_void) { let view_raw = view.as_ref().map(|h| h.as_raw() as usize); let sampler_raw = sampler.as_ref().map(|h| h.as_raw() as usize); if view_raw.is_none() && sampler_raw.is_none() { - return; + return false; } let mut to_bind: Option<Vec<usize>> = None; + let mut shared_view_bound = false; with_bindings(this, |b| { if let Some((next, has_sampler)) = default_bound_heaps(view_raw, sampler_raw, &b.heaps, b.has_sampler_heap) { b.heaps = next.clone(); b.has_sampler_heap = has_sampler; + b.shared_view_heap |= view_raw.is_some_and(|view| next.contains(&view)); to_bind = Some(next); } + shared_view_bound = b.shared_view_heap; }); if let Some(raw) = to_bind { pc::<unsafe extern "system" fn(*mut c_void, u32, *const usize)>(this, 28)(this, raw.len() as u32, raw.as_ptr()); } + shared_view_bound } /// console #32 SetDescriptorHeaps (PC #28) @@ -4809,6 +4868,7 @@ pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n with_bindings(this, |b| { b.heaps.clear(); b.has_sampler_heap = false; + b.shared_view_heap = false; }); return f(this, n, heaps); } @@ -4821,16 +4881,18 @@ pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n with_bindings(this, |b| { b.heaps = given; b.has_sampler_heap = has_sampler; + b.shared_view_heap = false; }); return f(this, n, heaps); } - let h = pc_heaps(n, heaps); + let (h, shared_view_heap) = pc_heaps_with_shared(n, heaps); let has_sampler = h.iter().any(|x| x.as_ref().is_some_and(|h| h.GetDesc().Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)); let raw: Vec<usize> = h.iter().map(|x| x.as_ref().map_or(0, |x| x.as_raw() as usize)).collect(); let kept = raw.clone(); with_bindings(this, |b| { b.heaps = kept; b.has_sampler_heap = has_sampler; + b.shared_view_heap = shared_view_heap; }); f(this, raw.len() as u32, raw.as_ptr()) } @@ -4998,6 +5060,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.clear_waits(); s.texture_writes.clear(); s.texture_transitions.clear(); + s.uses_shared_view_heap = false; s.cpu_writes.clear(); s.predication = None; s.pred_in_state = false; @@ -6198,6 +6261,80 @@ mod tests { } } + #[test] + fn submission_plan_keeps_shared_view_use_after_rerecord() { + let list = 0x7ffe_1901usize as *mut c_void; + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert( + list as usize, + ListState { uses_shared_view_heap: true, ..Default::default() }, + ); + let plan = SubmissionPlan::capture(&[list]); + LISTS.lock().unwrap().as_mut().unwrap().get_mut(&(list as usize)).unwrap().uses_shared_view_heap = false; + + let mut captured = false; + unsafe { + execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| captured = chunk.uses_shared_view_heap()); + } + assert!(captured, "the immutable plan owns the submitted recording's flag"); + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + } + + #[test] + fn console_replay_registers_the_physical_list_until_release() { + let pc = 0x7ffe_1981usize as *mut c_void; + assert!(!has_list_state(pc as usize)); + unsafe { on_console_list_create(pc, 0xa110, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE) }; + note_shared_view_heap_use(pc); + + let plan = SubmissionPlan::capture(&[pc]); + let mut captured = false; + unsafe { + execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| captured = chunk.uses_shared_view_heap()); + } + assert!(captured, "the plan uses the physical PC list mapped at queue submission"); + + on_release(pc as usize); + assert!(!has_list_state(pc as usize), "the physical list's final Release removes its state"); + } + + #[test] + fn clearing_a_reused_segment_clears_shared_view_use() { + let list = 0x7ffe_1a01usize; + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert( + list, + ListState { uses_shared_view_heap: true, ..Default::default() }, + ); + clear_segment_state(list); + + let mut g = LISTS.lock().unwrap(); + assert!(!g.as_ref().unwrap()[&list].uses_shared_view_heap); + g.as_mut().unwrap().remove(&list); + } + + #[test] + fn kickoff_moves_shared_view_use_to_the_finished_segment() { + let mut state = ListState { uses_shared_view_heap: true, ..Default::default() }; + let effects = take_kickoff_effects(&mut state); + assert!(effects.uses_shared_view_heap); + assert!(!state.uses_shared_view_heap, "the continuing recording starts a new segment"); + assert!(!take_kickoff_effects(&mut state).uses_shared_view_heap); + } + + #[test] + fn execute_bundle_use_survives_bundle_reset() { + let (parent, bundle) = (0x7ffe_1b01usize, 0x7ffe_1b02usize); + let mut states = HashMap::from([ + (parent, ListState::default()), + (bundle, ListState { uses_shared_view_heap: true, ..Default::default() }), + ]); + propagate_bundle_shared_view_use(&mut states, parent, bundle); + states.get_mut(&bundle).unwrap().uses_shared_view_heap = false; + assert!(states[&parent].uses_shared_view_heap); + + propagate_bundle_shared_view_use(&mut states, parent, bundle); + assert!(states[&parent].uses_shared_view_heap, "executing an unused bundle cannot clear prior use"); + } + #[test] fn queue_identity_changes_when_a_raw_address_is_reused() { let raw = 0x7ffe_1801usize; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bf1de79daf..eae0714e57 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1128,6 +1128,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (44, b::set_graphics_root_descriptor as usize), (46, b::set_graphics_root_descriptor as usize), (26, l::resource_barrier_x as usize), + (27, l::execute_bundle as usize), (25, b::set_pipeline_state as usize), (33, b::set_compute_root_signature as usize), (35, b::set_compute_root_table as usize), @@ -3011,6 +3012,7 @@ pub(super) unsafe extern "system" fn dev_create_command_list_x(this: *mut c_void let pc_pso = super::console_list::pc_pso(pso as *mut c_void) as usize; let hr = dev_create_command_list(this, mask, ty, alloc, pc_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::list_x::on_console_list_create(*ppv, alloc, pc_pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); *ppv = super::console_list::create_with_allocator(*ppv, alloc as *mut c_void); } hr diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 26d0b39306..83e4952c66 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -135,6 +135,7 @@ static PLACED_TEXTURES: Mutex<Option<HashSet<usize>>> = Mutex::new(None); /// `XCL_TEXTURE_BUDGET_EVICT=1`: retain CPU-side identities for live texture SRVs. This is /// preparation only: recorded command lists can still name older descriptor contents, so these /// records do not make descriptor replacement or texture eviction GPU-safe. +#[inline] pub(super) fn srv_tracking_enabled() -> bool { #[cfg(test)] if SRV_TRACKING_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) { From 025dc2facaefc1be1af7eb7fb49c173a7a36891d Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:54:09 -0800 Subject: [PATCH 204/265] D3D12.X: retire shared descriptor heap epochs Reserve exact opt-in shared-view heap epochs at native title submission and retain their strong fence receipts until retirement. Keep future descriptor mutations serialized with reservation, and poison quiescence permanently when executed work cannot be tracked. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 63 ++++++++- crates/xcl/src/hle/d3d12x/real.rs | 5 +- crates/xcl/src/hle/d3d12x/vram.rs | 201 ++++++++++++++++++++++++++++ 3 files changed, 265 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index d987a95dd1..b31ca75ba1 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1187,6 +1187,48 @@ impl<'a> SubmissionChunk<'a> { } } +/// Submit one exact title chunk, adding a retirement receipt only when an opt-in recording can +/// read the shared view heap. The ordinary path stays on `SubmissionGate::submit`, which avoids +/// an extra queue marker when descriptor-epoch tracking is disabled or the chunk does not use it. +pub(super) unsafe fn submit_title_chunk( + gate: &mut super::alloc_pool::SubmissionGate, + queue: *mut c_void, + lists: &[*mut c_void], + protect_shared_view: bool, + prepare: impl FnOnce(), + execute: impl FnOnce(), +) -> bool { + if !protect_shared_view { + return gate.submit(queue, lists, prepare, execute); + } + let mut epoch = None; + let submitted = gate.submit_receipted( + queue, + lists, + || { + epoch = Some(super::vram::reserve_shared_view_epoch()); + prepare(); + }, + execute, + ); + match submitted { + super::alloc_pool::ReceiptedSubmission::NotExecuted => { + if let Some(epoch) = epoch { + super::vram::cancel_shared_view_epoch(epoch); + } + false + } + super::alloc_pool::ReceiptedSubmission::Executed(receipt) => { + super::vram::attach_shared_view_epoch(epoch.expect("executed shared-view submission without an epoch"), receipt); + true + } + super::alloc_pool::ReceiptedSubmission::ExecutedUntracked => { + super::vram::poison_shared_view_epoch(epoch.expect("executed shared-view submission without an epoch")); + true + } + } +} + /// Record a newly created title command queue so `KickoffX` can find a compatible queue. pub fn on_queue_create(queue: usize, device: usize, ty: D3D12_COMMAND_LIST_TYPE) { if queue == 0 { @@ -4203,7 +4245,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), uses_shared_view_heap: false, write64_signals: Vec::new(), cpu_writes: Vec::new(), }), }; - let KickoffEffects { waits, sparse_writes, texture_writes, texture_transitions, uses_shared_view_heap: _uses_shared_view_heap, write64_signals, cpu_writes } = effects; + let KickoffEffects { waits, sparse_writes, texture_writes, texture_transitions, uses_shared_view_heap, write64_signals, cpu_writes } = effects; if let Some(wrapper) = super::title_list::wrapper_of(this) { record_deferred(wrapper); } @@ -4219,6 +4261,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let mut prior_cpu_completions = Vec::new(); let mut wait_after_cpu_write = false; let mut gate = super::alloc_pool::SubmissionGate::default(); + let track_shared_view_epochs = super::vram::srv_tracking_enabled(); if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { let plan = submission_plan(prior); @@ -4227,7 +4270,14 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let (completions, _) = execute_submission_plan_with_completions(q_raw, &plan, &waits, |chunk| { super::queue_submit::with(q_raw as usize, || { let lists = chunk.lists(); - if !gate.submit(q_raw, lists, || {}, || exec(q_raw, lists.len() as u32, lists.as_ptr())) { + if !submit_title_chunk( + &mut gate, + q_raw, + lists, + track_shared_view_epochs && chunk.uses_shared_view_heap(), + || {}, + || exec(q_raw, lists.len() as u32, lists.as_ptr()), + ) { return (false, None); } submitted.extend_from_slice(lists); @@ -4254,7 +4304,14 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let one = [this]; let current_submitted = super::queue_submit::with(q_raw as usize, || { - let submitted = gate.submit(q_raw, &one, || {}, || exec(q_raw, 1, one.as_ptr())); + let submitted = submit_title_chunk( + &mut gate, + q_raw, + &one, + track_shared_view_epochs && uses_shared_view_heap, + || {}, + || exec(q_raw, 1, one.as_ptr()), + ); if submitted { if let Some(trace) = ¤t_trace { mark_trace(trace, ListEvent::Executed); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index eae0714e57..d9031520e3 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9064,12 +9064,15 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis let mut chunks = 0usize; let mut gate = super::alloc_pool::SubmissionGate::default(); let mut submitted = Vec::with_capacity(mapped.len()); + let track_shared_view_epochs = super::vram::srv_tracking_enabled(); let _ = super::list_x::execute_submission_plan_until_failure_on(this, &plan, |chunk| { super::queue_submit::with(this as usize, || { let lists = chunk.lists(); - if !gate.submit( + if !super::list_x::submit_title_chunk( + &mut gate, this, lists, + track_shared_view_epochs && chunk.uses_shared_view_heap(), || { let _ = super::alloc_pool::note_resubmits(this, lists); }, diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 83e4952c66..bd1d16b4d4 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -154,6 +154,119 @@ pub(super) fn srv_tracking_enabled() -> bool { #[cfg(test)] static SRV_TRACKING_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) struct SharedViewEpoch(u64); + +enum EpochRetirement<R> { + Reserved, + Receipt(R), + Poisoned, +} + +struct SharedViewEpochs<R> { + next: u64, + poisoned: bool, + pending: Vec<(SharedViewEpoch, EpochRetirement<R>)>, +} + +impl<R> SharedViewEpochs<R> { + const fn new() -> Self { + Self { next: 0, poisoned: false, pending: Vec::new() } + } + + fn reserve(&mut self) -> SharedViewEpoch { + self.next = self.next.checked_add(1).expect("shared view heap epoch overflow"); + let epoch = SharedViewEpoch(self.next); + self.pending.push((epoch, EpochRetirement::Reserved)); + epoch + } + + fn cancel(&mut self, epoch: SharedViewEpoch) { + match self.pending.iter().position(|entry| entry.0 == epoch) { + Some(i) if matches!(self.pending[i].1, EpochRetirement::Reserved) => { + self.pending.remove(i); + } + _ => self.poisoned = true, + } + } + + fn attach(&mut self, epoch: SharedViewEpoch, receipt: R) { + match self.pending.iter_mut().find(|entry| entry.0 == epoch) { + Some((_, state @ EpochRetirement::Reserved)) => *state = EpochRetirement::Receipt(receipt), + _ => self.poisoned = true, + } + } + + fn poison(&mut self, epoch: SharedViewEpoch) { + match self.pending.iter_mut().find(|entry| entry.0 == epoch) { + Some((_, state @ EpochRetirement::Reserved)) => *state = EpochRetirement::Poisoned, + _ => self.poisoned = true, + } + } + + fn sweep(&mut self, complete: impl Fn(&R) -> bool) { + self.pending.retain(|(_, state)| !matches!(state, EpochRetirement::Receipt(receipt) if complete(receipt))); + } + + fn quiescent(&mut self, complete: impl Fn(&R) -> bool) -> bool { + self.sweep(complete); + !self.poisoned && self.pending.is_empty() + } +} + +fn with_quiescent_epochs<R, T>( + tracking_enabled: bool, + epochs: &Mutex<SharedViewEpochs<R>>, + complete: impl Fn(&R) -> bool, + mutation: impl FnOnce() -> T, +) -> Option<T> { + if !tracking_enabled { + return None; + } + let mut epochs = epochs.lock().unwrap(); + if !epochs.quiescent(complete) { + return None; + } + let result = mutation(); + drop(epochs); + Some(result) +} + +static SHARED_VIEW_EPOCHS: Mutex<SharedViewEpochs<super::alloc_pool::SubmissionReceipt>> = + Mutex::new(SharedViewEpochs::new()); + +pub(super) fn reserve_shared_view_epoch() -> SharedViewEpoch { + let mut epochs = SHARED_VIEW_EPOCHS.lock().unwrap(); + epochs.sweep(super::alloc_pool::SubmissionReceipt::is_complete); + epochs.reserve() +} + +pub(super) fn cancel_shared_view_epoch(epoch: SharedViewEpoch) { + SHARED_VIEW_EPOCHS.lock().unwrap().cancel(epoch); +} + +pub(super) fn attach_shared_view_epoch(epoch: SharedViewEpoch, receipt: super::alloc_pool::SubmissionReceipt) { + SHARED_VIEW_EPOCHS.lock().unwrap().attach(epoch, receipt); +} + +pub(super) fn poison_shared_view_epoch(epoch: SharedViewEpoch) { + SHARED_VIEW_EPOCHS.lock().unwrap().poison(epoch); +} + +/// Run a descriptor mutation only while every tracked shared-view submission is retired, holding +/// the epoch lock until the mutation ends so a new reservation cannot cross the check. This lock +/// is outermost: the closure may take descriptor backing/tracker locks, but must not submit GPU +/// work or call anything that reserves another shared-view epoch. +/// +/// A missing post-execute receipt permanently returns `None`, so an untracked submission (or a +/// reused queue address) can never be mistaken for quiescence. +#[allow(dead_code)] // consumed by the later descriptor-rewrite stage +pub(super) fn with_quiescent_shared_view_heap<T>(mutation: impl FnOnce() -> T) -> Option<T> { + with_quiescent_epochs( + srv_tracking_enabled(), &SHARED_VIEW_EPOCHS, super::alloc_pool::SubmissionReceipt::is_complete, mutation, + ) +} + #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub(super) struct SrvSlot { heap_generation: u64, @@ -2248,6 +2361,94 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st mod tests { use super::*; + #[derive(Clone)] + struct FakeReceipt { + fence: Arc<std::sync::atomic::AtomicU64>, + value: u64, + } + + fn fake_complete(receipt: &FakeReceipt) -> bool { + receipt.fence.load(std::sync::atomic::Ordering::Relaxed) >= receipt.value + } + + #[test] + fn shared_view_epochs_cancel_retire_and_remain_monotonic() { + let mut epochs = SharedViewEpochs::new(); + let cancelled = epochs.reserve(); + let retiring = epochs.reserve(); + assert!(cancelled.0 < retiring.0); + epochs.cancel(cancelled); + + let fence = Arc::new(std::sync::atomic::AtomicU64::new(0)); + epochs.attach(retiring, FakeReceipt { fence: Arc::clone(&fence), value: 3 }); + assert!(!epochs.quiescent(fake_complete)); + fence.store(3, std::sync::atomic::Ordering::Relaxed); + assert!(epochs.quiescent(fake_complete)); + assert!(epochs.reserve().0 > retiring.0, "retirement never reuses an epoch identity"); + } + + #[test] + fn reused_queue_address_cannot_retire_an_old_epoch() { + let mut epochs = SharedViewEpochs::new(); + let old_epoch = epochs.reserve(); + let old_generation_fence = Arc::new(std::sync::atomic::AtomicU64::new(0)); + epochs.attach(old_epoch, FakeReceipt { fence: Arc::clone(&old_generation_fence), value: 7 }); + + // A new queue generation at the same numeric address owns another fence. Its progress + // cannot satisfy the strong fence owner retained by the old epoch's receipt. + let replacement_generation_fence = Arc::new(std::sync::atomic::AtomicU64::new(99)); + assert_eq!(replacement_generation_fence.load(std::sync::atomic::Ordering::Relaxed), 99); + assert!(!epochs.quiescent(fake_complete)); + old_generation_fence.store(7, std::sync::atomic::Ordering::Relaxed); + assert!(epochs.quiescent(fake_complete)); + } + + #[test] + fn untracked_shared_view_epoch_never_becomes_quiescent() { + let mut epochs = SharedViewEpochs::<FakeReceipt>::new(); + let epoch = epochs.reserve(); + epochs.poison(epoch); + assert!(!epochs.quiescent(fake_complete)); + } + + #[test] + fn disabled_tracking_cannot_authorize_descriptor_mutation() { + let epochs = Mutex::new(SharedViewEpochs::<FakeReceipt>::new()); + let mut ran = false; + assert!(with_quiescent_epochs(false, &epochs, fake_complete, || ran = true).is_none()); + assert!(!ran); + } + + #[test] + fn quiescent_mutation_excludes_new_reservations() { + let epochs = Arc::new(Mutex::new(SharedViewEpochs::<FakeReceipt>::new())); + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let mutation_epochs = Arc::clone(&epochs); + let mutation = std::thread::spawn(move || { + with_quiescent_epochs(true, &mutation_epochs, fake_complete, || { + entered_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + }) + }); + entered_rx.recv().unwrap(); + + let (attempted_tx, attempted_rx) = std::sync::mpsc::channel(); + let (reserved_tx, reserved_rx) = std::sync::mpsc::channel(); + let reserve_epochs = Arc::clone(&epochs); + let reserve = std::thread::spawn(move || { + attempted_tx.send(()).unwrap(); + let epoch = reserve_epochs.lock().unwrap().reserve(); + reserved_tx.send(epoch).unwrap(); + }); + attempted_rx.recv().unwrap(); + assert!(reserved_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err()); + release_tx.send(()).unwrap(); + assert!(mutation.join().unwrap().is_some()); + assert_eq!(reserved_rx.recv().unwrap(), SharedViewEpoch(1)); + reserve.join().unwrap(); + } + fn tracked_entry(resource: usize, pc_srv: u64) -> TrackedSrv { let mut words = [0u32; 8]; words[0] = pc_srv as u32; From 84617008bc8b01c688b0b7c9559cb8925821bd8b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:50:42 -0800 Subject: [PATCH 205/265] D3D12.X: capture native PSO generations in recordings Recipe-backed PSOs can eventually replace a native object while recorded command lists still refer to the prior generation. Capture the exact generation atomically at every native bind, deduplicate pins per physical segment, and carry them into immutable submission plans and bundle parents. This stage intentionally stops at capture; submission retirement will attach the pins to receipts later. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 9 +- crates/xcl/src/hle/d3d12x/console_list.rs | 27 +++- crates/xcl/src/hle/d3d12x/device_x.rs | 3 +- crates/xcl/src/hle/d3d12x/list_x.rs | 151 +++++++++++++++--- crates/xcl/src/hle/d3d12x/pso_async.rs | 177 ++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 19 ++- 6 files changed, 335 insertions(+), 51 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index e6718c62da..8d63d78405 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -328,7 +328,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if unbuilt_compute && super::list_x::defer(this, raw_pso, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { return; } - let (pso, bound_unbuilt) = super::pso_async::resolve_wait_bound(raw_pso); + let ((pso, bound_unbuilt), generation) = super::pso_async::resolve_wait_bound_and_pin_if_enabled(raw_pso); + super::list_x::record_native_generation(this as usize, generation); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); let args_off_title = args_off; let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); @@ -650,7 +651,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option<ID3D12GraphicsCommandList> let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); let pso = with(this, |s| s.pso); // a pipeline still being built in the background is waited for (its stand-in draws nothing) - let real = super::pso_async::resolve_wait(pso); + let real = super::list_x::resolve_and_record_pipeline_wait(list.as_raw() as usize, pso); if !super::real::is_translated_graphics(real) { // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in // TWO_PASS rather than TRANSLATED_GRAPHICS. Binding the title's graphics RS and issuing @@ -1013,7 +1014,7 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f if super::pso_async::is_pending(pso) && super::list_x::defer(this, pso, super::list_x::Deferred::Dispatch(x, y, z, flags)) { return; } - let pso = super::pso_async::resolve_wait(pso); + let pso = super::list_x::resolve_and_record_pipeline_wait(this as usize, pso); let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; if !super::real::is_translated_compute(pso) { // a console pipeline without a translation (including a background build that @@ -1199,7 +1200,7 @@ unsafe fn bind_abi_with_root( Ok(p as usize) }; // a pipeline still being built in the background is waited for - let real = super::pso_async::resolve_wait(pso); + let real = super::list_x::resolve_and_record_pipeline_wait(list.as_raw() as usize, pso); // a compute shader takes no more arguments from registers than it has (`inline_for`) let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) }; let inline = layout.as_ref().map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len()); diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 3878989669..75a597eee0 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -435,7 +435,18 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, ps } with_list(obj, |st| new_chunk(obj, st)); let f: unsafe extern "system" fn(usize, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(pc_vtable_call(pc, 10)); - f(pc, allocator, pc_pso(pso)) + // The adopted physical slot reaches real::cl_reset, which resolves and records the initial + // generation. Do not clear that capture again in this outer console wrapper. + forward_reset(pc, allocator, pso, |pc, allocator, pso| f(pc, allocator, pso)) +} + +unsafe fn forward_reset( + pc: usize, + allocator: *mut c_void, + pso: *mut c_void, + call: impl FnOnce(usize, *mut c_void, *mut c_void) -> HRESULT, +) -> HRESULT { + call(pc, allocator, pc_pso(pso)) } unsafe extern "system" fn cl_dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { @@ -890,7 +901,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> { // a pipeline still being built in the background is waited for; if // the background translation failed, skip instead of binding XCL's // ABI root signature onto the stand-in - let real = super::pso_async::resolve_wait((*p).pc); + let real = super::list_x::resolve_and_record_pipeline_wait(st.pc, (*p).pc); if !super::real::is_translated_compute(real) { out.skipped_dispatches += 1; continue; @@ -997,6 +1008,18 @@ fn bytemuck_u32(v: &[u32]) -> &[u8] { mod tests { use super::*; + #[test] + fn console_reset_preserves_the_physical_initial_generation_capture() { + let mut pins = vec![1u64]; + let hr = unsafe { forward_reset(0xC1, std::ptr::null_mut(), std::ptr::null_mut(), |_, _, _| { + pins.clear(); + pins.push(2); + S_OK + }) }; + assert_eq!(hr, S_OK); + assert_eq!(pins, [2], "the outer wrapper must not clear the physical Reset hook's new pin"); + } + #[test] fn layout_packs_parameters_in_order() { // RTS0 v2: consts b0 x19 | UAV u0 | UAV u1 | SRV t0 diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index cff823329a..511ae0ad4a 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -104,11 +104,12 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: let hr = if super::console_list::enabled() { real::dev_create_command_list_x(this, node, ty, alloc, pso, riid, ppv) } else { - let resolved_pso = super::pso_async::resolve_for_bind(pso); + let (resolved_pso, generation) = super::pso_async::resolve_and_pin_if_enabled(pso); let pc_alloc = active_list_allocator(alloc); let hr = real::dev_create_command_list(this, node, ty, pc_alloc, resolved_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::list_x::on_create_with_backing(*ppv, alloc, pc_alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + super::list_x::record_native_generation(*ppv as usize, generation); super::dred::reset(*ppv); if pso != 0 { super::dred::mark_pipeline(*ppv, pso, resolved_pso); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index b31ca75ba1..ca48c66a09 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -728,6 +728,8 @@ struct ListState { last_queue: Option<usize>, /// Title's currently bound PSO (before dynamic depth-bias override) bound_pso: usize, + /// Recipe-backed native generations referenced by this physical recording. + native_generations: Vec<super::pso_async::NativeGeneration>, /// Active `RSSetDepthBiasX` override (None = zero / disabled) depth_bias: Option<DepthBias>, /// Last depth bias sent to `ID3D12GraphicsCommandList9::RSSetDepthBias` on this PC list @@ -811,6 +813,10 @@ enum WaitPlacement { } impl ListState { + fn pin_native_generation(&mut self, generation: super::pso_async::NativeGeneration) { + push_unique(&mut self.native_generations, generation, super::pso_async::NativeGeneration::same); + } + fn note_write(&mut self, producer: WriteProducer, va: u64, size: u64) { if size == 0 { return; @@ -885,22 +891,69 @@ pub(super) fn note_shared_view_heap_use(list: *mut c_void) { } } +fn push_unique<T>(items: &mut Vec<T>, item: T, same: impl Fn(&T, &T) -> bool) { + if !items.iter().any(|old| same(old, &item)) { + items.push(item); + } +} + fn propagate_bundle_shared_view_use(states: &mut HashMap<usize, ListState>, parent: usize, bundle: usize) { - let uses_shared = states.get(&bundle).is_some_and(|state| state.uses_shared_view_heap); - if uses_shared { - if let Some(state) = states.get_mut(&parent) { - state.uses_shared_view_heap = true; - } + if states.get(&bundle).is_some_and(|state| state.uses_shared_view_heap) { + states.entry(parent).or_default().uses_shared_view_heap = true; } } -/// Snapshot bundle descriptor use into the parent recording before the bundle may be reset. -pub(super) unsafe extern "system" fn execute_bundle(this: *mut c_void, bundle: *mut c_void) { - if super::vram::srv_tracking_enabled() { - if let Some(states) = LISTS.lock().unwrap().as_mut() { - propagate_bundle_shared_view_use(states, this as usize, bundle as usize); +pub(super) fn record_native_generation(list: usize, generation: Option<super::pso_async::NativeGeneration>) { + if let Some(generation) = generation { + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().pin_native_generation(generation); + } +} + +pub(super) fn resolve_and_record_pipeline(list: usize, pso: usize) -> usize { + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled(pso); + record_native_generation(list, generation); + resolved +} + +pub(super) fn resolve_and_record_pipeline_lazy(list: usize, pso: usize) -> usize { + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled_lazy(pso); + record_native_generation(list, generation); + resolved +} + +pub(super) fn resolve_and_record_pipeline_wait(list: usize, pso: usize) -> usize { + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled_wait(pso); + record_native_generation(list, generation); + resolved +} + +/// Snapshot bundle descriptor and PSO-generation use before the bundle may be reset. +pub(super) fn on_execute_bundle(parent: usize, bundle: usize) { + let track_descriptors = super::vram::srv_tracking_enabled(); + let track_generations = super::pso_async::rebuild_recipes_enabled(); + if !track_descriptors && !track_generations { + return; + } + let mut g = LISTS.lock().unwrap(); + let Some(m) = g.as_mut() else { return }; + let pins = if track_generations { + m.get(&bundle).map(|s| s.native_generations.clone()).unwrap_or_default() + } else { + Vec::new() + }; + if track_descriptors { + propagate_bundle_shared_view_use(m, parent, bundle); + } + if track_generations { + let parent = m.entry(parent).or_default(); + for pin in pins { + parent.pin_native_generation(pin); } } +} + +pub(super) unsafe extern "system" fn execute_bundle(this: *mut c_void, bundle: *mut c_void) { + on_execute_bundle(this as usize, bundle as usize); pc::<unsafe extern "system" fn(*mut c_void, *mut c_void)>(this, 27)(this, bundle); } @@ -930,6 +983,7 @@ struct KickoffEffects { uses_shared_view_heap: bool, write64_signals: Vec<(u64, u64)>, cpu_writes: Vec<super::cpu_writes::Write>, + _native_generations: Vec<super::pso_async::NativeGeneration>, } fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { @@ -941,6 +995,7 @@ fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { uses_shared_view_heap: std::mem::take(&mut state.uses_shared_view_heap), write64_signals: state.clear_write64_signals(), cpu_writes: std::mem::take(&mut state.cpu_writes), + _native_generations: std::mem::take(&mut state.native_generations), }; state.written_ranges.clear(); state.segment_write_producers.clear(); @@ -1068,6 +1123,7 @@ pub(super) struct SegmentEffects { texture_transitions: Vec<super::title_textures::Transition>, uses_shared_view_heap: bool, cpu_writes: Vec<super::cpu_writes::Write>, + _native_generations: Vec<super::pso_async::NativeGeneration>, } impl SegmentEffects { @@ -1107,6 +1163,7 @@ impl SubmissionPlan { texture_transitions: s.texture_transitions.clone(), uses_shared_view_heap: s.uses_shared_view_heap, cpu_writes: s.cpu_writes.clone(), + _native_generations: s.native_generations.clone(), }) .unwrap_or_default() }) @@ -1434,6 +1491,7 @@ pub(super) fn clear_segment_state(list: usize) { s.pred_in_state = false; s.bindings = Bindings::default(); s.deferred = None; + s.native_generations.clear(); } } @@ -3612,10 +3670,10 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - let pred_buf = &carry.pred_buf; let bindings = &carry.bindings; - let init_pso = if ty == D3D12_COMMAND_LIST_TYPE_COPY { - 0 + let (init_pso, init_generation) = if ty == D3D12_COMMAND_LIST_TYPE_COPY { + (0, None) } else { - super::pso_async::resolve(bound_pso) + super::pso_async::resolve_and_pin_if_enabled_lazy(bound_pso) }; let dev = device_of(list)?; let dev_raw = dev.as_raw() as usize; @@ -3650,7 +3708,10 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - } else { None }; - let continuation_state = carry.continuation_state(ty); + let mut continuation_state = carry.continuation_state(ty); + if let Some(generation) = init_generation { + continuation_state.pin_native_generation(generation); + } let next_bindings = super::bind::prepare_split(list, next_pc, alloc); let deferred_bindings = deferred.as_ref().map(|(seg, _)| super::bind::prepare_split(list, *seg, alloc)); @@ -4058,12 +4119,22 @@ pub(super) unsafe fn before_close(list: *mut c_void) { /// Clear active predication state when `ID3D12GraphicsCommandList::Reset` resets a recording. pub(super) fn on_pc_reset(list: *mut c_void) { reset_copy_scratch(list); - if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { + if list.is_null() { + return; + } + let clear_predication = PREDICATION_USED.load(Ordering::Acquire); + let clear_generations = super::pso_async::rebuild_recipes_enabled(); + if !clear_predication && !clear_generations { 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; + if clear_generations { + s.native_generations.clear(); + } + if clear_predication { + s.predication = None; + s.pred_in_state = false; + } } } @@ -4242,10 +4313,13 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let effects = match preclose_effects { Some(effects) => effects, None => LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).map(take_kickoff_effects).unwrap_or(KickoffEffects { - waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), uses_shared_view_heap: false, write64_signals: Vec::new(), cpu_writes: Vec::new(), + waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), uses_shared_view_heap: false, write64_signals: Vec::new(), cpu_writes: Vec::new(), _native_generations: Vec::new(), }), }; - let KickoffEffects { waits, sparse_writes, texture_writes, texture_transitions, uses_shared_view_heap, write64_signals, cpu_writes } = effects; + let KickoffEffects { + waits, sparse_writes, texture_writes, texture_transitions, uses_shared_view_heap, + write64_signals, cpu_writes, _native_generations, + } = effects; if let Some(wrapper) = super::title_list::wrapper_of(this) { record_deferred(wrapper); } @@ -4367,6 +4441,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { s.clear_waits(); s.texture_writes.clear(); s.cpu_writes.clear(); + s.native_generations.clear(); s.bindings = bindings_copy; } primary @@ -4375,7 +4450,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { }; let ext_closed = *(target as *const usize); - let init_pso = super::pso_async::resolve_for_bind(bound_pso); + let (init_pso, init_generation) = super::pso_async::resolve_and_pin_if_enabled(bound_pso); let reset_hr = super::alloc_pool::reset_list(target as usize, alloc, list_type(target).0, |pc_alloc| { pc::<unsafe extern "system" fn(*mut c_void, usize, usize) -> i32>(target, PC_RESET)(target, pc_alloc, init_pso) }); @@ -4389,6 +4464,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if reset_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); } + record_native_generation(target as usize, init_generation); trace_list(target as usize, ListEvent::Reset); reset_copy_scratch(target); let bindings = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(target as usize))).map(|s| s.bindings.clone()); @@ -4493,7 +4569,7 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b (if restore { Some(s.bound_pso) } else { None }, target != s.native_bias) }; if let Some(base) = need_restore_base { - let resolved = super::pso_async::resolve_for_bind(base); + let resolved = resolve_and_record_pipeline(this as usize, base); pc::<unsafe extern "system" fn(*mut c_void, usize)>(this, PC_SET_PIPELINE_STATE)(this, resolved); } if !need_native_call { @@ -4537,7 +4613,7 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b } }; if let Some(base) = restore { - let resolved = super::pso_async::resolve_for_bind(base); + let resolved = resolve_and_record_pipeline(this as usize, base); pc::<unsafe extern "system" fn(*mut c_void, usize)>(this, PC_SET_PIPELINE_STATE)(this, resolved); } } @@ -4577,7 +4653,7 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { } None => (bound_pso, false), }; - let resolved = super::pso_async::resolve_for_bind(target); + let resolved = resolve_and_record_pipeline(list as usize, target); pc::<unsafe extern "system" fn(*mut c_void, usize)>(list, PC_SET_PIPELINE_STATE)(list, resolved); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { s.using_fallback_pso = is_fallback; @@ -5084,7 +5160,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 // 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); - let resolved = super::pso_async::resolve_for_bind(pso); + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled(pso); // (the PC allocator the title's allocator stands for now: `alloc_pool`) let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0); let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| { @@ -5119,11 +5195,13 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.texture_transitions.clear(); s.uses_shared_view_heap = false; s.cpu_writes.clear(); + s.native_generations.clear(); s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) }; + record_native_generation(this as usize, generation); super::bind::reset(this, alloc, pso); if !is_bundle && pso != 0 { if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) { @@ -5640,6 +5718,31 @@ mod tests { use super::*; use std::sync::Arc; + #[test] + fn generation_capture_deduplicates_and_survives_recording_reset() { + let generation = Arc::new(()); + let mut recording = Vec::new(); + push_unique(&mut recording, generation.clone(), Arc::ptr_eq); + push_unique(&mut recording, generation.clone(), Arc::ptr_eq); + assert_eq!(recording.len(), 1); + + let submission_plan = recording.clone(); + recording.clear(); + drop(generation); + assert_eq!(Arc::strong_count(&submission_plan[0]), 1, "the immutable plan must own the submitted generation"); + } + + #[test] + fn bundle_snapshot_deduplicates_into_parent_recording() { + let generation = Arc::new(()); + let bundle = vec![generation.clone()]; + let mut parent = vec![generation]; + for pin in bundle { + push_unique(&mut parent, pin, Arc::ptr_eq); + } + assert_eq!(parent.len(), 1); + } + #[test] fn creation_keeps_logical_allocator_separate_from_recording_backing() { let list = 0x7e57_a101usize as *mut c_void; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index a8e4a52cc2..8e53bf7ebf 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -668,10 +668,12 @@ struct RecipeInner { #[allow(dead_code)] // recorded-list generation pins are the next opt-in stage pub(super) struct NativeGeneration(Arc<Generation<ID3D12PipelineState>>); -#[allow(dead_code)] // recorded-list generation pins are the next opt-in stage impl NativeGeneration { + #[allow(dead_code)] // consumed by the later retirement diagnostics stage pub(super) fn id(&self) -> u64 { self.0.id } + #[allow(dead_code)] // exposed to focused generation-capture tests pub(super) fn raw(&self) -> usize { self.0.raw } + pub(super) fn same(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } } /// Rebuildable immutable inputs for one pipeline. The first build and any later rebuild use the @@ -1280,6 +1282,88 @@ mod used_tests { assert_eq!(slot.resident.as_ref().unwrap().id, 400); } + #[test] + fn capture_preserves_lazy_for_bind_wait_and_identity_choices() { + let standin = 0x7E57_C130usize; + let real = 0x7E57_C131usize; + let (go_tx, go_rx) = mpsc::channel(); + let (started_tx, started_rx) = mpsc::channel(); + submit_lazy(standin, true, Box::new(move || { + started_tx.send(()).unwrap(); + go_rx.recv().unwrap(); + real + }), 0); + + let (lazy, lazy_pin) = resolve_and_pin_mode(standin, ResolveMode::Lazy); + assert_eq!(lazy, standin); + assert!(lazy_pin.is_none()); + let (identity, identity_pin) = resolve_and_pin_if_enabled_identity(standin); + assert_eq!(identity, standin); + assert!(identity_pin.is_none()); + started_rx.recv().unwrap(); + let (result_tx, result_rx) = mpsc::channel(); + std::thread::scope(|scope| { + scope.spawn(|| result_tx.send(resolve_and_pin_mode(standin, ResolveMode::ForBind).0).unwrap()); + assert!(result_rx.recv_timeout(std::time::Duration::from_millis(10)).is_err(), "for-bind compute resolution must still wait"); + go_tx.send(()).unwrap(); + }); + assert_eq!(result_rx.recv().unwrap(), real); + assert_eq!(resolve_and_pin_mode(standin, ResolveMode::Wait).0, real); + assert_eq!(released(standin), real); + } + + #[test] + fn capture_never_resolves_against_a_reused_pending_address() { + let standin = 0x7E57_C138usize; + let old_real = 0x7E57_C139usize; + submit_lazy(standin, false, Box::new(move || old_real), 0); + let old = entry(standin).unwrap(); + let job = old.build.job.lock().unwrap().take().unwrap(); + complete(&old.build, job()); + let removed = PENDING.remove(standin).unwrap(); + + submit_lazy(standin, false, Box::new(|| 0x7E57_C13Ausize), 0); + let (chosen, pin) = resolve_and_pin_pending(standin, &old, ResolveMode::Lazy); + assert_eq!(chosen, old_real, "selection must use the retained Pending, not its reused map slot"); + assert!(pin.is_none()); + + assert_eq!(released(standin), 0); + drop(removed); + drop(old); + } + + #[test] + fn bound_wait_capture_pins_the_exact_published_generation() { + #[repr(C)] + struct FakePso { vtable: *const usize, refs: AtomicUsize } + unsafe extern "system" fn add_ref(this: *mut std::ffi::c_void) -> u32 { + (*(this as *mut FakePso)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + unsafe extern "system" fn release(this: *mut std::ffi::c_void) -> u32 { + (*(this as *mut FakePso)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + + let vtable = [0usize, add_ref as usize, release as usize]; + let mut fake = FakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut fake as *mut FakePso as usize; + let standin = 0x7E57_C140usize; + let recipe = Recipe::new(move || raw); + submit_recipe_keyed(standin, true, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let job = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, job()); + + let ((chosen, bound_unbuilt), pin) = resolve_wait_bound_and_pin(standin); + let pin = pin.expect("published recipe generation must be captured"); + assert_eq!((chosen, bound_unbuilt, pin.raw(), pin.id()), (raw, false, raw, 1)); + assert_eq!(fake.refs.load(Ordering::Relaxed), 2, "generation pin shares the recipe's exact COM owner"); + + drop(pin); + assert_eq!(released(standin), raw); + drop(pending); + assert_eq!(unsafe { release(raw as *mut std::ffi::c_void) }, 0); + } + #[test] fn a_panicking_pipeline_job_completes_failed_and_wakes_its_waiter() { let build = Arc::new(Build::new(Box::new(|| panic!("simulated pipeline panic")), false)); @@ -2498,28 +2582,89 @@ pub fn resolve_for_bind(pso: usize) -> usize { /// generation is chosen while holding `Build.done`, the same lock that publishes it and that /// `released` uses before giving up the original raw owner. Ordinary one-shot builds keep their /// existing resolution path and return no generation pin. -#[allow(dead_code)] // command-list generation capture is the next opt-in stage pub(super) fn resolve_and_pin_for_bind(pso: usize) -> (usize, Option<NativeGeneration>) { + resolve_and_pin_mode(pso, ResolveMode::ForBind) +} + +#[derive(Clone, Copy)] +enum ResolveMode { Lazy, Wait, ForBind } + +fn resolve_and_pin_mode(pso: usize, mode: ResolveMode) -> (usize, Option<NativeGeneration>) { let Some(p) = entry(pso) else { return (pso, None) }; - let Some(recipe) = p.build.recipe.as_ref() else { return (resolve_for_bind(pso), None) }; - p.note_use(); - if p.compute { - let _ = resolve_wait_pending(&p, pso, wait_budget()); - } else if p.build.real.load(Ordering::Acquire) == 0 { - schedule(&p.build, Priority::BoundSoon, false, None); - p.build.promote(Priority::Foreground); - } + resolve_and_pin_pending(pso, &p, mode) +} + +fn resolve_and_pin_pending(pso: usize, p: &Arc<Pending>, mode: ResolveMode) -> (usize, Option<NativeGeneration>) { + // Resolve directly against this retained Pending: a concurrent release/address reuse cannot + // make selection consult a new registry entry while validation still uses the old recipe. + let resolved = match mode { + ResolveMode::Lazy => resolve_pending(p, pso), + ResolveMode::Wait => { + p.note_use(); + resolve_wait_pending(p, pso, wait_budget()) + } + ResolveMode::ForBind if p.compute => { + p.note_use(); + resolve_wait_pending(p, pso, wait_budget()) + } + ResolveMode::ForBind => resolve_pending(p, pso), + }; + let bound_unbuilt = p.bound_unbuilt(pso, resolved); + pin_resolved(p, resolved, bound_unbuilt) +} + +fn pin_resolved(p: &Pending, resolved: usize, bound_unbuilt: bool) -> (usize, Option<NativeGeneration>) { + let Some(recipe) = p.build.recipe.as_ref() else { return (resolved, None) }; let _done = p.build.done.lock().unwrap(); - let real = p.build.real.load(Ordering::Acquire); - if real == 0 { - return (p.stand(pso), None); + let current = p.build.real.load(Ordering::Acquire); + if current == resolved { + return (resolved, recipe.pin(resolved)); + } + // Preserve a resolver's deliberate stand-in choice. If an eventual rebuild replaced a + // native generation between resolution and this lock, select and pin the current publication + // instead of returning an ownerless stale raw pointer. + if bound_unbuilt { + return (resolved, None); } - match recipe.pin(real) { - Some(generation) => (generation.raw(), Some(generation)), - None => (p.stand(pso), None), + match recipe.pin(current) { + Some(generation) => (current, Some(generation)), + None => (resolved, None), } } +/// Preserve the ordinary resolver exactly unless recipe rebuilding was explicitly enabled. +pub(super) fn resolve_and_pin_if_enabled(pso: usize) -> (usize, Option<NativeGeneration>) { + if rebuild_recipes_enabled() { resolve_and_pin_for_bind(pso) } else { (resolve_for_bind(pso), None) } +} + +pub(super) fn resolve_and_pin_if_enabled_lazy(pso: usize) -> (usize, Option<NativeGeneration>) { + if rebuild_recipes_enabled() { resolve_and_pin_mode(pso, ResolveMode::Lazy) } else { (resolve(pso), None) } +} + +pub(super) fn resolve_and_pin_if_enabled_wait(pso: usize) -> (usize, Option<NativeGeneration>) { + if rebuild_recipes_enabled() { resolve_and_pin_mode(pso, ResolveMode::Wait) } else { (resolve_wait(pso), None) } +} + +pub(super) fn resolve_and_pin_if_enabled_identity(pso: usize) -> (usize, Option<NativeGeneration>) { + (pso, None) +} + +pub(super) fn resolve_wait_bound_and_pin_if_enabled(pso: usize) -> ((usize, bool), Option<NativeGeneration>) { + if !rebuild_recipes_enabled() { + return (resolve_wait_bound(pso), None); + } + resolve_wait_bound_and_pin(pso) +} + +fn resolve_wait_bound_and_pin(pso: usize) -> ((usize, bool), Option<NativeGeneration>) { + let Some(p) = entry(pso) else { return ((pso, false), None) }; + p.note_use(); + let bound = resolve_wait_pending(&p, pso, wait_budget()); + let choice = (bound, p.bound_unbuilt(pso, bound)); + let (resolved, generation) = pin_resolved(&p, choice.0, choice.1); + ((resolved, choice.1), generation) +} + /// The title released stand-in `pso` for good: forget it (its address may come back for /// another object) and return its real pipeline to release when this is its last owner /// (0: another `Pending` owns the build, none, or still being built – the worker's result is diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index d9031520e3..b561258578 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3009,10 +3009,11 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro } pub(super) unsafe extern "system" fn dev_create_command_list_x(this: *mut c_void, mask: usize, ty: usize, alloc: usize, pso: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let pc_pso = super::console_list::pc_pso(pso as *mut c_void) as usize; + let (pc_pso, generation) = super::pso_async::resolve_and_pin_if_enabled_identity(super::console_list::pc_pso(pso as *mut c_void) as usize); let hr = dev_create_command_list(this, mask, ty, alloc, pc_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::list_x::on_console_list_create(*ppv, alloc, pc_pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + super::list_x::record_native_generation(*ppv as usize, generation); *ppv = super::console_list::create_with_allocator(*ppv, alloc as *mut c_void); } hr @@ -3109,6 +3110,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("DrawInstanced", cl_draw_instanced as usize), ("DrawIndexedInstanced", cl_draw_indexed_instanced as usize), ("SetPipelineState", cl_set_pipeline_state as usize), + ("ExecuteBundle", cl_execute_bundle as usize), ("SetMarker", cl_set_marker as usize), ("OMSetRenderTargets", cl_om_set_render_targets as usize), ("ClearRenderTargetView", cl_clear_rtv as usize), @@ -3201,11 +3203,13 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in let ext = *(this as *const usize); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot!(this, "Reset"))); - let resolved = super::pso_async::resolve_for_bind(initial_state as usize) as *mut c_void; + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled(initial_state as usize); + let resolved = resolved as *mut c_void; let hr = f(this, allocator, resolved); preserve_vtable(this, ext); if hr >= 0 { super::list_x::on_pc_reset(this); + super::list_x::record_native_generation(this as usize, generation); super::dred::reset(this); if !initial_state.is_null() { super::dred::mark_pipeline(this, initial_state as usize, resolved as usize); @@ -8642,12 +8646,19 @@ pub(super) unsafe fn bind_pipeline(this: *mut c_void, pso: *mut c_void) { unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot!(this, "SetPipelineState"))); - let bound = super::pso_async::resolve(pso as usize); + let bound = super::list_x::resolve_and_record_pipeline_lazy(this as usize, pso as usize); f(this, bound as *mut c_void); super::dred::mark_pipeline(this, pso as usize, bound); super::list_x::on_set_pipeline_state(this, pso as usize); } +unsafe extern "system" fn cl_execute_bundle(this: *mut c_void, bundle: *mut c_void) { + type F = unsafe extern "system" fn(*mut c_void, *mut c_void); + super::list_x::on_execute_bundle(this as usize, bundle as usize); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ExecuteBundle"))); + f(this, bundle); +} + /// The title's markers are counted for `XCL_DRED=1`'s pipeline labels (`dred`). unsafe extern "system" fn cl_set_marker(this: *mut c_void, metadata: u32, data: *const c_void, size: u32) { type F = unsafe extern "system" fn(*mut c_void, u32, *const c_void, u32); @@ -8659,7 +8670,7 @@ unsafe extern "system" fn cl_set_marker(this: *mut c_void, metadata: u32, data: unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ClearState"))); - let bound = super::pso_async::resolve_for_bind(pso as usize); + let bound = super::list_x::resolve_and_record_pipeline(this as usize, pso as usize); f(this, bound as *mut c_void); if !pso.is_null() { super::dred::mark_pipeline(this, pso as usize, bound); From c57709e4a1f03bf1371af11e301486989c8a592e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:54:02 -0800 Subject: [PATCH 206/265] D3D12.X: release sparse state during upload waits Sparse upload slot and staging-ring retirement waited for the GPU while holding the global sparse state, blocking commits, mappings and other state users behind a stalled queue. Return exact generation-bound wait tickets only at closed-list boundaries, wait under a lifetime gate with STATE released, then validate and rescan journaled CPU writes before recording more work. Signal failure remains terminal poison. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 363 ++++++++++++++++++++++------ 1 file changed, 288 insertions(+), 75 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index ae89913cdb..1b083a1651 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -209,6 +209,32 @@ enum SubmitResult { Unordered, } +enum UploadStep { + Done(PreparationOutcome), + Wait(WaitTicket), +} + +enum BeginSlot { + Ready(usize), + Wait(WaitTicket), + RetryRequired, +} + +#[derive(Clone, Copy)] +enum WaitKind { + Slot { index: usize, next_slot: usize, fence: u64 }, + Ring { front: (u64, u64), write: u64, submitted: u64, free: u64 }, +} + +struct WaitTicket { + state_generation: u64, + mapping_epoch: u64, + dev: ID3D12Device, + fence: ID3D12Fence, + target: u64, + kind: WaitKind, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) enum PreparationOutcome { Ready, @@ -233,6 +259,8 @@ struct RetiredTiles { } struct State { + generation: u64, + mapping_epoch: u64, dev: ID3D12Device, queue: ID3D12CommandQueue, fence: ID3D12Fence, @@ -507,6 +535,11 @@ fn plan_ring_chunk(ring_write: u64, want: usize, cap: usize) -> (u64, usize) { unsafe impl Send for State {} static STATE: Mutex<Option<State>> = Mutex::new(None); +static NEXT_STATE_GENERATION: AtomicU64 = AtomicU64::new(1); + +/// Upload allocators, lists and staging storage stay owned while `STATE` is released for a wait. +/// Lock order is `WAIT_GATES` → `UPLOAD_GATE` → `STATE`; initialization takes `PLACEMENT` first. +static UPLOAD_GATE: Mutex<()> = Mutex::new(()); /// A placement may release `STATE` while the driver creates its reserved resource. Keep sparse /// state replacement and another placement from crossing that exact-state transaction. @@ -722,6 +755,8 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { let _ = rb_alloc.SetName(windows::core::w!("xcl sparse readback allocator")); let _ = queue.SetName(windows::core::w!("xcl sparse queue")); Ok(State { + generation: NEXT_STATE_GENERATION.fetch_add(1, Ordering::Relaxed), + mapping_epoch: 0, dev: dev.clone(), queue, fence, @@ -766,6 +801,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { // its last buffers reaches `forget_buffer`, which takes the lock (#344) // (the queue first: `queue()` never answers with one older than the state's) let _placement = PLACEMENT.lock().unwrap(); + let _uploads = UPLOAD_GATE.lock().unwrap(); let old_queue = QUEUE.lock().unwrap().replace(s.queue.clone()); let mut state = STATE.lock().unwrap(); let old = state.replace(s); @@ -1072,26 +1108,49 @@ impl State { } } - /// Acquire the next upload command slot, waiting only if that slot's previous submission is - /// still executing on the GPU, then reset its allocator and list. - unsafe fn begin_slot(&mut self) -> Option<usize> { - self.begin_slot_with_timeout(5000) - } - - unsafe fn begin_slot_with_timeout(&mut self, timeout_ms: u32) -> Option<usize> { + /// Acquire the next upload command slot, or return a ticket to wait for without `STATE`. + unsafe fn begin_slot(&mut self) -> BeginSlot { let idx = self.next_slot; - self.next_slot = (self.next_slot + 1) % self.slots.len(); let fv = self.slots[idx].fence_val; if fv > 0 && self.fence.GetCompletedValue() < fv { - if !self.wait_for_ms(fv, timeout_ms) { - return None; - } - self.reclaim_ring(); + return BeginSlot::Wait(self.wait_ticket(fv, WaitKind::Slot { index: idx, next_slot: idx, fence: fv })); } + self.next_slot = (idx + 1) % self.slots.len(); let slot = &self.slots[idx]; - slot.alloc.Reset().ok()?; - slot.list.Reset(&slot.alloc, None).ok()?; - Some(idx) + if slot.alloc.Reset().is_err() || slot.list.Reset(&slot.alloc, None).is_err() { + return BeginSlot::RetryRequired; + } + BeginSlot::Ready(idx) + } + + fn wait_ticket(&self, target: u64, kind: WaitKind) -> WaitTicket { + WaitTicket { + state_generation: self.generation, + mapping_epoch: self.mapping_epoch, + dev: self.dev.clone(), + fence: self.fence.clone(), + target, + kind, + } + } + + fn wait_ticket_owns_upload(&self, ticket: &WaitTicket) -> bool { + if self.generation != ticket.state_generation || self.fence.as_raw() != ticket.fence.as_raw() || !self.uploads_ordered { + return false; + } + match ticket.kind { + WaitKind::Slot { index, next_slot, fence } => { + self.next_slot == next_slot && self.slots.get(index).is_some_and(|slot| slot.fence_val == fence) + } + WaitKind::Ring { front, write, submitted, free } => { + self.inflight.front().copied() == Some(front) + && self.ring_write == write && self.ring_submitted == submitted && self.ring_free == free + } + } + } + + fn wait_ticket_valid(&self, ticket: &WaitTicket) -> bool { + self.mapping_epoch == ticket.mapping_epoch && self.wait_ticket_owns_upload(ticket) } /// Close and submit upload slot `idx` asynchronously (NO CPU wait — callers order GPU work @@ -1310,17 +1369,21 @@ impl State { /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` /// (zero staging ring bytes consumed, zero CPU stall). - unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) -> PreparationOutcome { + unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) -> UploadStep { if runs.is_empty() { - return PreparationOutcome::Ready; + return UploadStep::Done(PreparationOutcome::Ready); } if !self.uploads_ordered { - return PreparationOutcome::ExecutedUntracked; + return UploadStep::Done(PreparationOutcome::ExecutedUntracked); } if !self.ensure_zero_buf() { - return PreparationOutcome::RetryRequired; + return UploadStep::Done(PreparationOutcome::RetryRequired); } - let Some(slot_idx) = self.begin_slot() else { return PreparationOutcome::RetryRequired }; + let slot_idx = match self.begin_slot() { + BeginSlot::Ready(index) => index, + BeginSlot::Wait(ticket) => return UploadStep::Wait(ticket), + BeginSlot::RetryRequired => return UploadStep::Done(PreparationOutcome::RetryRequired), + }; let mut last_wi: Option<usize> = None; let zero_buf = self.zero_buf.as_ref().unwrap(); let list = &self.slots[slot_idx].list; @@ -1345,24 +1408,24 @@ impl State { done += chunk; } } - self.submit_slot(slot_idx).into() + UploadStep::Done(self.submit_slot(slot_idx).into()) } /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via /// the 64 MiB ring staging buffer (zero CPU stall on the common path). - unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) -> PreparationOutcome { + unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) -> UploadStep { self.upload_dirty_with_timeout(runs, 5000) } - unsafe fn upload_dirty_with_timeout(&mut self, runs: &[(usize, usize)], wait_ms: u32) -> PreparationOutcome { + unsafe fn upload_dirty_with_timeout(&mut self, runs: &[(usize, usize)], _wait_ms: u32) -> UploadStep { if runs.is_empty() { - return PreparationOutcome::Ready; + return UploadStep::Done(PreparationOutcome::Ready); } if !self.uploads_ordered { - return PreparationOutcome::ExecutedUntracked; + return UploadStep::Done(PreparationOutcome::ExecutedUntracked); } let Some(p) = self.staging_ptr() else { - return PreparationOutcome::RetryRequired; + return UploadStep::Done(PreparationOutcome::RetryRequired); }; let mut open_slot: Option<usize> = None; let mut batch_start = self.ring_write; @@ -1383,7 +1446,7 @@ impl State { if open_slot.is_some() { self.ring_write = batch_start; } - return PreparationOutcome::RetryRequired; + return UploadStep::Done(PreparationOutcome::RetryRequired); } }, }; @@ -1401,27 +1464,26 @@ impl State { } SubmitResult::NotSubmitted => { self.ring_write = batch_start; - return PreparationOutcome::RetryRequired; + return UploadStep::Done(PreparationOutcome::RetryRequired); } - SubmitResult::Unordered => return PreparationOutcome::ExecutedUntracked, + SubmitResult::Unordered => return UploadStep::Done(PreparationOutcome::ExecutedUntracked), } self.reclaim_ring(); } while (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { let Some(&(fv, _)) = self.inflight.front() else { crate::xlog_warn!("sparse: the staging ring is full without a retirement fence; the unsubmitted CPU writes will be retried"); - return PreparationOutcome::RetryRequired; + return UploadStep::Done(PreparationOutcome::RetryRequired); }; - let reached = self.wait_for_ms(fv, wait_ms); - self.reclaim_ring(); - if !reached { - static RING_STALLS: AtomicU64 = AtomicU64::new(0); - let stalls = RING_STALLS.fetch_add(1, Ordering::Relaxed) + 1; - if stalls <= 4 || stalls.is_power_of_two() { - crate::xlog_warn!("sparse: staging ring reclaim timed out at fence {fv}; the unsubmitted CPU writes will be retried ({stalls} stalls)"); - } - return PreparationOutcome::RetryRequired; - } + return UploadStep::Wait(self.wait_ticket( + fv, + WaitKind::Ring { + front: *self.inflight.front().unwrap(), + write: self.ring_write, + submitted: self.ring_submitted, + free: self.ring_free, + }, + )); } } } @@ -1435,16 +1497,18 @@ impl State { } SubmitResult::NotSubmitted => { self.ring_write = batch_start; - return PreparationOutcome::RetryRequired; + return UploadStep::Done(PreparationOutcome::RetryRequired); } - SubmitResult::Unordered => return PreparationOutcome::ExecutedUntracked, + SubmitResult::Unordered => return UploadStep::Done(PreparationOutcome::ExecutedUntracked), } } let slot_idx = match open_slot { Some(idx) => idx, None => { - let Some(idx) = self.begin_slot() else { - return PreparationOutcome::RetryRequired; + let idx = match self.begin_slot() { + BeginSlot::Ready(index) => index, + BeginSlot::Wait(ticket) => return UploadStep::Wait(ticket), + BeginSlot::RetryRequired => return UploadStep::Done(PreparationOutcome::RetryRequired), }; batch_start = self.ring_write; open_slot = Some(idx); @@ -1465,12 +1529,12 @@ impl State { SubmitResult::Submitted => self.publish_hashes(&batch_updates), SubmitResult::NotSubmitted => { self.ring_write = batch_start; - return PreparationOutcome::RetryRequired; + return UploadStep::Done(PreparationOutcome::RetryRequired); } - SubmitResult::Unordered => return PreparationOutcome::ExecutedUntracked, + SubmitResult::Unordered => return UploadStep::Done(PreparationOutcome::ExecutedUntracked), } } - PreparationOutcome::Ready + UploadStep::Done(PreparationOutcome::Ready) } } @@ -1528,6 +1592,7 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz if ranges.is_empty() { return; } + let _uploads = UPLOAD_GATE.lock().unwrap(); let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); @@ -1562,6 +1627,8 @@ pub unsafe fn readback_now(va: usize, len: usize) { if len == 0 { return; } + let _uploads = UPLOAD_GATE.lock().unwrap(); + 'prepare: loop { let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; if s.window_index(va).is_none() { @@ -1572,9 +1639,17 @@ pub unsafe fn readback_now(va: usize, len: usize) { for &(a, n) in &zeroed { s.clear_sent_range(a, n); } - if s.upload_zeros(&zeroed) != PreparationOutcome::Ready { - s.to_zero.extend(zeroed); - return; + match s.upload_zeros(&zeroed) { + UploadStep::Done(PreparationOutcome::Ready) => {} + UploadStep::Wait(ticket) => { + s.to_zero.extend(zeroed); + drop(g); + if wait_upload_released(&ticket) { continue 'prepare } else { return } + } + UploadStep::Done(_) => { + s.to_zero.extend(zeroed); + return; + } } } // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` @@ -1598,11 +1673,18 @@ pub unsafe fn readback_now(va: usize, len: usize) { pg = tile_end; } if !dirty_runs.is_empty() { - if s.upload_dirty(&dirty_runs) != PreparationOutcome::Ready { - return; + match s.upload_dirty(&dirty_runs) { + UploadStep::Done(PreparationOutcome::Ready) => {} + UploadStep::Wait(ticket) => { + drop(g); + if wait_upload_released(&ticket) { continue 'prepare } else { return } + } + UploadStep::Done(_) => return, } } s.readback_ranges(&[(va, len)]); + return; + } } /// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that @@ -1678,6 +1760,7 @@ impl State { } pg = tile_end; } + self.mapping_epoch = self.mapping_epoch.wrapping_add(1); } /// `decommitted` with the state locked: the tiles that go are parked (`flush_parked` unmaps @@ -1696,6 +1779,7 @@ impl State { } } let tiles = decommit_tiles(&mut self.mapped, &self.pinned, &mut Vec::new(), &mut self.to_zero, a, n); + self.mapping_epoch = self.mapping_epoch.wrapping_add(1); if tiles.is_empty() { return; } @@ -1836,6 +1920,7 @@ impl State { let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); self.unmap_tiles(&r, b, &ts); } + self.mapping_epoch = self.mapping_epoch.wrapping_add(1); self.signal(); self.quarantine_tiles_for(tiles, queues, retiring, blocked); true @@ -1984,7 +2069,7 @@ pub fn mapped_ranges() -> Vec<(usize, usize)> { s.runs.clone().unwrap_or_default() } -const LOOK_FIELDS: usize = 13; +const LOOK_FIELDS: usize = 14; const ACTIVE_US: usize = 0; const REFRESH_WAIT_US: usize = 1; const WATCH_US: usize = 2; @@ -1998,6 +2083,7 @@ const SCAN_US: usize = 9; const UPLOAD_US: usize = 10; const RUNS: usize = 11; const TRANSFER_BYTES: usize = 12; +const UPLOAD_WAIT_US: usize = 13; /// One complete `XCL_ACTIVITY` look. It is built without shared updates, then published once so /// the reporting thread cannot split one look across adjacent intervals. @@ -2048,11 +2134,11 @@ pub fn look_delta(now: [u64; LOOK_FIELDS], before: [u64; LOOK_FIELDS]) -> [u64; /// Active foreground elapsed time and serialization wait before title submits in one interval. pub fn look_line(d: [u64; LOOK_FIELDS], secs: u64) -> String { - let [active, refresh_wait, watch, pages, looks, watched, ranges, queue_wait, maintenance, scan, upload, runs, transfer_bytes] = d; + let [active, refresh_wait, watch, pages, looks, watched, ranges, queue_wait, maintenance, scan, upload, runs, transfer_bytes, upload_wait] = d; let ms = |us: u64| us / 1000; - let sparse = queue_wait.saturating_add(maintenance).saturating_add(scan).saturating_add(upload); + let sparse = queue_wait.saturating_add(maintenance).saturating_add(scan).saturating_add(upload).saturating_add(upload_wait); format!( - "looks before submits ({secs} s): {looks} looks did {} ms active work ({:.1} % of the time) after {} ms waiting for the refresh turn: write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); sparse queue wait/fence+state/scan/upload {}/{}/{}/{} ms ({runs} runs, {:.1} MB zero/dirty bytes); other active work {} ms", + "looks before submits ({secs} s): {looks} looks did {} ms active work ({:.1} % of the time) after {} ms waiting for the refresh turn: write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); sparse queue wait/fence+state/scan/upload/ownership wait {}/{}/{}/{}/{} ms ({runs} runs, {:.1} MB zero/dirty bytes); other active work {} ms", ms(active), active as f64 / (secs.max(1) * 10_000) as f64, ms(refresh_wait), @@ -2063,6 +2149,7 @@ pub fn look_line(d: [u64; LOOK_FIELDS], secs: u64) -> String { ms(maintenance), ms(scan), ms(upload), + ms(upload_wait), transfer_bytes as f64 / (1 << 20) as f64, ms(active.saturating_sub(watch.saturating_add(sparse))) ) @@ -2105,6 +2192,21 @@ fn retry_journal(outcome: PreparationOutcome, mut deferred: Vec<usize>, runs: &[ deferred } +fn remember_metric_runs(seen: &mut BTreeMap<usize, usize>, runs: &[(usize, usize)]) { + for &(a, n) in runs { + early_add(seen, a, a.saturating_add(n)); + } +} + +fn note_transfer_metrics( + sample: Option<&mut LookSample>, seen: Option<&(BTreeMap<usize, usize>, BTreeMap<usize, usize>)>, +) { + let (Some(sample), Some((zero, dirty))) = (sample, seen) else { return }; + sample.add(RUNS, (zero.len() + dirty.len()) as u64); + let bytes = zero.iter().chain(dirty).fold(0usize, |sum, (&a, &b)| sum.saturating_add(b.saturating_sub(a))); + sample.add(TRANSFER_BYTES, bytes as u64); +} + fn rollback_queue_wait(waited: &mut FxHashMap<usize, u64>, queue: usize, value: u64, previous: Option<u64>) { if waited.get(&queue) != Some(&value) { return; @@ -2115,6 +2217,34 @@ fn rollback_queue_wait(waited: &mut FxHashMap<usize, u64>, queue: usize, value: } } +/// Wait with `STATE` released. `UPLOAD_GATE` keeps the ticket's allocator, list, staging and +/// destination owners alive; only an exact same-generation ticket may retire ring storage. +unsafe fn wait_upload_released(ticket: &WaitTicket) -> bool { + loop { + match crate::gpu::fence::wait(&ticket.fence, ticket.target, &ticket.dev, None, 5000) { + Ok(()) => break, + Err(crate::gpu::fence::FenceError::Timeout(_)) => { + crate::xlog_warn!("sparse: upload retirement fence {} is still pending; STATE remains released", ticket.target); + } + Err(e) => { + crate::xlog_warn!("sparse: upload retirement fence {} failed: {e}", ticket.target); + return false; + } + } + } + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return false }; + if !s.wait_ticket_owns_upload(ticket) { + return false; + } + // A concurrent commit/decommit/remap invalidates the mapping epoch. Do not apply the old + // ticket to ring state; the caller loops and rebuilds its upload from current mappings. + if s.wait_ticket_valid(ticket) { + s.reclaim_ring(); + } + true +} + /// Snapshot strong fence owners under `STATE`, then query them without it. A batch or a higher /// mark added while polling is checked against the same observation; a new fence has no /// observation and therefore remains quarantined. @@ -2137,14 +2267,21 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], let t0 = look.is_some().then(std::time::Instant::now); let queue_gate = WAIT_GATES.lock().unwrap().entry(q).or_default().clone(); let _queue_serial = queue_gate.lock().unwrap(); + let _uploads = UPLOAD_GATE.lock().unwrap(); let t_gated = t0.map(|_| std::time::Instant::now()); + if let (Some(sample), Some(t0), Some(t_gated)) = (look.as_deref_mut(), t0, t_gated) { + sample.add_time(QUEUE_WAIT_US, t_gated.duration_since(t0)); + } + let mut metric_runs = look.is_some().then(|| (BTreeMap::new(), BTreeMap::new())); + 'prepare: loop { + let t_started = t0.map(|_| std::time::Instant::now()); let observed = poll_retirement_fences(); let mut g = lock_state(); let Some(s) = g.as_mut() else { - if let (Some(sample), Some(t0), Some(t_gated)) = (look.as_deref_mut(), t0, t_gated) { - sample.add_time(QUEUE_WAIT_US, t_gated.duration_since(t0)); - sample.add_time(MAINTENANCE_US, t_gated.elapsed()); + if let (Some(sample), Some(t_started)) = (look.as_deref_mut(), t_started) { + sample.add_time(MAINTENANCE_US, t_started.elapsed()); } + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); return PreparationOutcome::Ready; }; // the title's work sees what was decommitted unmapped, as it was @@ -2212,33 +2349,63 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], let t_scanned = t0.map(|_| std::time::Instant::now()); // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. let mut outcome = PreparationOutcome::Ready; + let mut upload_wait = None; if !zero_runs.is_empty() { - outcome = s.upload_zeros(&zero_runs); + match s.upload_zeros(&zero_runs) { + UploadStep::Done(done) => outcome = done, + UploadStep::Wait(ticket) => { + outcome = PreparationOutcome::RetryRequired; + upload_wait = Some(ticket); + } + } if outcome != PreparationOutcome::Ready { s.to_zero.extend(zero_runs.iter().copied()); } } if outcome == PreparationOutcome::Ready && !dirty_runs.is_empty() { - outcome = s.upload_dirty(&dirty_runs); + match s.upload_dirty(&dirty_runs) { + UploadStep::Done(done) => outcome = done, + UploadStep::Wait(ticket) => { + outcome = PreparationOutcome::RetryRequired; + upload_wait = Some(ticket); + } + } } s.retry_pages = retry_journal(outcome, deferred, &dirty_runs); - if let (Some(sample), Some(t0), Some(t_gated), Some(t_maintained), Some(t_scanned)) = - (look.as_deref_mut(), t0, t_gated, t_maintained, t_scanned) + if let Some((zero, dirty)) = metric_runs.as_mut() { + remember_metric_runs(zero, &zero_runs); + remember_metric_runs(dirty, &dirty_runs); + } + if let (Some(sample), Some(t_started), Some(t_maintained), Some(t_scanned)) = + (look.as_deref_mut(), t_started, t_maintained, t_scanned) { let t_uploaded = std::time::Instant::now(); - sample.add_time(QUEUE_WAIT_US, t_gated.duration_since(t0)); - sample.add_time(MAINTENANCE_US, t_maintained.duration_since(t_gated)); + sample.add_time(MAINTENANCE_US, t_maintained.duration_since(t_started)); sample.add_time(SCAN_US, t_scanned.duration_since(t_maintained)); sample.add_time(UPLOAD_US, t_uploaded.duration_since(t_scanned)); - sample.add(RUNS, (zero_runs.len() + dirty_runs.len()) as u64); - let bytes = zero_runs.iter().chain(&dirty_runs).fold(0usize, |sum, run| sum.saturating_add(run.1)); - sample.add(TRANSFER_BYTES, bytes as u64); } dirty_runs.clear(); s.scratch_runs = dirty_runs; + if let Some(ticket) = upload_wait { + drop(g); + drop(observed); + let wait_started = t0.map(|_| std::time::Instant::now()); + if !wait_upload_released(&ticket) { + if let (Some(sample), Some(wait_started)) = (look.as_deref_mut(), wait_started) { + sample.add_time(UPLOAD_WAIT_US, wait_started.elapsed()); + } + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::RetryRequired; + } + if let (Some(sample), Some(wait_started)) = (look.as_deref_mut(), wait_started) { + sample.add_time(UPLOAD_WAIT_US, wait_started.elapsed()); + } + continue 'prepare; + } if outcome != PreparationOutcome::Ready { drop(g); drop(observed); + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); return outcome; } let value = s.value; @@ -2252,11 +2419,14 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], if let Some(s) = g.as_mut().filter(|s| s.fence.as_raw() == fence.as_raw() && s.waited.get(&q) == Some(&value)) { rollback_queue_wait(&mut s.waited, q, value, previous); } + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); return PreparationOutcome::RetryRequired; } super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &fence, value); } - PreparationOutcome::Ready + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::Ready; + } } /// A buffer the title places at `va` in a sparse window (`bytes` long, `desc` the PC @@ -2335,6 +2505,7 @@ unsafe fn place_buffer_in( let holes = query_tile_holes(t); (holes, !holes) }); + s.mapping_epoch = s.mapping_epoch.wrapping_add(1); let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|e| (t, e.pool))).collect(); s.map_tiles(&res, start, &tiles); if s.buffers.contains_key(&(raw as usize)) { @@ -2425,10 +2596,11 @@ mod tests { 40_000, 90, 96 << 20, + 20_000, ], 2); assert!(line.contains("240 looks did 830 ms active work (41.5 % of the time) after 120 ms waiting"), "{line}"); assert!(line.contains("write-watch 610 ms (1641.0 MB in 69.0 ranges/look, 4800 pages written)"), "{line}"); - assert!(line.contains("sparse queue wait/fence+state/scan/upload 10/30/40/40 ms (90 runs, 96.0 MB zero/dirty bytes); other active work 100 ms"), "{line}"); + assert!(line.contains("sparse queue wait/fence+state/scan/upload/ownership wait 10/30/40/40/20 ms (90 runs, 96.0 MB zero/dirty bytes); other active work 80 ms"), "{line}"); let idle = look_line([0; LOOK_FIELDS], 2); assert!(idle.contains("0 looks did 0 ms active work (0.0 % of the time) after 0 ms waiting"), "{idle}"); assert!(idle.contains("0.0 MB in 0.0 ranges/look"), "{idle}"); @@ -2439,6 +2611,20 @@ mod tests { assert_eq!(look_delta([0; LOOK_FIELDS], [u64::MAX; LOOK_FIELDS]), [1; LOOK_FIELDS]); } + #[test] + fn retried_upload_ranges_are_counted_once() { + let mut zero = BTreeMap::new(); + let mut dirty = BTreeMap::new(); + remember_metric_runs(&mut zero, &[(0x1000, 0x1000)]); + remember_metric_runs(&mut zero, &[(0x1000, 0x1000)]); + remember_metric_runs(&mut dirty, &[(0x4000, 0x1000)]); + remember_metric_runs(&mut dirty, &[(0x4000, 0x2000)]); + let mut sample = LookSample::default(); + note_transfer_metrics(Some(&mut sample), Some(&(zero, dirty))); + assert_eq!(sample.0[RUNS], 2); + assert_eq!(sample.0[TRANSFER_BYTES], 0x3000); + } + #[test] fn activity_look_publishes_one_complete_sample() { let mut total = [10; LOOK_FIELDS]; @@ -2707,6 +2893,8 @@ mod tests { let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); rb_list.Close().expect("rb_list close"); let mut s = State { + generation: 1, + mapping_epoch: 0, dev, queue, fence, @@ -3027,6 +3215,8 @@ mod tests { rb_list.Close().expect("rb_list close"); let mut s = State { + generation: 1, + mapping_epoch: 0, dev, queue, fence, @@ -3129,6 +3319,8 @@ mod tests { rb_list.Close().expect("rb_list close"); let mut s = State { + generation: 1, + mapping_epoch: 0, dev, queue, fence, @@ -3267,6 +3459,8 @@ mod tests { rb_list.Close().expect("rb_list close"); let s = State { + generation: 1, + mapping_epoch: 0, dev, queue, fence, @@ -3307,7 +3501,7 @@ mod tests { } #[test] - fn a_stalled_upload_ring_returns_without_publishing_hashes() { + fn a_stalled_upload_ring_yields_without_publishing_hashes() { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; unsafe { @@ -3326,9 +3520,14 @@ mod tests { s.ring_submitted = STAGING as u64; s.ring_free = 0; s.inflight.push_back((s.value + 1, STAGING as u64)); - let started = std::time::Instant::now(); - assert_eq!(s.upload_dirty_with_timeout(&[(base + CHUNK, 2 * CHUNK)], 20), PreparationOutcome::RetryRequired); - assert!(started.elapsed() < std::time::Duration::from_secs(2), "a stalled fence kept upload_dirty in its ring loop"); + let ticket = match s.upload_dirty_with_timeout(&[(base + CHUNK, 2 * CHUNK)], 20) { + UploadStep::Wait(ticket) => ticket, + UploadStep::Done(_) => panic!("a full ring did not return its retirement ticket"), + }; + assert_eq!(ticket.target, s.value + 1); + assert!(s.wait_ticket_valid(&ticket)); + s.mapping_epoch += 1; + assert!(!s.wait_ticket_valid(&ticket), "a remapped destination accepted an old upload ticket"); let after = s.mapped[&base].sent[0].as_ref().unwrap(); assert_eq!(after.as_ref(), &before, "a failed upload changed the published hash state"); @@ -3337,7 +3536,21 @@ mod tests { list.Close().unwrap(); s.slots.push(UploadSlot { alloc, list, fence_val: s.value + 1 }); s.next_slot = 0; - assert_eq!(s.begin_slot_with_timeout(20), None, "a timed-out slot must not reset its in-flight allocator"); + let before_slot = s.next_slot; + let ticket = match s.begin_slot() { + BeginSlot::Wait(ticket) => ticket, + _ => panic!("a busy slot did not return its retirement ticket"), + }; + assert_eq!(s.next_slot, before_slot, "a busy slot advanced before its fence completed"); + assert!(matches!(ticket.kind, WaitKind::Slot { index: 0, next_slot: 0, .. })); + assert!(s.wait_ticket_owns_upload(&ticket)); + s.generation += 1; + assert!(!s.wait_ticket_owns_upload(&ticket), "a replacement state accepted an old upload ticket"); + s.uploads_ordered = false; + assert!(matches!( + s.upload_dirty_with_timeout(&[(base + CHUNK, CHUNK)], 20), + UploadStep::Done(PreparationOutcome::ExecutedUntracked) + )); drop(s); assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); From c77b48496043fcb4009f2a4734887a61bf561f3d Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:06:24 -0800 Subject: [PATCH 207/265] D3D12.X: serialize native PSO generation rebuilds Retained recipes need one atomic replacement path before any eviction policy can use them. Coalesce overlapping rebuild requests, keep the current generation on failure, publish replacements under the build lock, and abandon new results when the last title owner disappears during the driver build. No policy calls this foundation yet. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 275 ++++++++++++++++++++++++- 1 file changed, 271 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 8e53bf7ebf..73f667716f 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -465,7 +465,7 @@ fn complete(build: &Arc<Build>, real: usize) { if !orphan { if real != 0 { if let Some(recipe) = &build.recipe { - replaced_generation = recipe.publish(real); + replaced_generation = recipe.publish(real).1; } } build.real.store(real, Ordering::Release); @@ -482,6 +482,67 @@ fn complete(build: &Arc<Build>, real: usize) { } forget_in_flight(build); } + +/// Result shared by callers that requested the same overlapping recipe rebuild. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RebuildResult { + NotReady, + Failed, + Abandoned, + Published { generation: u64 }, +} + +/// Build and atomically publish one replacement generation. This remains deliberately uncalled +/// until submitted recording pins are retained to exact GPU retirement receipts: publication is +/// safe, but a policy must not make an old generation reclaimable while the GPU can still use it. +#[allow(dead_code)] +fn rebuild_once(build: &Build) -> Option<RebuildResult> { + let recipe = build.recipe.as_ref()?; + { + let done = build.done.lock().unwrap(); + if !*done { + return Some(RebuildResult::NotReady); + } + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + return Some(RebuildResult::Abandoned); + } + } + match recipe.begin_rebuild() { + RebuildTurn::Follower(result) => return Some(result), + RebuildTurn::Leader => {} + } + + // Do expensive driver work without Build.done or the recipe state held. Binds keep using the + // current immutable generation throughout the rebuild. + let raw = run_job(recipe.initial_job()); + let mut replaced_generation = None; + let mut replaced_raw = 0; + let result = if raw == 0 { + RebuildResult::Failed + } else { + let _done = build.done.lock().unwrap(); + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + RebuildResult::Abandoned + } else { + let (generation, replaced) = recipe.publish(raw); + replaced_generation = replaced; + replaced_raw = build.real.swap(raw, Ordering::AcqRel); + build.completed_frame.store(super::present::presents(), Ordering::Relaxed); + RebuildResult::Published { generation: generation.id() } + } + }; + + // Publish the result before COM Release, which can re-enter pipeline bookkeeping. Never drop + // either old owner under Build.done or while this attempt is still blocking followers. + recipe.finish_rebuild(result); + drop(replaced_generation); + if matches!(result, RebuildResult::Published { .. }) { + release(replaced_raw); + } else if raw != 0 { + release(raw); + } + Some(result) +} static BUILT: AtomicUsize = AtomicUsize::new(0); static FAILED: AtomicUsize = AtomicUsize::new(0); static QUEUED_BUILDS: AtomicUsize = AtomicUsize::new(0); @@ -660,6 +721,22 @@ impl<T> GenerationSlot<T> { struct RecipeInner { build: Box<dyn Fn() -> usize + Send + Sync>, generation: Mutex<GenerationSlot<ID3D12PipelineState>>, + rebuild: Mutex<RebuildState>, + rebuild_done: Condvar, +} + +#[derive(Default)] +struct RebuildState { + active: bool, + completed: u64, + waiters: usize, + last: Option<RebuildResult>, +} + +#[derive(Debug)] +enum RebuildTurn { + Leader, + Follower(RebuildResult), } /// One immutable native pipeline generation. Its strong owner keeps the exact object alive even @@ -684,7 +761,12 @@ pub(super) struct Recipe(Arc<RecipeInner>); impl Recipe { pub(super) fn new(build: impl Fn() -> usize + Send + Sync + 'static) -> Self { - Self(Arc::new(RecipeInner { build: Box::new(build), generation: Mutex::new(GenerationSlot::default()) })) + Self(Arc::new(RecipeInner { + build: Box::new(build), + generation: Mutex::new(GenerationSlot::default()), + rebuild: Mutex::new(RebuildState::default()), + rebuild_done: Condvar::new(), + })) } fn run(&self) -> usize { @@ -693,10 +775,11 @@ impl Recipe { /// Publish before `Build.real` becomes visible. The returned generation owns one independent /// COM reference; the raw result remains the existing `Build.real` owner. - fn publish(&self, raw: usize) -> Option<NativeGeneration> { + fn publish(&self, raw: usize) -> (NativeGeneration, Option<NativeGeneration>) { let p = raw as *mut std::ffi::c_void; let owner = unsafe { ID3D12PipelineState::from_raw_borrowed(&p) }.expect("non-null pipeline result").clone(); - self.0.generation.lock().unwrap().publish(raw, owner).1.map(NativeGeneration) + let (generation, replaced) = self.0.generation.lock().unwrap().publish(raw, owner); + (NativeGeneration(generation), replaced.map(NativeGeneration)) } fn pin(&self, raw: usize) -> Option<NativeGeneration> { @@ -707,6 +790,40 @@ impl Recipe { let recipe = self.clone(); Box::new(move || recipe.run()) } + + fn begin_rebuild(&self) -> RebuildTurn { + let mut state = self.0.rebuild.lock().unwrap(); + loop { + if !state.active && state.waiters == 0 { + state.active = true; + return RebuildTurn::Leader; + } + if state.active { + let completed = state.completed; + state.waiters += 1; + while state.completed == completed { + state = self.0.rebuild_done.wait(state).unwrap(); + } + let result = state.last.expect("completed rebuild without a result"); + state.waiters -= 1; + if state.waiters == 0 { + self.0.rebuild_done.notify_all(); + } + return RebuildTurn::Follower(result); + } + // Followers of the completed attempt must consume `last` before another leader can + // overwrite it. A request arriving during this drain starts (or joins) the next one. + state = self.0.rebuild_done.wait(state).unwrap(); + } + } + + fn finish_rebuild(&self, result: RebuildResult) { + let mut state = self.0.rebuild.lock().unwrap(); + state.last = Some(result); + state.active = false; + state.completed = state.completed.checked_add(1).expect("pipeline rebuild serial exhausted"); + self.0.rebuild_done.notify_all(); + } } /// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. @@ -1212,6 +1329,20 @@ fn preload_enabled() -> bool { mod used_tests { use super::*; + #[repr(C)] + struct RebuildFakePso { + vtable: *const usize, + refs: AtomicUsize, + } + + unsafe extern "system" fn rebuild_fake_add_ref(this: *mut std::ffi::c_void) -> u32 { + (*(this as *mut RebuildFakePso)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + + unsafe extern "system" fn rebuild_fake_release(this: *mut std::ffi::c_void) -> u32 { + (*(this as *mut RebuildFakePso)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + #[test] fn rebuild_recipe_gate_requires_exact_one() { assert!(recipe_gate_value(Some("1"))); @@ -1282,6 +1413,142 @@ mod used_tests { assert_eq!(slot.resident.as_ref().unwrap().id, 400); } + #[test] + fn overlapping_recipe_rebuild_requests_share_one_result() { + let recipe = Recipe::new(|| 0); + assert!(matches!(recipe.begin_rebuild(), RebuildTurn::Leader)); + let follower_recipe = recipe.clone(); + let follower = std::thread::spawn(move || follower_recipe.begin_rebuild()); + let started = std::time::Instant::now(); + loop { + if recipe.0.rebuild.lock().unwrap().waiters == 1 { + break; + } + assert!(started.elapsed() < std::time::Duration::from_secs(2), "follower did not join the active rebuild"); + std::thread::yield_now(); + } + let result = RebuildResult::Published { generation: 7 }; + recipe.finish_rebuild(result); + assert!(matches!(follower.join().unwrap(), RebuildTurn::Follower(r) if r == result)); + assert_eq!(recipe.0.rebuild.lock().unwrap().completed, 1); + } + + #[test] + fn next_leader_waits_for_prior_followers_to_consume_their_result() { + let recipe = Recipe::new(|| 0); + let first = RebuildResult::Published { generation: 11 }; + { + // Deterministically model a completed attempt whose notified follower has not yet + // reacquired the mutex. `last` must remain immutable until that waiter drains. + let mut state = recipe.0.rebuild.lock().unwrap(); + state.completed = 1; + state.last = Some(first); + state.waiters = 1; + } + let next_recipe = recipe.clone(); + let (leader_tx, leader_rx) = mpsc::channel(); + let next = std::thread::spawn(move || leader_tx.send(next_recipe.begin_rebuild()).unwrap()); + assert!(leader_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), "a new leader crossed an undrained prior follower"); + + let consumed = { + let mut state = recipe.0.rebuild.lock().unwrap(); + let result = state.last.unwrap(); + state.waiters = 0; + recipe.0.rebuild_done.notify_all(); + result + }; + assert_eq!(consumed, first); + assert!(matches!(leader_rx.recv().unwrap(), RebuildTurn::Leader)); + recipe.finish_rebuild(RebuildResult::Published { generation: 12 }); + next.join().unwrap(); + } + + #[test] + fn failed_rebuild_keeps_current_generation_and_success_replaces_it() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut second = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let second_raw = &mut second as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let recipe = Recipe::new(move || build_next.load(Ordering::Acquire)); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + assert_eq!((build.real.load(Ordering::Acquire), first.refs.load(Ordering::Relaxed)), (first_raw, 2)); + + next.store(0, Ordering::Release); + assert_eq!(rebuild_once(&build), Some(RebuildResult::Failed)); + assert_eq!(build.real.load(Ordering::Acquire), first_raw); + assert_eq!(recipe.pin(first_raw).unwrap().id(), 1); + + next.store(second_raw, Ordering::Release); + assert_eq!(rebuild_once(&build), Some(RebuildResult::Published { generation: 2 })); + assert_eq!(build.real.load(Ordering::Acquire), second_raw); + assert_eq!(first.refs.load(Ordering::Relaxed), 0, "both superseded owners release outside publication locks"); + assert_eq!(second.refs.load(Ordering::Relaxed), 2); + + let final_raw = build.real.swap(0, Ordering::AcqRel); + drop(build); + drop(recipe); + assert_eq!(second.refs.load(Ordering::Relaxed), 1); + release(final_raw); + assert_eq!(second.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn release_during_rebuild_abandons_and_releases_the_new_raw() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let block = Arc::new((Mutex::new((false, false)), Condvar::new())); + let build_block = block.clone(); + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let recipe = Recipe::new(move || { + let mut state = build_block.0.lock().unwrap(); + if state.0 { + state.1 = true; + build_block.1.notify_all(); + while state.0 { + state = build_block.1.wait(state).unwrap(); + } + } + build_next.load(Ordering::Acquire) + }); + let standin = 0x7E57_C150usize; + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + + next.store(replacement_raw, Ordering::Release); + block.0.lock().unwrap().0 = true; + let rebuilding = pending.build.clone(); + let thread = std::thread::spawn(move || rebuild_once(&rebuilding)); + { + let mut state = block.0.lock().unwrap(); + while !state.1 { + state = block.1.wait(state).unwrap(); + } + } + let old_raw = released(standin); + release(old_raw); + { + let mut state = block.0.lock().unwrap(); + state.0 = false; + block.1.notify_all(); + } + assert_eq!(thread.join().unwrap(), Some(RebuildResult::Abandoned)); + assert_eq!(pending.build.real.load(Ordering::Acquire), 0); + assert_eq!(replacement.refs.load(Ordering::Relaxed), 0, "an abandoned new raw leaked"); + drop(pending); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + #[test] fn capture_preserves_lazy_for_bind_wait_and_identity_choices() { let standin = 0x7E57_C130usize; From ae303f65fcab1d4c427945461e1227626ea0656b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:08:29 -0800 Subject: [PATCH 208/265] D3D12.X: retire native PSO generation pins Keep exact native pipeline generation owners through GPU completion using the same strong submission receipt already requested for descriptor epochs. Executed work without a receipt retains its pins permanently; ordinary submissions without opt-in pins keep the marker-free path. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 108 ++++++++++++++-- crates/xcl/src/hle/d3d12x/pso_async.rs | 170 ++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 3 + 3 files changed, 266 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ca48c66a09..d82c392607 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -983,7 +983,7 @@ struct KickoffEffects { uses_shared_view_heap: bool, write64_signals: Vec<(u64, u64)>, cpu_writes: Vec<super::cpu_writes::Write>, - _native_generations: Vec<super::pso_async::NativeGeneration>, + native_generations: Vec<super::pso_async::NativeGeneration>, } fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { @@ -995,7 +995,7 @@ fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { uses_shared_view_heap: std::mem::take(&mut state.uses_shared_view_heap), write64_signals: state.clear_write64_signals(), cpu_writes: std::mem::take(&mut state.cpu_writes), - _native_generations: std::mem::take(&mut state.native_generations), + native_generations: std::mem::take(&mut state.native_generations), }; state.written_ranges.clear(); state.segment_write_producers.clear(); @@ -1006,6 +1006,30 @@ fn take_kickoff_effects_before_close(state: &mut ListState, has_fail_closed_stan (!has_fail_closed_standby).then(|| take_kickoff_effects(state)) } +fn restore_unique<T>(destination: Option<&mut Vec<T>>, pins: Vec<T>, same: impl Fn(&T, &T) -> bool) -> Result<(), Vec<T>> { + let Some(destination) = destination else { return Err(pins) }; + for pin in pins { + push_unique(destination, pin, &same); + } + Ok(()) +} + +fn restore_kickoff_native_generations(list: usize, pins: Vec<super::pso_async::NativeGeneration>) { + if pins.is_empty() { + return; + } + let mut lists = LISTS.lock().unwrap(); + let restored = restore_unique( + lists.as_mut().and_then(|lists| lists.get_mut(&list)).map(|state| &mut state.native_generations), + pins, + super::pso_async::NativeGeneration::same, + ); + drop(lists); + if let Err(pins) = restored { + super::pso_async::poison_native_generations(pins.iter()); + } +} + fn settle_kickoff_standby<T, U>( standby: Option<(T, U)>, reset_succeeded: bool, @@ -1123,7 +1147,7 @@ pub(super) struct SegmentEffects { texture_transitions: Vec<super::title_textures::Transition>, uses_shared_view_heap: bool, cpu_writes: Vec<super::cpu_writes::Write>, - _native_generations: Vec<super::pso_async::NativeGeneration>, + native_generations: Vec<super::pso_async::NativeGeneration>, } impl SegmentEffects { @@ -1163,7 +1187,7 @@ impl SubmissionPlan { texture_transitions: s.texture_transitions.clone(), uses_shared_view_heap: s.uses_shared_view_heap, cpu_writes: s.cpu_writes.clone(), - _native_generations: s.native_generations.clone(), + native_generations: s.native_generations.clone(), }) .unwrap_or_default() }) @@ -1232,6 +1256,14 @@ impl<'a> SubmissionChunk<'a> { self.effects.iter().any(|effects| effects.uses_shared_view_heap) } + pub(super) fn native_generations(self) -> impl Clone + Iterator<Item = &'a super::pso_async::NativeGeneration> { + self.effects.iter().flat_map(|effects| effects.native_generations.iter()) + } + + pub(super) fn has_native_generations(self) -> bool { + self.effects.iter().any(|effects| !effects.native_generations.is_empty()) + } + pub(super) unsafe fn submit_effects(self, queue: *mut c_void) -> Option<super::cpu_writes::Completion> { // The immutable submission plan is now the production path, so record execution here // after its caller has successfully submitted this exact chunk. The legacy @@ -1244,18 +1276,20 @@ impl<'a> SubmissionChunk<'a> { } } -/// Submit one exact title chunk, adding a retirement receipt only when an opt-in recording can -/// read the shared view heap. The ordinary path stays on `SubmissionGate::submit`, which avoids -/// an extra queue marker when descriptor-epoch tracking is disabled or the chunk does not use it. -pub(super) unsafe fn submit_title_chunk( +/// Submit one exact title chunk, adding one shared retirement receipt when an opt-in recording +/// can read the shared view heap or owns native pipeline generation pins. The ordinary path stays +/// on `SubmissionGate::submit`, avoiding a marker, allocation or lock when neither applies. +pub(super) unsafe fn submit_title_chunk<'a>( gate: &mut super::alloc_pool::SubmissionGate, queue: *mut c_void, lists: &[*mut c_void], protect_shared_view: bool, + protect_native_generations: bool, + native_generations: impl Iterator<Item = &'a super::pso_async::NativeGeneration>, prepare: impl FnOnce(), execute: impl FnOnce(), ) -> bool { - if !protect_shared_view { + if !protect_shared_view && !protect_native_generations { return gate.submit(queue, lists, prepare, execute); } let mut epoch = None; @@ -1263,7 +1297,9 @@ pub(super) unsafe fn submit_title_chunk( queue, lists, || { - epoch = Some(super::vram::reserve_shared_view_epoch()); + if protect_shared_view { + epoch = Some(super::vram::reserve_shared_view_epoch()); + } prepare(); }, execute, @@ -1276,11 +1312,31 @@ pub(super) unsafe fn submit_title_chunk( false } super::alloc_pool::ReceiptedSubmission::Executed(receipt) => { - super::vram::attach_shared_view_epoch(epoch.expect("executed shared-view submission without an epoch"), receipt); + if protect_native_generations { + if protect_shared_view { + super::vram::attach_shared_view_epoch( + epoch.expect("executed shared-view submission without an epoch"), + receipt.clone(), + ); + } + super::pso_async::retire_native_generations(receipt, native_generations); + } else if protect_shared_view { + super::vram::attach_shared_view_epoch( + epoch.expect("executed shared-view submission without an epoch"), + receipt, + ); + } true } super::alloc_pool::ReceiptedSubmission::ExecutedUntracked => { - super::vram::poison_shared_view_epoch(epoch.expect("executed shared-view submission without an epoch")); + if protect_shared_view { + super::vram::poison_shared_view_epoch( + epoch.expect("executed shared-view submission without an epoch"), + ); + } + if protect_native_generations { + super::pso_async::poison_native_generations(native_generations); + } true } } @@ -4305,6 +4361,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let close_hr = pc::<unsafe extern "system" fn(*mut c_void) -> i32>(this, PC_CLOSE)(this); real::preserve_vtable(this, ext); if close_hr < 0 { + if let Some(effects) = preclose_effects { + restore_kickoff_native_generations(this as usize, effects.native_generations); + } if let Some((wrapper, standby)) = standby { super::title_list::fail_closed(wrapper, this, standby, true); } @@ -4313,12 +4372,12 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let effects = match preclose_effects { Some(effects) => effects, None => LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).map(take_kickoff_effects).unwrap_or(KickoffEffects { - waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), uses_shared_view_heap: false, write64_signals: Vec::new(), cpu_writes: Vec::new(), _native_generations: Vec::new(), + waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), uses_shared_view_heap: false, write64_signals: Vec::new(), cpu_writes: Vec::new(), native_generations: Vec::new(), }), }; let KickoffEffects { waits, sparse_writes, texture_writes, texture_transitions, uses_shared_view_heap, - write64_signals, cpu_writes, _native_generations, + write64_signals, cpu_writes, native_generations, } = effects; if let Some(wrapper) = super::title_list::wrapper_of(this) { record_deferred(wrapper); @@ -4336,6 +4395,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let mut wait_after_cpu_write = false; let mut gate = super::alloc_pool::SubmissionGate::default(); let track_shared_view_epochs = super::vram::srv_tracking_enabled(); + let track_native_generation_receipts = super::pso_async::rebuild_recipes_enabled(); if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { let plan = submission_plan(prior); @@ -4349,6 +4409,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { q_raw, lists, track_shared_view_epochs && chunk.uses_shared_view_heap(), + track_native_generation_receipts && chunk.has_native_generations(), + chunk.native_generations(), || {}, || exec(q_raw, lists.len() as u32, lists.as_ptr()), ) { @@ -4383,6 +4445,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { q_raw, &one, track_shared_view_epochs && uses_shared_view_heap, + track_native_generation_receipts && !native_generations.is_empty(), + native_generations.iter(), || {}, || exec(q_raw, 1, one.as_ptr()), ); @@ -5732,6 +5796,22 @@ mod tests { assert_eq!(Arc::strong_count(&submission_plan[0]), 1, "the immutable plan must own the submitted generation"); } + #[test] + fn close_failure_restores_exact_generation_carriers_or_returns_them_fail_closed() { + let generation = Arc::new(()); + let mut recording = vec![generation.clone()]; + restore_unique( + Some(&mut recording), + vec![generation.clone(), generation.clone()], + Arc::ptr_eq, + ).unwrap(); + assert_eq!(recording.len(), 1, "restoring a retryable recording duplicated its exact generation"); + + let stranded = restore_unique::<Arc<()>>(None, vec![generation.clone()], Arc::ptr_eq).unwrap_err(); + assert_eq!(stranded.len(), 1, "a missing list state dropped its fail-closed carrier"); + assert!(Arc::ptr_eq(&stranded[0], &generation)); + } + #[test] fn bundle_snapshot_deduplicates_into_parent_recording() { let generation = Arc::new(()); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 73f667716f..e578614241 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -742,7 +742,6 @@ enum RebuildTurn { /// One immutable native pipeline generation. Its strong owner keeps the exact object alive even /// after the title releases its stand-in or a later rebuild publishes the same raw address. #[derive(Clone)] -#[allow(dead_code)] // recorded-list generation pins are the next opt-in stage pub(super) struct NativeGeneration(Arc<Generation<ID3D12PipelineState>>); impl NativeGeneration { @@ -753,6 +752,91 @@ impl NativeGeneration { pub(super) fn same(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } } +struct GenerationRetirements<G, R> { + pending: Vec<(R, Vec<G>)>, + poisoned: Vec<G>, +} + +impl<G, R> GenerationRetirements<G, R> { + const fn new() -> Self { + Self { pending: Vec::new(), poisoned: Vec::new() } + } + + fn sweep(&mut self, complete: impl Fn(&R) -> bool) -> Vec<(R, Vec<G>)> { + let mut retired = Vec::new(); + let mut i = 0; + while i < self.pending.len() { + if complete(&self.pending[i].0) { + retired.push(self.pending.swap_remove(i)); + } else { + i += 1; + } + } + retired + } + + fn retire_pending(&mut self, receipt: R, pins: Vec<G>, complete: impl Fn(&R) -> bool) -> Vec<(R, Vec<G>)> { + if !pins.is_empty() { + self.pending.push((receipt, pins)); + } + self.sweep(complete) + } + + fn poison(&mut self, pins: Vec<G>, same: impl Fn(&G, &G) -> bool) { + for pin in pins { + if !self.poisoned.iter().any(|old| same(old, &pin)) { + self.poisoned.push(pin); + } + } + } +} + +fn dedup_generations<G>(pins: impl Iterator<Item = G>, same: impl Fn(&G, &G) -> bool) -> Vec<G> { + let mut unique = Vec::new(); + for pin in pins { + if !unique.iter().any(|old| same(old, &pin)) { + unique.push(pin); + } + } + unique +} + +static RETIRING_GENERATIONS: Mutex<GenerationRetirements<NativeGeneration, super::alloc_pool::SubmissionReceipt>> = + Mutex::new(GenerationRetirements::new()); + +/// Keep the exact native generations used by one executed title submission until its strong +/// queue receipt completes. Completed batches are swept whenever another pinned batch arrives. +pub(super) fn retire_native_generations<'a>( + receipt: super::alloc_pool::SubmissionReceipt, + pins: impl Iterator<Item = &'a NativeGeneration>, +) { + if receipt.is_complete() { + return; + } + let pins = dedup_generations(pins.cloned(), NativeGeneration::same); + if pins.is_empty() { + return; + } + let mut retiring = RETIRING_GENERATIONS.lock().unwrap(); + let retired = retiring.retire_pending(receipt, pins, super::alloc_pool::SubmissionReceipt::is_complete); + drop(retiring); + drop(retired); +} + +/// Native execution began but no exact retirement marker could be recorded. Retain every exact +/// generation permanently: dropping any of them could free a pipeline still referenced by GPU work. +pub(super) fn poison_native_generations<'a>(pins: impl Iterator<Item = &'a NativeGeneration>) { + let pins = dedup_generations(pins.cloned(), NativeGeneration::same); + if pins.is_empty() { + return; + } + let mut retiring = RETIRING_GENERATIONS.lock().unwrap(); + let retired = retiring.sweep(super::alloc_pool::SubmissionReceipt::is_complete); + retiring.poison(pins, NativeGeneration::same); + drop(retiring); + drop(retired); +} + /// Rebuildable immutable inputs for one pipeline. The first build and any later rebuild use the /// same operation; retaining it does not by itself schedule or run more work. Its existing opt-in /// allocation also owns the native generation, so ordinary one-shot builds allocate no new state. @@ -1394,6 +1478,90 @@ mod used_tests { assert_eq!(drops.load(Ordering::Relaxed), 2); } + #[derive(Clone)] + struct FakeReceipt { + fence: Arc<AtomicU64>, + value: u64, + } + + fn fake_receipt_complete(receipt: &FakeReceipt) -> bool { + receipt.fence.load(Ordering::Relaxed) >= receipt.value + } + + #[test] + fn generation_retirement_deduplicates_and_uses_the_exact_receipt_owner() { + let generation = Arc::new(()); + let pins = dedup_generations( + [generation.clone(), generation.clone()].into_iter(), + Arc::ptr_eq, + ); + assert_eq!(pins.len(), 1); + + let old_fence = Arc::new(AtomicU64::new(0)); + let replacement_fence = Arc::new(AtomicU64::new(99)); + let mut retiring = GenerationRetirements::new(); + drop(retiring.retire_pending( + FakeReceipt { fence: old_fence.clone(), value: 7 }, + pins, + fake_receipt_complete, + )); + drop(retiring.sweep(fake_receipt_complete)); + assert_eq!(retiring.pending.len(), 1, "a replacement queue generation retired an old receipt"); + assert_eq!(Arc::strong_count(&generation), 2, "the in-flight batch did not retain its generation"); + + old_fence.store(7, Ordering::Relaxed); + drop(retiring.sweep(fake_receipt_complete)); + assert!(retiring.pending.is_empty()); + assert_eq!(Arc::strong_count(&generation), 1); + assert_eq!(replacement_fence.load(Ordering::Relaxed), 99); + + drop(retiring.retire_pending( + FakeReceipt { fence: old_fence, value: 7 }, + vec![generation.clone()], + fake_receipt_complete, + )); + assert!(retiring.pending.is_empty(), "an already-complete receipt retained a final batch"); + } + + #[test] + fn untracked_generation_pins_are_never_swept() { + let generation = Arc::new(()); + let weak = Arc::downgrade(&generation); + let pins = dedup_generations( + [generation.clone(), generation.clone()].into_iter(), + Arc::ptr_eq, + ); + let mut retiring = GenerationRetirements::<Arc<()>, FakeReceipt>::new(); + retiring.poison(pins, Arc::ptr_eq); + drop(generation); + + drop(retiring.sweep(fake_receipt_complete)); + assert!(weak.upgrade().is_some(), "sweeping tracked receipts released an untracked generation"); + assert_eq!(retiring.poisoned.len(), 1); + } + + #[test] + fn newly_completed_batch_is_returned_for_drop_after_unlock() { + struct DropPin(Arc<AtomicUsize>); + impl Drop for DropPin { + fn drop(&mut self) { self.0.fetch_add(1, Ordering::Relaxed); } + } + + let drops = Arc::new(AtomicUsize::new(0)); + let fence = Arc::new(AtomicU64::new(1)); + let mut retiring = GenerationRetirements::new(); + let retired = retiring.retire_pending( + FakeReceipt { fence, value: 1 }, + vec![DropPin(drops.clone())], + fake_receipt_complete, + ); + + assert!(retiring.pending.is_empty()); + assert_eq!(drops.load(Ordering::Relaxed), 0, "the manager dropped a pin while it was borrowed mutably"); + drop(retired); + assert_eq!(drops.load(Ordering::Relaxed), 1); + } + #[test] fn concurrent_generation_publications_are_monotonic() { let slot = Arc::new(Mutex::new(GenerationSlot::default())); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index b561258578..add365707b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9076,6 +9076,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis let mut gate = super::alloc_pool::SubmissionGate::default(); let mut submitted = Vec::with_capacity(mapped.len()); let track_shared_view_epochs = super::vram::srv_tracking_enabled(); + let track_native_generation_receipts = super::pso_async::rebuild_recipes_enabled(); let _ = super::list_x::execute_submission_plan_until_failure_on(this, &plan, |chunk| { super::queue_submit::with(this as usize, || { let lists = chunk.lists(); @@ -9084,6 +9085,8 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis this, lists, track_shared_view_epochs && chunk.uses_shared_view_heap(), + track_native_generation_receipts && chunk.has_native_generations(), + chunk.native_generations(), || { let _ = super::alloc_pool::note_resubmits(this, lists); }, From 54815e01ec6c95b34586366ec65d3d23bf0ab426 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:06:37 -0800 Subject: [PATCH 209/265] D3D12.X: pin tracked SRV resources across release Serialize opt-in final resource release with a dedicated lifetime gate so a future quiescent rewrite cannot clone a numeric COM identity after it died. On logical zero, remove the tracker entry atomically with lease snapshots, then leave the lifetime gate before unrelated backing cleanup. Descriptor writes never nest with that gate, and the exact-generation strong resource lease never waits for descriptor writes. Heap-generation leasing and raw descriptor-memory reconciliation remain separate prerequisites. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 16 +- crates/xcl/src/hle/d3d12x/vram.rs | 233 +++++++++++++++++++++++++++++- 2 files changed, 245 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index add365707b..18f47c632e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1779,6 +1779,10 @@ unsafe extern "system" fn res_unmap(this: *mut c_void, sub: u32, range: *const c unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + // When opt-in SRV tracking is active, exclude a future resource lease before the native + // object can die. This is not the descriptor-write gate: descriptor hooks keep that across + // driver calls which may make a temporary, non-final Release here. + let mut tracked_srv_lifetime = super::vram::lock_tracked_srv_lifetime(); // The last reference: kept until the queues are past the work in flight (`late_release`). // (Two last-but-one releases at once can miss each other here; the object then goes at // once, as before.) @@ -1797,6 +1801,15 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { f(this) }; if n == 0 { + // Remove lease candidates while Release is still serialized, then leave the lifetime + // gate before the independent sparse/page/arena cleanup locks below. Do not wait for the + // global descriptor-write gate here: an unrelated hook may hold it while a driver call + // makes a temporary Release that waits for this lifetime gate. Any lease already returned + // owns a strong resource reference and therefore prevents this logical zero. + super::vram::forget_tracked_after_resource_release( + this as usize, tracked_srv_lifetime.as_ref(), + ); + drop(tracked_srv_lifetime.take()); if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() { s.remove(&(this as usize)); } @@ -1813,7 +1826,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { m.remove(&(this as usize)); } super::sparse::forget_buffer(this as usize); - super::vram::forget(this as usize); + super::vram::forget_resource_backing_after_release(this as usize); super::title_textures::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { @@ -1824,6 +1837,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } } } + drop(tracked_srv_lifetime.take()); if held { super::late_release::hold(this as usize); } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index bd1d16b4d4..6c6c2066ff 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -359,13 +359,24 @@ impl TrackedSrvs { static TRACKED_SRVS: Mutex<Option<TrackedSrvs>> = Mutex::new(None); static TRACKED_SRV_WRITES: Mutex<()> = Mutex::new(()); +static TRACKED_SRV_LIFETIMES: Mutex<()> = Mutex::new(()); + +pub(super) type TrackedSrvWriteGuard = std::sync::MutexGuard<'static, ()>; +pub(super) type TrackedSrvLifetimeGuard = std::sync::MutexGuard<'static, ()>; /// Serialize an entire hooked descriptor mutation while tracking is enabled. Operation tokens /// alone order hook starts, not native/console writes that complete in the opposite order. -pub(super) fn lock_tracked_srv_write() -> Option<std::sync::MutexGuard<'static, ()>> { +pub(super) fn lock_tracked_srv_write() -> Option<TrackedSrvWriteGuard> { srv_tracking_enabled().then(|| TRACKED_SRV_WRITES.lock().unwrap()) } +/// Exclude final native resource Release while a tracked entry is turned into a strong owner. +/// This is deliberately distinct from `TRACKED_SRV_WRITES`: descriptor hooks hold the write gate +/// across driver calls which may make a temporary, non-final resource Release. +pub(super) fn lock_tracked_srv_lifetime() -> Option<TrackedSrvLifetimeGuard> { + srv_tracking_enabled().then(|| TRACKED_SRV_LIFETIMES.lock().unwrap()) +} + /// Record the descriptor currently in `slot`. `None` clears an SRV overwritten by another view. pub(super) fn track_srv( device: usize, @@ -425,14 +436,50 @@ pub(super) fn forget_srv_heap(generation: u64) { } } +fn forget_tracked_srvs_locked(resource: usize) { + if let Some(tracked) = TRACKED_SRVS.lock().unwrap().as_mut() { + tracked.forget_resource(resource); + } +} + +#[cfg(test)] fn forget_tracked_srvs(resource: usize) { if !srv_tracking_enabled() { return; } let _write = lock_tracked_srv_write(); - if let Some(tracked) = TRACKED_SRVS.lock().unwrap().as_mut() { - tracked.forget_resource(resource); + forget_tracked_srvs_locked(resource); +} + +/// Clone an owner for one exact tracked resource while final `Release` is excluded. The tracker +/// mutex makes the snapshot coherent; this does not take the descriptor-write gate. A later +/// mutator must take that gate and revalidate the logical generation, as well as lease the exact +/// heap generation, before using `pc_srv` or `shared_srv`. +#[allow(dead_code)] // consumed by the later descriptor-rewrite stage +fn lease_tracked_srv_resource(slot: SrvSlot, generation: u64) -> Option<(TrackedSrv, ID3D12Resource)> { + lease_tracked_srv_resource_with(slot, generation, |resource| { + let raw = resource as *mut std::ffi::c_void; + unsafe { ID3D12Resource::from_raw_borrowed(&raw).cloned() } + }) +} + +fn lease_tracked_srv_resource_with<T>( + slot: SrvSlot, generation: u64, lease: impl FnOnce(usize) -> Option<T>, +) -> Option<(TrackedSrv, T)> { + if !srv_tracking_enabled() { + return None; } + let _lifetime = TRACKED_SRV_LIFETIMES.lock().unwrap(); + let entry = TRACKED_SRVS + .lock() + .unwrap() + .as_ref()? + .by_slot + .get(&slot) + .copied() + .filter(|entry| entry.generation == generation)?; + let owner = lease(entry.resource)?; + Some((entry, owner)) } /// An exact, on-demand snapshot for a future residency consumer. It is deliberately not on the @@ -465,8 +512,34 @@ pub(super) fn is_placed_texture(resource: usize) -> bool { PLACED_TEXTURES.lock().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) } +#[cfg(test)] pub(super) fn forget(resource: usize) { forget_tracked_srvs(resource); + forget_resource_backing(resource); +} + +/// Remove descriptor records after native final `Release`, while the caller still holds the +/// lifetime gate acquired before that call. Do not acquire the descriptor-write gate here: an +/// unrelated hook may hold it across a driver call whose temporary resource Release waits on the +/// lifetime gate. The tracker mutex makes removal atomic with lease snapshots. A future descriptor +/// transaction must take the write gate and revalidate the exact generation and descriptor words; +/// a same-resource descriptor hook concurrent with final Release is invalid object lifetime use. +/// Once this returns no new resource lease can start, so the caller may drop the lifetime gate +/// before doing unrelated sparse/page/arena cleanup. +pub(super) fn forget_tracked_after_resource_release( + resource: usize, lifetime: Option<&TrackedSrvLifetimeGuard>, +) { + debug_assert!(!srv_tracking_enabled() || lifetime.is_some()); + if lifetime.is_some() { + forget_tracked_srvs_locked(resource); + } +} + +pub(super) fn forget_resource_backing_after_release(resource: usize) { + forget_resource_backing(resource); +} + +fn forget_resource_backing(resource: usize) { let placed = PLACED_TEXTURES.lock().unwrap().as_mut().is_some_and(|textures| textures.remove(&resource)); if placed { forget_pages(resource); @@ -2541,6 +2614,160 @@ mod tests { SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); } + #[test] + fn tracked_srv_lease_excludes_final_release_and_locked_cleanup() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + let slot = srv_slot(52, 3); + let mut tracked = TrackedSrvs::default(); + tracked.write(slot, Some(tracked_entry(0x5210, 0x80))); + let generation = tracked.by_slot[&slot].generation; + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let (continue_tx, continue_rx) = std::sync::mpsc::channel(); + let lease = std::thread::spawn(move || { + lease_tracked_srv_resource_with(slot, generation, |resource| { + entered_tx.send(()).unwrap(); + continue_rx.recv().unwrap(); + Some(resource) + }) + .map(|(entry, owner)| (entry.resource, owner)) + }); + entered_rx.recv().unwrap(); + + let (attempted_tx, attempted_rx) = std::sync::mpsc::channel(); + let (released_tx, released_rx) = std::sync::mpsc::channel(); + let release = std::thread::spawn(move || { + attempted_tx.send(()).unwrap(); + let _lifetime = lock_tracked_srv_lifetime(); + released_tx.send(()).unwrap(); + }); + attempted_rx.recv().unwrap(); + assert!(released_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), + "final Release crossed a resource lease in progress"); + continue_tx.send(()).unwrap(); + assert_eq!(lease.join().unwrap(), Some((0x5210, 0x5210))); + released_rx.recv().unwrap(); + release.join().unwrap(); + + let lifetime = lock_tracked_srv_lifetime(); + forget_tracked_after_resource_release(0x5210, lifetime.as_ref()); + assert!(TRACKED_SRVS.lock().unwrap().as_ref().is_some_and(|tracked| tracked.by_slot.is_empty())); + drop(lifetime); + TRACKED_SRVS.lock().unwrap().take(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn descriptor_write_allows_nonfinal_release_before_concurrent_lease() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + let slot = srv_slot(53, 2); + let mut tracked = TrackedSrvs::default(); + tracked.write(slot, Some(tracked_entry(0x5310, 0x84))); + let generation = tracked.by_slot[&slot].generation; + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + + let (release_entered_tx, release_entered_rx) = std::sync::mpsc::channel(); + let (finish_release_tx, finish_release_rx) = std::sync::mpsc::channel(); + let (drop_write_tx, drop_write_rx) = std::sync::mpsc::channel(); + let hook = std::thread::spawn(move || { + let _write = lock_tracked_srv_write(); + // Model a driver temporary Release reentering while a descriptor hook holds WRITE. + // A non-final Release takes only LIFETIME, then returns to the hook. + let lifetime = lock_tracked_srv_lifetime(); + release_entered_tx.send(()).unwrap(); + finish_release_rx.recv().unwrap(); + drop(lifetime); + drop_write_rx.recv().unwrap(); + }); + release_entered_rx.recv().unwrap(); + + let (attempted_tx, attempted_rx) = std::sync::mpsc::channel(); + let (leased_tx, leased_rx) = std::sync::mpsc::channel(); + let lease = std::thread::spawn(move || { + attempted_tx.send(()).unwrap(); + let leased = lease_tracked_srv_resource_with(slot, generation, Some) + .map(|(entry, owner)| (entry.resource, owner)); + leased_tx.send(leased).unwrap(); + }); + attempted_rx.recv().unwrap(); + assert!(leased_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), + "a lease crossed the resource Release lifetime gate"); + finish_release_tx.send(()).unwrap(); + assert_eq!(leased_rx.recv().unwrap(), Some((0x5310, 0x5310)), + "lease acquisition waited for the descriptor-write gate and deadlocked the hook"); + lease.join().unwrap(); + drop_write_tx.send(()).unwrap(); + hook.join().unwrap(); + + let lifetime = lock_tracked_srv_lifetime(); + forget_tracked_after_resource_release(0x5310, lifetime.as_ref()); + drop(lifetime); + TRACKED_SRVS.lock().unwrap().take(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn final_release_cleanup_does_not_wait_for_unrelated_descriptor_write() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + let (slot_a, slot_b) = (srv_slot(54, 0), srv_slot(54, 1)); + let mut tracked = TrackedSrvs::default(); + tracked.write(slot_a, Some(tracked_entry(0x5410, 0x88))); + tracked.write(slot_b, Some(tracked_entry(0x5420, 0x8c))); + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + + let (lifetime_held_tx, lifetime_held_rx) = std::sync::mpsc::channel(); + let (clean_tx, clean_rx) = std::sync::mpsc::channel(); + let (cleaned_tx, cleaned_rx) = std::sync::mpsc::channel(); + let final_release = std::thread::spawn(move || { + let lifetime = lock_tracked_srv_lifetime(); + lifetime_held_tx.send(()).unwrap(); + clean_rx.recv().unwrap(); + forget_tracked_after_resource_release(0x5410, lifetime.as_ref()); + cleaned_tx.send(()).unwrap(); + drop(lifetime); + }); + lifetime_held_rx.recv().unwrap(); + + let (write_held_tx, write_held_rx) = std::sync::mpsc::channel(); + let (release_attempted_tx, release_attempted_rx) = std::sync::mpsc::channel(); + let (release_returned_tx, release_returned_rx) = std::sync::mpsc::channel(); + let (drop_write_tx, drop_write_rx) = std::sync::mpsc::channel(); + let unrelated_hook = std::thread::spawn(move || { + let _write = lock_tracked_srv_write(); + write_held_tx.send(()).unwrap(); + // Model resource B's driver call making a temporary Release while WRITE is held. + release_attempted_tx.send(()).unwrap(); + let lifetime = lock_tracked_srv_lifetime(); + release_returned_tx.send(()).unwrap(); + drop(lifetime); + drop_write_rx.recv().unwrap(); + }); + write_held_rx.recv().unwrap(); + release_attempted_rx.recv().unwrap(); + + clean_tx.send(()).unwrap(); + cleaned_rx.recv_timeout(std::time::Duration::from_secs(1)).expect( + "resource A final cleanup waited for WRITE while resource B Release waited for LIFETIME", + ); + final_release.join().unwrap(); + release_returned_rx.recv().unwrap(); + drop_write_tx.send(()).unwrap(); + unrelated_hook.join().unwrap(); + + { + let tracked = TRACKED_SRVS.lock().unwrap(); + let tracked = tracked.as_ref().unwrap(); + assert!(!tracked.by_slot.contains_key(&slot_a)); + assert_eq!(tracked.by_slot[&slot_b].resource, 0x5420); + } + TRACKED_SRVS.lock().unwrap().take(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + #[test] fn title_queue_mapping_wait_reservation_is_monotonic_and_per_queue() { let mut waited = HashMap::new(); From ea55fb1f7eae582c4f4ebdd766c6a0d6ab669fe9 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:20:13 -0800 Subject: [PATCH 210/265] D3D12.X: queue native pipeline rebuild requests Reserve rebuild attempts in the recipe state machine before placing them on the existing speculative pipeline worker band. Queued attempts own the Build independently of the Pending registry and recheck title ownership before driver work and publication, so release cannot resurrect a pipeline and failed rebuilds retain the current generation. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 206 ++++++++++++++++++++++++- 1 file changed, 205 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index e578614241..708dfd9b4b 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -492,6 +492,15 @@ enum RebuildResult { Published { generation: u64 }, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RebuildRequest { + Queued, + Coalesced, + NotReady, + Abandoned, + Unavailable, +} + /// Build and atomically publish one replacement generation. This remains deliberately uncalled /// until submitted recording pins are retained to exact GPU retirement receipts: publication is /// safe, but a policy must not make an old generation reclaimable while the GPU can still use it. @@ -512,6 +521,22 @@ fn rebuild_once(build: &Build) -> Option<RebuildResult> { RebuildTurn::Leader => {} } + Some(rebuild_reserved(build, recipe)) +} + +/// Run an attempt which already owns the recipe's rebuild turn. +fn rebuild_reserved(build: &Build, recipe: &Recipe) -> RebuildResult { + // A queued request can lose its last title-visible owner before a worker starts it. The queued + // Arc keeps this state alive only so the attempt can retire; it must not revive the pipeline. + { + let done = build.done.lock().unwrap(); + if !*done || build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + drop(done); + recipe.finish_rebuild(RebuildResult::Abandoned); + return RebuildResult::Abandoned; + } + } + // Do expensive driver work without Build.done or the recipe state held. Binds keep using the // current immutable generation throughout the rebuild. let raw = run_job(recipe.initial_job()); @@ -541,7 +566,7 @@ fn rebuild_once(build: &Build) -> Option<RebuildResult> { } else if raw != 0 { release(raw); } - Some(result) + result } static BUILT: AtomicUsize = AtomicUsize::new(0); static FAILED: AtomicUsize = AtomicUsize::new(0); @@ -901,6 +926,16 @@ impl Recipe { } } + /// Reserve one asynchronous attempt without waiting for an attempt already in flight. + fn reserve_rebuild(&self) -> bool { + let mut state = self.0.rebuild.lock().unwrap(); + if state.active || state.waiters != 0 { + return false; + } + state.active = true; + true + } + fn finish_rebuild(&self, result: RebuildResult) { let mut state = self.0.rebuild.lock().unwrap(); state.last = Some(result); @@ -1054,6 +1089,55 @@ fn start_preload_workers() -> bool { }) } +fn run_reserved_rebuild(build: Arc<Build>, recipe: Recipe) { + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_NORMAL}; + let preload = PRELOAD_WORKER.get(); + BUILDING.with(|b| *b.borrow_mut() = Some(build.clone())); + if preload { + let mut demand = build.demand.lock().unwrap(); + demand.preload_thread = unsafe { GetCurrentThreadId() }; + if build.wanted.load(Ordering::Acquire) { + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; + } + } + let _running = RunningBuild { build: &build, preload }; + let _ = rebuild_reserved(&build, &recipe); +} + +fn request_rebuild_on(build: Arc<Build>, q: &BuildQueue) -> RebuildRequest { + let recipe = { + let done = build.done.lock().unwrap(); + if !*done { + return RebuildRequest::NotReady; + } + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + return RebuildRequest::Abandoned; + } + let Some(recipe) = build.recipe.clone() else { return RebuildRequest::Unavailable }; + if !recipe.reserve_rebuild() { + return RebuildRequest::Coalesced; + } + recipe + }; + let failed_recipe = recipe.clone(); + if q.submit(Priority::Speculative, Box::new(move || run_reserved_rebuild(build, recipe))).is_none() { + failed_recipe.finish_rebuild(RebuildResult::Failed); + return RebuildRequest::Unavailable; + } + RebuildRequest::Queued +} + +/// Queue one low-priority replacement build. This is intentionally uncalled until an eviction +/// policy has selected a pipeline; requesting never waits for driver work on the title thread. +#[allow(dead_code)] +fn request_rebuild(pso: usize) -> RebuildRequest { + let Some(pending) = entry(pso) else { return RebuildRequest::Unavailable }; + if !start_preload_workers() { + return RebuildRequest::Unavailable; + } + request_rebuild_on(pending.build.clone(), queue()) +} + fn submit_job(q: &BuildQueue, build: &Arc<Build>, priority: Priority, preload: bool, preload_rank: Option<usize>) -> Option<JobHandle> { let queued_build = build.clone(); q.submit_ranked(priority, preload_rank, Box::new(move || { @@ -1717,6 +1801,126 @@ mod used_tests { assert_eq!(first.refs.load(Ordering::Relaxed), 0); } + #[test] + fn async_rebuild_requests_coalesce_without_running_on_the_requester() { + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + 0 + }); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + let q = BuildQueue::new(); + + assert_eq!(request_rebuild_on(build.clone(), &q), RebuildRequest::Queued); + assert_eq!(request_rebuild_on(build.clone(), &q), RebuildRequest::Coalesced); + assert_eq!(calls.load(Ordering::Relaxed), 1, "requesting performed driver work"); + assert!(q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(calls.load(Ordering::Relaxed), 2); + assert_eq!(build.recipe.as_ref().unwrap().0.rebuild.lock().unwrap().completed, 1); + } + + #[test] + fn async_rebuild_released_before_start_does_not_run_or_resurrect() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + first_raw + }); + let standin = 0x7E57_C151usize; + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + let q = BuildQueue::new(); + assert_eq!(request_rebuild_on(pending.build.clone(), &q), RebuildRequest::Queued); + + let current = released(standin); + release(current); + assert!(q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(calls.load(Ordering::Relaxed), 1, "orphaned queued request ran its recipe"); + assert_eq!(pending.build.real.load(Ordering::Acquire), 0, "queued work resurrected a released build"); + drop(pending); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn async_rebuild_failure_keeps_current_generation() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let recipe = Recipe::new(move || build_next.load(Ordering::Acquire)); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + next.store(0, Ordering::Release); + let q = BuildQueue::new(); + + assert_eq!(request_rebuild_on(build.clone(), &q), RebuildRequest::Queued); + assert!(q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(build.real.load(Ordering::Acquire), first_raw); + assert_eq!(recipe.pin(first_raw).unwrap().id(), 1); + + let final_raw = build.real.swap(0, Ordering::AcqRel); + drop(build); + drop(recipe); + release(final_raw); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn async_rebuild_released_while_worker_runs_abandons_replacement() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let block = Arc::new((Mutex::new((false, false)), Condvar::new())); + let build_block = block.clone(); + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let recipe = Recipe::new(move || { + if build_next.load(Ordering::Acquire) == replacement_raw { + let mut state = build_block.0.lock().unwrap(); + state.0 = true; + build_block.1.notify_all(); + while !state.1 { state = build_block.1.wait(state).unwrap(); } + } + build_next.load(Ordering::Acquire) + }); + let standin = 0x7E57_C152usize; + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + next.store(replacement_raw, Ordering::Release); + let q = Arc::new(BuildQueue::new()); + assert_eq!(request_rebuild_on(pending.build.clone(), &q), RebuildRequest::Queued); + let worker_q = q.clone(); + let worker = std::thread::spawn(move || worker_q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + { + let mut state = block.0.lock().unwrap(); + while !state.0 { state = block.1.wait(state).unwrap(); } + } + let old = released(standin); + release(old); + block.0.lock().unwrap().1 = true; + block.1.notify_all(); + assert!(worker.join().unwrap()); + assert_eq!(pending.build.real.load(Ordering::Acquire), 0); + assert_eq!(replacement.refs.load(Ordering::Relaxed), 0); + drop(pending); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + #[test] fn capture_preserves_lazy_for_bind_wait_and_identity_choices() { let standin = 0x7E57_C130usize; From 95d3844ecb649a52c55110ad2d361d1326f99cf5 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:22:09 -0800 Subject: [PATCH 211/265] D3D12.X: choose a ready sparse upload slot Scan the small upload-slot ring before waiting so a busy round-robin head does not hide an already-retired allocator. When every slot is busy, wait on the earliest value from the shared sparse fence without advancing slot ownership. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 96 +++++++++++++++++++++++++++-- 1 file changed, 91 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 1b083a1651..819bc8f0a2 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1110,16 +1110,30 @@ impl State { /// Acquire the next upload command slot, or return a ticket to wait for without `STATE`. unsafe fn begin_slot(&mut self) -> BeginSlot { - let idx = self.next_slot; - let fv = self.slots[idx].fence_val; - if fv > 0 && self.fence.GetCompletedValue() < fv { - return BeginSlot::Wait(self.wait_ticket(fv, WaitKind::Slot { index: idx, next_slot: idx, fence: fv })); + let next_slot = self.next_slot; + let completed = self.fence.GetCompletedValue(); + let mut waiting = None; + let mut ready = None; + for offset in 0..self.slots.len() { + let idx = (next_slot + offset) % self.slots.len(); + let fv = self.slots[idx].fence_val; + if fv == 0 || fv <= completed { + ready = Some(idx); + break; + } + if waiting.is_none_or(|(_, earliest)| fv < earliest) { + waiting = Some((idx, fv)); + } } - self.next_slot = (idx + 1) % self.slots.len(); + let Some(idx) = ready else { + let (idx, fv) = waiting.expect("sparse upload slots are not empty"); + return BeginSlot::Wait(self.wait_ticket(fv, WaitKind::Slot { index: idx, next_slot, fence: fv })); + }; let slot = &self.slots[idx]; if slot.alloc.Reset().is_err() || slot.list.Reset(&slot.alloc, None).is_err() { return BeginSlot::RetryRequired; } + self.next_slot = (idx + 1) % self.slots.len(); BeginSlot::Ready(idx) } @@ -3500,6 +3514,78 @@ mod tests { (base, s) } + unsafe fn add_upload_slot(s: &mut State, fence_val: u64, close: bool) { + let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("upload allocator"); + let list: ID3D12GraphicsCommandList = s.dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None) + .expect("upload list"); + if close { + list.Close().expect("upload list close"); + } + s.slots.push(UploadSlot { alloc, list, fence_val }); + } + + #[test] + fn begin_slot_skips_a_busy_head_for_a_ready_slot() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + add_upload_slot(&mut s, 9, true); + add_upload_slot(&mut s, 0, true); + + assert!(matches!(s.begin_slot(), BeginSlot::Ready(1))); + assert_eq!(s.next_slot, 0); + s.slots[1].list.Close().expect("selected list close"); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn begin_slot_waits_for_the_earliest_busy_slot_without_advancing() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + add_upload_slot(&mut s, 9, true); + add_upload_slot(&mut s, 7, true); + add_upload_slot(&mut s, 8, true); + let ticket = match s.begin_slot() { + BeginSlot::Wait(ticket) => ticket, + _ => panic!("all busy slots did not return a retirement ticket"), + }; + + assert_eq!(s.next_slot, 0); + assert_eq!(ticket.target, 7); + assert!(matches!(ticket.kind, WaitKind::Slot { index: 1, next_slot: 0, fence: 7 })); + assert!(s.wait_ticket_owns_upload(&ticket)); + s.slots[1].fence_val = 10; + assert!(!s.wait_ticket_owns_upload(&ticket), "a changed selected slot accepted its old ticket"); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn begin_slot_reset_failure_does_not_open_or_advance_a_slot() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + add_upload_slot(&mut s, 0, false); + + assert!(matches!(s.begin_slot(), BeginSlot::RetryRequired)); + assert_eq!(s.next_slot, 0); + + s.slots[0].list.Close().expect("failed selected list close"); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + #[test] fn a_stalled_upload_ring_yields_without_publishing_hashes() { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; From 870e6fa0567d7dd6a173873c6af8431e1bcde3ab Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:25:19 -0800 Subject: [PATCH 212/265] D3D12.X: deduplicate native generation pins linearly Use the generation owner's stable Arc allocation as the identity for hash-based receipt and permanent-poison deduplication. This preserves distinct generations when a driver reuses the same raw pipeline address while removing unbounded repeated Vec scans. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 37 +++++++++++++++++--------- 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 708dfd9b4b..400ba4041b 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -7,7 +7,7 @@ //! for where it is used, a `Dispatch` at its submit (a skipped dispatch would corrupt what it computes). //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock, Weak}; @@ -775,16 +775,19 @@ impl NativeGeneration { #[allow(dead_code)] // exposed to focused generation-capture tests pub(super) fn raw(&self) -> usize { self.0.raw } pub(super) fn same(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } + // The owner allocation, rather than `raw`, distinguishes ABA reuse by a later generation. + fn identity(&self) -> usize { Arc::as_ptr(&self.0) as usize } } struct GenerationRetirements<G, R> { pending: Vec<(R, Vec<G>)>, poisoned: Vec<G>, + poisoned_identities: Option<HashSet<usize>>, } impl<G, R> GenerationRetirements<G, R> { const fn new() -> Self { - Self { pending: Vec::new(), poisoned: Vec::new() } + Self { pending: Vec::new(), poisoned: Vec::new(), poisoned_identities: None } } fn sweep(&mut self, complete: impl Fn(&R) -> bool) -> Vec<(R, Vec<G>)> { @@ -807,19 +810,21 @@ impl<G, R> GenerationRetirements<G, R> { self.sweep(complete) } - fn poison(&mut self, pins: Vec<G>, same: impl Fn(&G, &G) -> bool) { + fn poison(&mut self, pins: Vec<G>, identity: impl Fn(&G) -> usize) { + let identities = self.poisoned_identities.get_or_insert_with(HashSet::new); for pin in pins { - if !self.poisoned.iter().any(|old| same(old, &pin)) { + if identities.insert(identity(&pin)) { self.poisoned.push(pin); } } } } -fn dedup_generations<G>(pins: impl Iterator<Item = G>, same: impl Fn(&G, &G) -> bool) -> Vec<G> { +fn dedup_generations<G>(pins: impl Iterator<Item = G>, identity: impl Fn(&G) -> usize) -> Vec<G> { let mut unique = Vec::new(); + let mut identities = HashSet::new(); for pin in pins { - if !unique.iter().any(|old| same(old, &pin)) { + if identities.insert(identity(&pin)) { unique.push(pin); } } @@ -838,7 +843,7 @@ pub(super) fn retire_native_generations<'a>( if receipt.is_complete() { return; } - let pins = dedup_generations(pins.cloned(), NativeGeneration::same); + let pins = dedup_generations(pins.cloned(), NativeGeneration::identity); if pins.is_empty() { return; } @@ -851,13 +856,13 @@ pub(super) fn retire_native_generations<'a>( /// Native execution began but no exact retirement marker could be recorded. Retain every exact /// generation permanently: dropping any of them could free a pipeline still referenced by GPU work. pub(super) fn poison_native_generations<'a>(pins: impl Iterator<Item = &'a NativeGeneration>) { - let pins = dedup_generations(pins.cloned(), NativeGeneration::same); + let pins = dedup_generations(pins.cloned(), NativeGeneration::identity); if pins.is_empty() { return; } let mut retiring = RETIRING_GENERATIONS.lock().unwrap(); let retired = retiring.sweep(super::alloc_pool::SubmissionReceipt::is_complete); - retiring.poison(pins, NativeGeneration::same); + retiring.poison(pins, NativeGeneration::identity); drop(retiring); drop(retired); } @@ -1552,6 +1557,12 @@ mod used_tests { let (second, replaced) = slot.publish(0x7E57_ABA0, Owner(drops.clone())); assert_eq!(second.id, 2); assert!(!Arc::ptr_eq(&pinned, &second), "a reused raw address aliased its older generation"); + let unique = dedup_generations( + [first.clone(), first.clone(), second.clone(), second.clone()].into_iter(), + |generation| Arc::as_ptr(generation) as usize, + ); + assert_eq!(unique.len(), 2, "a reused raw address collapsed distinct generations"); + drop(unique); drop(first); drop(replaced); assert_eq!(drops.load(Ordering::Relaxed), 0, "the old generation died while a pin held it"); @@ -1577,7 +1588,7 @@ mod used_tests { let generation = Arc::new(()); let pins = dedup_generations( [generation.clone(), generation.clone()].into_iter(), - Arc::ptr_eq, + |generation| Arc::as_ptr(generation) as usize, ); assert_eq!(pins.len(), 1); @@ -1613,10 +1624,12 @@ mod used_tests { let weak = Arc::downgrade(&generation); let pins = dedup_generations( [generation.clone(), generation.clone()].into_iter(), - Arc::ptr_eq, + |generation| Arc::as_ptr(generation) as usize, ); let mut retiring = GenerationRetirements::<Arc<()>, FakeReceipt>::new(); - retiring.poison(pins, Arc::ptr_eq); + retiring.poison(pins, |generation| Arc::as_ptr(generation) as usize); + retiring.poison(vec![generation.clone()], |generation| Arc::as_ptr(generation) as usize); + assert_eq!(retiring.poisoned.len(), 1, "a later poison duplicated an existing generation"); drop(generation); drop(retiring.sweep(fake_receipt_complete)); From 10ab225b1809329164b0187442cf08ea7fa63ca8 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:23:52 -0800 Subject: [PATCH 213/265] D3D12.X: lease exact descriptor heap slots Keep the source and shared native descriptor heaps and their device alive while a future quiescent mutation validates an exact heap generation and slot. Serialize opt-in final heap Release without taking the descriptor-write gate, and preserve the default-off path. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/console_heap.rs | 186 +++++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 15 +- crates/xcl/src/hle/d3d12x/vram.rs | 65 +++++++- 3 files changed, 255 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 15cb8a4361..575762ee71 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -76,6 +76,16 @@ impl Heap { static HEAPS: Mutex<Vec<Heap>> = Mutex::new(Vec::new()); static NEXT_HEAP_GENERATION: AtomicU64 = AtomicU64::new(0); +static HEAP_LIFETIMES: Mutex<()> = Mutex::new(()); + +pub(super) type HeapLifetimeGuard = std::sync::MutexGuard<'static, ()>; + +/// Exclude final descriptor-heap `Release` while an exact heap generation is turned into +/// strong native owners. This is separate from the descriptor-write gate: hooks keep that gate +/// across driver calls which may temporarily release a heap. +pub(super) fn lock_lifetime() -> Option<HeapLifetimeGuard> { + super::vram::srv_tracking_enabled().then(|| HEAP_LIFETIMES.lock().unwrap()) +} /// Shared ranges being written by lock-free single-descriptor publication, and releases which /// cannot return to the allocator until every overlapping write has finished. @@ -496,15 +506,29 @@ pub struct Taken(Heap); /// Stop finding a heap by object address without freeing memory the object may still use. pub fn take(obj: usize) -> Option<Taken> { + let heap = detach(obj)?; + super::vram::forget_srv_heap(heap.generation); + Some(Taken(heap)) +} + +fn detach(obj: usize) -> Option<Heap> { + let mut heaps = HEAPS.lock().unwrap(); + heaps.iter().position(|h| h.obj == obj).map(|i| heaps.swap_remove(i)) +} + +pub(super) fn generation(obj: usize) -> Option<u64> { + HEAPS.lock().unwrap().iter().find(|heap| heap.obj == obj).map(|heap| heap.generation) +} + +/// Detach bookkeeping before the native object can die. The caller holds `HEAP_LIFETIMES`, so +/// cleanup must not wait for the descriptor-write gate (a reentrant temporary Release may hold +/// that gate while waiting here). +pub(super) fn take_after_release(obj: usize, generation: Option<u64>, lifetime: Option<&HeapLifetimeGuard>) -> Option<Taken> { let mut heaps = HEAPS.lock().unwrap(); - let heap = heaps.iter().position(|h| h.obj == obj).map(|i| heaps.swap_remove(i)); + let heap = heaps.iter().position(|h| h.obj == obj && Some(h.generation) == generation).map(|i| heaps.swap_remove(i))?; drop(heaps); - if let Some(heap) = heap { - super::vram::forget_srv_heap(heap.generation); - Some(Taken(heap)) - } else { - None - } + super::vram::forget_srv_heap_after_release(heap.generation, lifetime); + Some(Taken(heap)) } /// Return a taken heap's slots and shadow memory after its native object is gone. @@ -555,6 +579,79 @@ pub struct Slot { pub remaining: u32, } +/// Strong ownership and the exact handles of one view slot. Holding this value only proves CPU +/// object lifetime; a consumer must separately prove queue quiescence, take the descriptor-write +/// gate, and revalidate the tracked logical generation and words before mutating descriptors. +#[allow(dead_code)] +pub(super) struct ViewSlotLease { + pub pc_srv: u64, + pub shared_srv: u64, + pub index: u32, + _device: ID3D12Device, + _source_heap: ID3D12DescriptorHeap, + _shared_heap: Option<ID3D12DescriptorHeap>, +} + +/// Lease the native objects behind one exact heap generation and slot. All arithmetic and both +/// CPU handles are checked while `HEAPS` (and, for a shared slot, `GLOBAL`) still identify that +/// generation. Driver calls happen only after allocator locks have been dropped. +#[allow(dead_code)] +pub(super) fn lease_view_slot(generation: u64, k: u32, pc_srv: u64, shared_srv: u64, index: u32) -> Option<ViewSlotLease> { + let _lifetime = lock_lifetime()?; + let (source_raw, shared_index) = { + let heaps = HEAPS.lock().unwrap(); + let h = heaps.iter().find(|h| h.generation == generation && !h.sampler && k < h.n)?; + let local_index = k.checked_mul(2)?; + let expected_pc = h.pc_cpu.checked_add(local_index as u64 * h.inc as u64)?; + if expected_pc != pc_srv { + return None; + } + let shared_index = if h.pages.is_empty() { + if shared_srv != 0 || index != local_index { + return None; + } + None + } else { + let first = *h.pages.get((k / PAGE_SLOTS) as usize)?; + if first == UNMAPPED { + return None; + } + Some(first.checked_add(2 * (k % PAGE_SLOTS))?) + }; + (h.obj as *mut std::ffi::c_void, shared_index) + }; + let shared_raw = if let Some(expected_index) = shared_index { + let global = GLOBAL.lock().unwrap(); + let global = global.as_ref()?; + if expected_index.checked_add(1)? >= global.cap + || index != expected_index + || shared_srv != global.cpu.checked_add(expected_index as u64 * global.inc as u64)? + { + return None; + } + Some((global.dev.as_raw(), global.heap.as_raw())) + } else { + None + }; + // The lifetime gate prevents source final Release, and process-global heaps are never + // replaced. Invoke COM only after allocator mutexes have been dropped. + let source_heap = unsafe { ID3D12DescriptorHeap::from_raw_borrowed(&source_raw)?.clone() }; + // The strong source owner now prevents native final Release. Leave the non-reentrant gate + // before any fallible COM work so an error or unwind can drop that owner through our hooked + // Release without trying to reacquire a gate this thread still holds. + drop(_lifetime); + let (device, shared_heap) = if let Some((device_raw, heap_raw)) = shared_raw { + let device = unsafe { ID3D12Device::from_raw_borrowed(&device_raw)?.clone() }; + let heap = unsafe { ID3D12DescriptorHeap::from_raw_borrowed(&heap_raw)?.clone() }; + (device, Some(heap)) + } else { + let mut device = None; + unsafe { source_heap.GetDevice(&mut device).ok()? }; + (device?, None) + }; + Some(ViewSlotLease { pc_srv, shared_srv, index, _device: device, _source_heap: source_heap, _shared_heap: shared_heap }) +} + /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot /// of a heap in the shared heap gets its page's place there now if the page has none yet. pub fn slot(cpu: u64) -> Option<Slot> { @@ -1062,6 +1159,81 @@ mod tests { assert!(free.is_empty()); } + #[test] + fn exact_view_slot_lease_survives_detach_and_rejects_address_reuse() { + const CHILD: &str = "XCL_TEST_VIEW_SLOT_LEASE_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::exact_view_slot_lease_survives_detach_and_rejects_address_reuse", "--nocapture"]) + .env(CHILD, "1").env("XCL_TEXTURE_BUDGET_EVICT", "1").output().unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + static RELEASE_REENTERED: AtomicBool = AtomicBool::new(false); + #[repr(C)] + struct Object { vt: *const usize, refs: AtomicU32 } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (*(this as *mut Object)).refs.fetch_add(1, Ordering::Relaxed) + 1 + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + RELEASE_REENTERED.fetch_or(HEAP_LIFETIMES.try_lock().is_ok(), Ordering::Relaxed); + (*(this as *mut Object)).refs.fetch_sub(1, Ordering::Relaxed) - 1 + } + unsafe extern "system" fn get_device(_this: *mut c_void, _iid: *const windows::core::GUID, _out: *mut *mut c_void) -> windows::core::HRESULT { + windows::core::HRESULT(0x8000_4002u32 as i32) + } + let mut vt = [0usize; 8]; + vt[1] = add_ref as usize; + vt[2] = release as usize; + vt[7] = get_device as usize; + let mut device = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + let mut global_heap = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + let mut source_heap = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + unsafe { + *GLOBAL.lock().unwrap() = Some(Global { + dev: ID3D12Device::from_raw((&mut device as *mut Object).cast()), + heap: ID3D12DescriptorHeap::from_raw((&mut global_heap as *mut Object).cast()), + cpu: 0x10_0000, gpu: 0x20_0000, inc: 32, cap: 128, next: 80, + free: Vec::new(), leases: PublishLeases::default(), + }); + HEAPS.lock().unwrap().push(Heap { + generation: 70, obj: &mut source_heap as *mut Object as usize, shadow: 0x5000, + n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, + pages: vec![64], visible: true, memory: Memory::Uma, + }); + let lease = lease_view_slot(70, 2, 0x30_0080, 0x10_0880, 68).expect("exact slot"); + assert_eq!((source_heap.refs.load(Ordering::Relaxed), global_heap.refs.load(Ordering::Relaxed), device.refs.load(Ordering::Relaxed)), (2, 2, 2)); + assert!(lease_view_slot(70, 4, 0x30_0100, 0, 0).is_none(), "slot bound"); + assert!(lease_view_slot(70, 2, 0x30_0080, 0x10_0880, 69).is_none(), "shared index"); + + let lifetime = lock_lifetime(); + let Taken(old) = take_after_release(&mut source_heap as *mut Object as usize, Some(70), lifetime.as_ref()).unwrap(); + drop(lifetime); + HEAPS.lock().unwrap().push(Heap { generation: 71, pc_cpu: 0x40_0000, pages: vec![80], ..old }); + assert!(lease_view_slot(70, 2, 0x30_0080, 0x10_0880, 68).is_none(), "old generation at reused object address"); + let lifetime = lock_lifetime(); + assert!(take_after_release(&mut source_heap as *mut Object as usize, Some(70), lifetime.as_ref()).is_none()); + drop(lifetime); + assert!(HEAPS.lock().unwrap().iter().any(|heap| heap.generation == 71), "late cleanup must keep the replacement"); + assert_eq!((lease.pc_srv, lease.shared_srv, lease.index), (0x30_0080, 0x10_0880, 68)); + drop(lease); + assert_eq!((source_heap.refs.load(Ordering::Relaxed), global_heap.refs.load(Ordering::Relaxed), device.refs.load(Ordering::Relaxed)), (1, 1, 1)); + HEAPS.lock().unwrap().clear(); + HEAPS.lock().unwrap().push(Heap { + generation: 72, obj: &mut source_heap as *mut Object as usize, shadow: 0x6000, + n: 1, pc_cpu: 0x50_0000, pc_gpu: 0, inc: 32, sampler: false, + pages: Vec::new(), visible: true, memory: Memory::Uma, + }); + RELEASE_REENTERED.store(false, Ordering::Relaxed); + assert!(lease_view_slot(72, 0, 0x50_0000, 0, 0).is_none(), "GetDevice fails"); + assert!(RELEASE_REENTERED.load(Ordering::Relaxed), "failed lease must drop its owner outside the lifetime gate"); + HEAPS.lock().unwrap().clear(); + *GLOBAL.lock().unwrap() = None; + } + } + #[test] fn a_freed_range_at_the_cursor_continues_into_the_never_used_tail() { // the false-full shape: four freed slots end at the cursor and four more were never diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 18f47c632e..46d6426251 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2210,7 +2210,20 @@ unsafe fn release_taking_first<T>(this: *mut c_void, mut take: impl FnMut() -> T /// descriptor heap Release (every caller): a console heap's slots go with it unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 { - release_taking_first(this, || super::console_heap::take(this as usize), |h| h.into_iter().for_each(super::console_heap::free)) + let lifetime = super::console_heap::lock_lifetime(); + if lifetime.is_none() { + return release_taking_first(this, || super::console_heap::take(this as usize), |h| h.into_iter().for_each(super::console_heap::free)); + } + let generation = lifetime.as_ref().and_then(|_| super::console_heap::generation(this as usize)); + let mut taken = None; + let n = release_taking_first( + this, + || super::console_heap::take_after_release(this as usize, generation, lifetime.as_ref()), + |h| taken = h, + ); + drop(lifetime); + taken.into_iter().for_each(super::console_heap::free); + n } /// Default UAV dimension for a texture resource when `CreateUnorderedAccessView` receives a NULL desc. diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 6c6c2066ff..d30c06f1dd 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -436,6 +436,20 @@ pub(super) fn forget_srv_heap(generation: u64) { } } +/// Remove candidates for a descriptor heap that reached final native `Release`, while the heap +/// lifetime gate still excludes snapshots. Do not take `TRACKED_SRV_WRITES`: a descriptor hook +/// may hold it across a driver call which reenters a temporary heap Release. +pub(super) fn forget_srv_heap_after_release( + generation: u64, lifetime: Option<&super::console_heap::HeapLifetimeGuard>, +) { + debug_assert!(!srv_tracking_enabled() || lifetime.is_some()); + if lifetime.is_some() { + if let Some(tracked) = TRACKED_SRVS.lock().unwrap().as_mut() { + tracked.forget_heap(generation); + } + } +} + fn forget_tracked_srvs_locked(resource: usize) { if let Some(tracked) = TRACKED_SRVS.lock().unwrap().as_mut() { tracked.forget_resource(resource); @@ -456,11 +470,15 @@ fn forget_tracked_srvs(resource: usize) { /// mutator must take that gate and revalidate the logical generation, as well as lease the exact /// heap generation, before using `pc_srv` or `shared_srv`. #[allow(dead_code)] // consumed by the later descriptor-rewrite stage -fn lease_tracked_srv_resource(slot: SrvSlot, generation: u64) -> Option<(TrackedSrv, ID3D12Resource)> { - lease_tracked_srv_resource_with(slot, generation, |resource| { +fn lease_tracked_srv_resource(slot: SrvSlot, generation: u64) -> Option<(TrackedSrv, ID3D12Resource, super::console_heap::ViewSlotLease)> { + let (entry, resource) = lease_tracked_srv_resource_with(slot, generation, |resource| { let raw = resource as *mut std::ffi::c_void; unsafe { ID3D12Resource::from_raw_borrowed(&raw).cloned() } - }) + })?; + let heap = super::console_heap::lease_view_slot( + slot.heap_generation, slot.slot, entry.pc_srv, entry.shared_srv, entry.index, + )?; + Some((entry, resource, heap)) } fn lease_tracked_srv_resource_with<T>( @@ -2709,6 +2727,47 @@ mod tests { SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); } + #[test] + fn descriptor_heap_final_cleanup_does_not_invert_reentrant_write_order() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + let slot = srv_slot(55, 0); + let mut tracked = TrackedSrvs::default(); + tracked.write(slot, Some(tracked_entry(0x5510, 0x90))); + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + + let (held_tx, held_rx) = std::sync::mpsc::channel(); + let (clean_tx, clean_rx) = std::sync::mpsc::channel(); + let (cleaned_tx, cleaned_rx) = std::sync::mpsc::channel(); + let final_release = std::thread::spawn(move || { + let lifetime = super::super::console_heap::lock_lifetime(); + held_tx.send(()).unwrap(); + clean_rx.recv().unwrap(); + forget_srv_heap_after_release(55, lifetime.as_ref()); + cleaned_tx.send(()).unwrap(); + drop(lifetime); + }); + held_rx.recv().unwrap(); + let (write_tx, write_rx) = std::sync::mpsc::channel(); + let (drop_tx, drop_rx) = std::sync::mpsc::channel(); + let hook = std::thread::spawn(move || { + let _write = lock_tracked_srv_write(); + write_tx.send(()).unwrap(); + let lifetime = super::super::console_heap::lock_lifetime(); + drop(lifetime); + drop_rx.recv().unwrap(); + }); + write_rx.recv().unwrap(); + clean_tx.send(()).unwrap(); + cleaned_rx.recv_timeout(std::time::Duration::from_secs(1)).expect("final cleanup must not wait for WRITE"); + final_release.join().unwrap(); + drop_tx.send(()).unwrap(); + hook.join().unwrap(); + assert!(TRACKED_SRVS.lock().unwrap().as_ref().is_some_and(|tracked| tracked.by_slot.is_empty())); + TRACKED_SRVS.lock().unwrap().take(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + #[test] fn final_release_cleanup_does_not_wait_for_unrelated_descriptor_write() { let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); From dd17d62f3b9abe873242081f8070006ca7342343 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:33:14 -0800 Subject: [PATCH 214/265] D3D12.X: revalidate tracked SRVs before mutation Compose queue quiescence, exact resource and heap leases, descriptor-write exclusion, and final logical-generation and raw-word checks into an uncalled mutation transaction. Stale observations fail closed, while strong COM owners are released only after inner locks have been dropped. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/console_heap.rs | 11 ++ crates/xcl/src/hle/d3d12x/vram.rs | 181 ++++++++++++++++++++++ 2 files changed, 192 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 575762ee71..60a3136444 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -973,6 +973,17 @@ pub(super) fn view_slot_words(slots: &[(u64, u32)]) -> Vec<Option<[u32; 8]>> { .collect() } +/// Exact console words currently in one view slot. The exact-generation heap lease used by a +/// caller keeps the native object and its backing allocation alive; `HEAPS` still verifies that +/// the allocation has not been detached before the point-in-time read. +pub(super) fn exact_view_slot_words(generation: u64, k: u32) -> Option<[u32; 8]> { + let heaps = HEAPS.lock().unwrap(); + let h = heaps.iter().find(|heap| heap.generation == generation && !heap.sampler && k < heap.n)?; + let mut words = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping((h.shadow + (k * SLOT) as usize) as *const u32, words.as_mut_ptr(), 8) }; + Some(words) +} + // --------------------------------------------------------------------------------------- // Shared shader-visible PC sampler heap (`GLOBAL_SAMPLER`, up to D3D12's 2048 limit): // allows 16-byte S# descriptors copied via raw CPU `memcpy` between CPU-only and diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index d30c06f1dd..8775d3bddf 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -500,6 +500,69 @@ fn lease_tracked_srv_resource_with<T>( Some((entry, owner)) } +/// Execute one point-in-time mutation of an exact tracked SRV generation. Queue quiescence is +/// held outermost so no new shared-view submission can cross the mutation. Strong resource and +/// heap owners are acquired before `WRITE`, then the tracker generation and all eight console +/// words are revalidated immediately before `mutate` runs. The tracker mutex is not held across +/// `mutate`; `WRITE` is, so the closure must call only unhooked descriptor operations and must not +/// submit work or reserve another shared-view epoch. +/// +/// Title code can write console descriptor memory without using a hook. Such a write can race +/// after the point-in-time word check, so this primitive deliberately promises no stronger +/// atomicity than the title's descriptor-lifetime rules. A mismatch fails closed and forgets only +/// the stale generation. Strong owners are dropped after `WRITE` and the tracker lock are gone. +#[allow(dead_code)] // consumed by the later descriptor-rewrite policy +fn with_exact_tracked_srv_mutation<T>( + slot: SrvSlot, + generation: u64, + mutate: impl FnOnce(&TrackedSrv, &ID3D12Resource, &super::console_heap::ViewSlotLease) -> T, +) -> Option<T> { + with_exact_tracked_srv_mutation_on( + slot, + generation, + lease_tracked_srv_resource, + |slot| super::console_heap::exact_view_slot_words(slot.heap_generation, slot.slot), + mutate, + ) +} + +fn with_exact_tracked_srv_mutation_on<T, Resource, Heap>( + slot: SrvSlot, + generation: u64, + lease: impl FnOnce(SrvSlot, u64) -> Option<(TrackedSrv, Resource, Heap)>, + observe_words: impl FnOnce(SrvSlot) -> Option<[u32; 8]>, + mutate: impl FnOnce(&TrackedSrv, &Resource, &Heap) -> T, +) -> Option<T> { + with_quiescent_shared_view_heap(|| { + let (snapshot, resource, heap) = lease(slot, generation)?; + let result = { + let _write = lock_tracked_srv_write()?; + let valid = { + let mut tracked = TRACKED_SRVS.lock().unwrap(); + let current = tracked.as_mut()?.by_slot.get(&slot).copied()?; + if current.generation != generation { + return None; + } + // This is TRACKED_SRVS -> HEAPS. Final heap cleanup drops HEAPS before taking + // TRACKED_SRVS, and descriptor-hook lookups also take them sequentially, so there + // is no nested inverse while the exact words are observed. + if observe_words(slot) != Some(current.words) { + tracked.as_mut()?.by_slot.remove(&slot); + return None; + } + // The generation identifies the complete immutable tracker snapshot. Drop this + // mutex before the supplied operation; WRITE keeps hooked mutations excluded. + current + }; + debug_assert_eq!(valid.generation, snapshot.generation); + Some(mutate(&valid, &resource, &heap)) + }; + // `resource` and `heap` drop here, after the tracker and WRITE guards above. + result + }) + .flatten() +} + /// An exact, on-demand snapshot for a future residency consumer. It is deliberately not on the /// submit path: scanning every live SRV there would turn descriptor count into foreground cost. /// A consumer must still capture descriptor generations with recorded lists and queue fences; @@ -2555,6 +2618,124 @@ mod tests { SrvSlot { heap_generation, slot } } + struct MutationOwner(Arc<std::sync::atomic::AtomicUsize>); + + impl Drop for MutationOwner { + fn drop(&mut self) { + assert!(TRACKED_SRV_WRITES.try_lock().is_ok(), "strong owner dropped under WRITE"); + assert!(TRACKED_SRVS.try_lock().is_ok(), "strong owner dropped under tracker lock"); + self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + + fn begin_mutation_test(entry: TrackedSrv, slot: SrvSlot) -> (u64, [u32; 8]) { + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + *SHARED_VIEW_EPOCHS.lock().unwrap() = SharedViewEpochs::new(); + let mut tracked = TrackedSrvs::default(); + tracked.write(slot, Some(entry)); + let current = tracked.by_slot[&slot]; + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + (current.generation, current.words) + } + + fn end_mutation_test() { + TRACKED_SRVS.lock().unwrap().take(); + *SHARED_VIEW_EPOCHS.lock().unwrap() = SharedViewEpochs::new(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn exact_srv_mutation_revalidates_then_drops_owners_outside_inner_locks() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let slot = srv_slot(60, 2); + let (generation, words) = begin_mutation_test(tracked_entry(0x6010, 0xA0), slot); + let snapshot = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let result = with_exact_tracked_srv_mutation_on( + slot, + generation, + |_, _| Some((snapshot, MutationOwner(Arc::clone(&drops)), MutationOwner(Arc::clone(&drops)))), + |_| Some(words), + |entry, _, _| { + assert_eq!(entry.resource, 0x6010); + assert!(SHARED_VIEW_EPOCHS.try_lock().is_err(), "epoch was not held outermost"); + assert!(TRACKED_SRV_WRITES.try_lock().is_err(), "WRITE was not held for mutation"); + assert!(TRACKED_SRVS.try_lock().is_ok(), "tracker lock crossed mutation"); + 17 + }, + ); + assert_eq!(result, Some(17)); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 2); + end_mutation_test(); + } + + #[test] + fn exact_srv_mutation_rejects_a_changed_generation_without_removing_it() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let slot = srv_slot(61, 1); + let (generation, words) = begin_mutation_test(tracked_entry(0x6110, 0xA4), slot); + let old = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let result = with_exact_tracked_srv_mutation_on( + slot, + generation, + |_, _| { + // Model a hooked overwrite after the owners were acquired but before WRITE. + TRACKED_SRVS.lock().unwrap().as_mut().unwrap().write(slot, Some(tracked_entry(0x6120, 0xA4))); + Some((old, MutationOwner(Arc::clone(&drops)), MutationOwner(Arc::clone(&drops)))) + }, + |_| Some(words), + |_, _, _| panic!("stale mutation ran"), + ); + assert_eq!(result, None); + let newer = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + assert_ne!(newer.generation, generation); + assert_eq!(newer.resource, 0x6120); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 2); + end_mutation_test(); + } + + #[test] + fn exact_srv_mutation_forgets_raw_mismatch_or_missing_heap_backing() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for missing in [false, true] { + let slot = srv_slot(62 + missing as u64, 0); + let (generation, words) = begin_mutation_test(tracked_entry(0x6210, 0xA8), slot); + let snapshot = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut changed = words; + changed[5] ^= 1; + let result = with_exact_tracked_srv_mutation_on( + slot, + generation, + |_, _| Some((snapshot, MutationOwner(Arc::clone(&drops)), MutationOwner(Arc::clone(&drops)))), + |_| (!missing).then_some(changed), + |_, _, _| panic!("invalid raw descriptor mutation ran"), + ); + assert_eq!(result, None); + assert!(!TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot.contains_key(&slot)); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 2); + end_mutation_test(); + } + } + + #[test] + fn exact_srv_mutation_fails_closed_when_resource_or_heap_lease_is_gone() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let slot = srv_slot(64, 0); + let (generation, _) = begin_mutation_test(tracked_entry(0x6410, 0xAC), slot); + let result = with_exact_tracked_srv_mutation_on( + slot, + generation, + |_, _| None::<(TrackedSrv, (), ())>, + |_| panic!("observed words without strong owners"), + |_, _, _| panic!("mutation ran without strong owners"), + ); + assert_eq!(result, None); + assert!(TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot.contains_key(&slot)); + end_mutation_test(); + } + #[test] fn tracked_srv_copy_requires_exact_source_words() { let mut tracked = TrackedSrvs::default(); From ff23e65c6cdd22b0483d7a04f345afe46014f992 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:33:51 -0800 Subject: [PATCH 215/265] D3D12.X: release sparse upload gate during fence waits Retain the exact native backing named by an accepted upload so the process-wide ownership gate can be released while its retirement fence is waited. A crossing uploader may reuse retired slots or ring space; the waiter only mutates exact unchanged state and otherwise rebuilds from the current generation. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 136 +++++++++++++++++++++++----- 1 file changed, 114 insertions(+), 22 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 819bc8f0a2..89c4199471 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -537,10 +537,26 @@ unsafe impl Send for State {} static STATE: Mutex<Option<State>> = Mutex::new(None); static NEXT_STATE_GENERATION: AtomicU64 = AtomicU64::new(1); -/// Upload allocators, lists and staging storage stay owned while `STATE` is released for a wait. -/// Lock order is `WAIT_GATES` → `UPLOAD_GATE` → `STATE`; initialization takes `PLACEMENT` first. +/// Serialize mutation of upload slots, staging cursors and retry journals. Fence waits release this +/// gate while a shared generation lifetime keeps their exact native backing. Lock order is +/// `WAIT_GATES` → `UPLOAD_STATE_LIFETIME` (shared) → `UPLOAD_GATE` → `STATE`; +/// initialization takes `PLACEMENT` then the lifetime lock exclusively before `UPLOAD_GATE`. static UPLOAD_GATE: Mutex<()> = Mutex::new(()); +/// A waiter keeps its exact `State` generation and all of that generation's native backing alive +/// while `UPLOAD_GATE` is released. Other uploaders take shared ownership and can cross the wait; +/// setup takes exclusive ownership before `UPLOAD_GATE` and cannot replace `STATE` meanwhile. +static UPLOAD_STATE_LIFETIME: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +type UploadGuard = std::sync::MutexGuard<'static, ()>; + +fn with_upload_gate_released<T>(guard: &mut Option<UploadGuard>, wait: impl FnOnce() -> T) -> T { + drop(guard.take()); + let result = wait(); + *guard = Some(UPLOAD_GATE.lock().unwrap()); + result +} + /// A placement may release `STATE` while the driver creates its reserved resource. Keep sparse /// state replacement and another placement from crossing that exact-state transaction. static PLACEMENT: Mutex<()> = Mutex::new(()); @@ -801,6 +817,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { // its last buffers reaches `forget_buffer`, which takes the lock (#344) // (the queue first: `queue()` never answers with one older than the state's) let _placement = PLACEMENT.lock().unwrap(); + let _upload_lifetime = UPLOAD_STATE_LIFETIME.write().unwrap(); let _uploads = UPLOAD_GATE.lock().unwrap(); let old_queue = QUEUE.lock().unwrap().replace(s.queue.clone()); let mut state = STATE.lock().unwrap(); @@ -1149,7 +1166,7 @@ impl State { } fn wait_ticket_owns_upload(&self, ticket: &WaitTicket) -> bool { - if self.generation != ticket.state_generation || self.fence.as_raw() != ticket.fence.as_raw() || !self.uploads_ordered { + if !self.wait_ticket_generation(ticket) { return false; } match ticket.kind { @@ -1163,6 +1180,12 @@ impl State { } } + fn wait_ticket_generation(&self, ticket: &WaitTicket) -> bool { + self.generation == ticket.state_generation + && self.fence.as_raw() == ticket.fence.as_raw() + && self.uploads_ordered + } + fn wait_ticket_valid(&self, ticket: &WaitTicket) -> bool { self.mapping_epoch == ticket.mapping_epoch && self.wait_ticket_owns_upload(ticket) } @@ -1641,7 +1664,8 @@ pub unsafe fn readback_now(va: usize, len: usize) { if len == 0 { return; } - let _uploads = UPLOAD_GATE.lock().unwrap(); + let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); + let mut uploads = Some(UPLOAD_GATE.lock().unwrap()); 'prepare: loop { let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; @@ -1656,9 +1680,12 @@ pub unsafe fn readback_now(va: usize, len: usize) { match s.upload_zeros(&zeroed) { UploadStep::Done(PreparationOutcome::Ready) => {} UploadStep::Wait(ticket) => { + // Publish the clear retry journal before another uploader can take the gate. It + // may consume it while this thread waits; after reacquiring, restart from state. s.to_zero.extend(zeroed); drop(g); - if wait_upload_released(&ticket) { continue 'prepare } else { return } + if !with_upload_gate_released(&mut uploads, || wait_upload_released(ticket)) { return } + continue 'prepare; } UploadStep::Done(_) => { s.to_zero.extend(zeroed); @@ -1690,8 +1717,11 @@ pub unsafe fn readback_now(va: usize, len: usize) { match s.upload_dirty(&dirty_runs) { UploadStep::Done(PreparationOutcome::Ready) => {} UploadStep::Wait(ticket) => { + // Dirty bytes were only observed, not removed from a journal. Another uploader + // may send them while this thread waits; restart and rescan current hashes. drop(g); - if wait_upload_released(&ticket) { continue 'prepare } else { return } + if !with_upload_gate_released(&mut uploads, || wait_upload_released(ticket)) { return } + continue 'prepare; } UploadStep::Done(_) => return, } @@ -2231,9 +2261,10 @@ fn rollback_queue_wait(waited: &mut FxHashMap<usize, u64>, queue: usize, value: } } -/// Wait with `STATE` released. `UPLOAD_GATE` keeps the ticket's allocator, list, staging and -/// destination owners alive; only an exact same-generation ticket may retire ring storage. -unsafe fn wait_upload_released(ticket: &WaitTicket) -> bool { +/// Wait with both `STATE` and `UPLOAD_GATE` released. The caller's shared generation lease keeps +/// every old-state allocator, list, staging byte and destination alive. Only an exact ticket may +/// retire ring storage; a crossing uploader otherwise makes the caller rebuild from current state. +unsafe fn wait_upload_released(ticket: WaitTicket) -> bool { loop { match crate::gpu::fence::wait(&ticket.fence, ticket.target, &ticket.dev, None, 5000) { Ok(()) => break, @@ -2246,17 +2277,29 @@ unsafe fn wait_upload_released(ticket: &WaitTicket) -> bool { } } } - let mut g = lock_state(); - let Some(s) = g.as_mut() else { return false }; - if !s.wait_ticket_owns_upload(ticket) { - return false; - } - // A concurrent commit/decommit/remap invalidates the mapping epoch. Do not apply the old - // ticket to ring state; the caller loops and rebuilds its upload from current mappings. - if s.wait_ticket_valid(ticket) { - s.reclaim_ring(); - } - true + let proceed = { + let mut g = lock_state(); + match g.as_mut() { + None => false, + Some(s) if s.generation != ticket.state_generation || s.fence.as_raw() != ticket.fence.as_raw() => { + // The caller's shared lifetime makes replacement impossible. Fail closed if a + // future teardown path violates that protocol. + false + } + Some(s) if !s.uploads_ordered => false, + Some(s) => { + // Another uploader can retire/reuse this slot or ring range after the waited + // target completes. That invalidates exact ownership but not the completed fence; + // loop on current state. Reclaim only if neither it nor a remap crossed this ticket. + if s.wait_ticket_valid(&ticket) { + s.reclaim_ring(); + } + true + } + } + }; + drop(ticket); + proceed } /// Snapshot strong fence owners under `STATE`, then query them without it. A batch or a higher @@ -2281,7 +2324,8 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], let t0 = look.is_some().then(std::time::Instant::now); let queue_gate = WAIT_GATES.lock().unwrap().entry(q).or_default().clone(); let _queue_serial = queue_gate.lock().unwrap(); - let _uploads = UPLOAD_GATE.lock().unwrap(); + let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); + let mut uploads = Some(UPLOAD_GATE.lock().unwrap()); let t_gated = t0.map(|_| std::time::Instant::now()); if let (Some(sample), Some(t0), Some(t_gated)) = (look.as_deref_mut(), t0, t_gated) { sample.add_time(QUEUE_WAIT_US, t_gated.duration_since(t0)); @@ -2401,10 +2445,13 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], dirty_runs.clear(); s.scratch_runs = dirty_runs; if let Some(ticket) = upload_wait { + // `to_zero` and `retry_pages` were restored above before ownership is released. Another + // queue may consume either journal; reacquisition is included in UPLOAD_WAIT_US and the + // next iteration always rebuilds its plan from current state. drop(g); drop(observed); let wait_started = t0.map(|_| std::time::Instant::now()); - if !wait_upload_released(&ticket) { + if !with_upload_gate_released(&mut uploads, || wait_upload_released(ticket)) { if let (Some(sample), Some(wait_started)) = (look.as_deref_mut(), wait_started) { sample.add_time(UPLOAD_WAIT_US, wait_started.elapsed()); } @@ -3586,6 +3633,47 @@ mod tests { } } + #[test] + fn upload_wait_releases_and_reacquires_its_ownership_gate() { + let (acquired_tx, acquired_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let mut guard = Some(UPLOAD_GATE.lock().unwrap()); + let worker = std::thread::spawn(move || { + let _crossing_uploader = UPLOAD_GATE.lock().unwrap(); + acquired_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + }); + let released = with_upload_gate_released(&mut guard, || { + let acquired = acquired_rx.recv_timeout(std::time::Duration::from_secs(1)).is_ok(); + release_tx.send(()).unwrap(); + worker.join().unwrap(); + acquired + }); + assert!(released, "another uploader could not cross the fence wait"); + assert!(UPLOAD_GATE.try_lock().is_err(), "the process upload gate was not reacquired"); + drop(guard); + } + + #[test] + fn replacement_waits_for_every_upload_generation_reader() { + let _placement = PLACEMENT.lock().unwrap(); + let lower_target = UPLOAD_STATE_LIFETIME.read().unwrap(); + let higher_target = UPLOAD_STATE_LIFETIME.read().unwrap(); + let (acquired_tx, acquired_rx) = std::sync::mpsc::channel(); + let replacement = std::thread::spawn(move || { + let _exclusive = UPLOAD_STATE_LIFETIME.write().unwrap(); + acquired_tx.send(()).unwrap(); + }); + + assert!(acquired_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err()); + drop(lower_target); + assert!(acquired_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), + "replacement passed the lower target while a higher upload was still in flight"); + drop(higher_target); + acquired_rx.recv_timeout(std::time::Duration::from_secs(1)).expect("replacement stayed blocked after every upload reader retired"); + replacement.join().unwrap(); + } + #[test] fn a_stalled_upload_ring_yields_without_publishing_hashes() { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; @@ -3614,6 +3702,7 @@ mod tests { assert!(s.wait_ticket_valid(&ticket)); s.mapping_epoch += 1; assert!(!s.wait_ticket_valid(&ticket), "a remapped destination accepted an old upload ticket"); + assert!(s.wait_ticket_generation(&ticket), "a remap invalidated the live state generation"); let after = s.mapped[&base].sent[0].as_ref().unwrap(); assert_eq!(after.as_ref(), &before, "a failed upload changed the published hash state"); @@ -3630,6 +3719,9 @@ mod tests { assert_eq!(s.next_slot, before_slot, "a busy slot advanced before its fence completed"); assert!(matches!(ticket.kind, WaitKind::Slot { index: 0, next_slot: 0, .. })); assert!(s.wait_ticket_owns_upload(&ticket)); + s.slots[0].fence_val += 1; + assert!(!s.wait_ticket_owns_upload(&ticket), "a reused slot accepted its predecessor ticket"); + assert!(s.wait_ticket_generation(&ticket), "safe slot reuse invalidated the live generation"); s.generation += 1; assert!(!s.wait_ticket_owns_upload(&ticket), "a replacement state accepted an old upload ticket"); s.uploads_ordered = false; From c58bf39a305db8500e5b2aa7e6539f2bcc3467a9 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:35:14 -0800 Subject: [PATCH 216/265] D3D12.X: detach evicted native pipeline generations Model recipe residency explicitly and add an uncalled eviction transition that atomically detaches the raw and generation owners while excluding rebuild publication. Exact recording pins remain independent, and COM owners are released only after every state lock is dropped. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 279 +++++++++++++++++++++++-- 1 file changed, 262 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 400ba4041b..e2bf20a903 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -467,6 +467,8 @@ fn complete(build: &Arc<Build>, real: usize) { if let Some(recipe) = &build.recipe { replaced_generation = recipe.publish(real).1; } + } else if let Some(recipe) = &build.recipe { + recipe.mark_failed(); } build.real.store(real, Ordering::Release); } @@ -501,6 +503,53 @@ enum RebuildRequest { Unavailable, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum EvictResult { + Evicted { generation: u64 }, + NotReady, + Active, + Abandoned, + Unavailable, + NotResident, +} + +/// Detach both owners of the current native generation. This remains deliberately uncalled until +/// a policy and a nonblocking rehydration path choose the correctness/performance tradeoff after +/// eviction. Exact recording and receipt pins independently keep the detached generation alive. +#[allow(dead_code)] +fn try_evict_current(build: &Build) -> EvictResult { + let done = build.done.lock().unwrap(); + if !*done { + return EvictResult::NotReady; + } + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + return EvictResult::Abandoned; + } + let Some(recipe) = build.recipe.as_ref() else { return EvictResult::Unavailable }; + // Keep the rebuild turn reserved through the raw-owner swap. Every rebuild reservation takes + // this lock, and publication takes `done`, so neither transition can cross this one. + let rebuild = recipe.0.rebuild.lock().unwrap(); + if rebuild.active || rebuild.waiters != 0 { + return EvictResult::Active; + } + let raw = build.real.load(Ordering::Acquire); + if raw == 0 { + return EvictResult::NotResident; + } + let Some(generation) = recipe.detach_current(raw) else { return EvictResult::NotResident }; + let generation_id = generation.id(); + let old_raw = build.real.swap(0, Ordering::AcqRel); + debug_assert_eq!(old_raw, raw); + drop(rebuild); + drop(done); + + // COM Release can re-enter pipeline bookkeeping. Drop both owners outside every state lock; + // an exact recording/receipt pin is another Arc to `generation` and survives independently. + drop(generation); + release(old_raw); + EvictResult::Evicted { generation: generation_id } +} + /// Build and atomically publish one replacement generation. This remains deliberately uncalled /// until submitted recording pins are retained to exact GPU retirement receipts: publication is /// safe, but a policy must not make an old generation reclaimable while the GPU can still use it. @@ -724,10 +773,19 @@ struct Generation<T> { struct GenerationSlot<T> { next: u64, resident: Option<Arc<Generation<T>>>, + residency: Residency, } impl<T> Default for GenerationSlot<T> { - fn default() -> Self { Self { next: 0, resident: None } } + fn default() -> Self { Self { next: 0, resident: None, residency: Residency::Rebuilding } } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Residency { + Resident, + Evicted, + Rebuilding, + Failed, } impl<T> GenerationSlot<T> { @@ -735,12 +793,43 @@ impl<T> GenerationSlot<T> { self.next = self.next.checked_add(1).expect("pipeline generation id exhausted"); let generation = Arc::new(Generation { id: self.next, raw, _owner: owner }); let replaced = self.resident.replace(generation.clone()); + self.residency = Residency::Resident; (generation, replaced) } fn pin(&self, raw: usize) -> Option<Arc<Generation<T>>> { self.resident.as_ref().filter(|generation| generation.raw == raw).cloned() } + + fn mark_rebuilding(&mut self) -> Residency { + let previous = self.residency; + self.residency = Residency::Rebuilding; + previous + } + + fn finish_rebuild(&mut self, result: RebuildResult, previous: Option<Residency>) { + self.residency = if self.resident.is_some() { + Residency::Resident + } else { + match result { + RebuildResult::Failed => Residency::Failed, + RebuildResult::Abandoned | RebuildResult::NotReady => match previous { + Some(Residency::Evicted) => Residency::Evicted, + Some(Residency::Failed) => Residency::Failed, + _ => Residency::Failed, + }, + RebuildResult::Published { .. } => Residency::Failed, + } + }; + } + + fn detach(&mut self, raw: usize) -> Option<Arc<Generation<T>>> { + if self.residency != Residency::Resident || self.resident.as_ref()?.raw != raw { + return None; + } + self.residency = Residency::Evicted; + self.resident.take() + } } struct RecipeInner { @@ -756,6 +845,7 @@ struct RebuildState { completed: u64, waiters: usize, last: Option<RebuildResult>, + from: Option<Residency>, } #[derive(Debug)] @@ -896,8 +986,20 @@ impl Recipe { (NativeGeneration(generation), replaced.map(NativeGeneration)) } - fn pin(&self, raw: usize) -> Option<NativeGeneration> { - self.0.generation.lock().unwrap().pin(raw).map(NativeGeneration) + fn pin_with_residency(&self, raw: usize) -> (Option<NativeGeneration>, Residency) { + let generation = self.0.generation.lock().unwrap(); + (generation.pin(raw).map(NativeGeneration), generation.residency) + } + + fn mark_failed(&self) { + let mut generation = self.0.generation.lock().unwrap(); + if generation.resident.is_none() { + generation.residency = Residency::Failed; + } + } + + fn detach_current(&self, raw: usize) -> Option<NativeGeneration> { + self.0.generation.lock().unwrap().detach(raw).map(NativeGeneration) } fn initial_job(&self) -> Job { @@ -910,6 +1012,7 @@ impl Recipe { loop { if !state.active && state.waiters == 0 { state.active = true; + state.from = Some(self.0.generation.lock().unwrap().mark_rebuilding()); return RebuildTurn::Leader; } if state.active { @@ -938,11 +1041,13 @@ impl Recipe { return false; } state.active = true; + state.from = Some(self.0.generation.lock().unwrap().mark_rebuilding()); true } fn finish_rebuild(&self, result: RebuildResult) { let mut state = self.0.rebuild.lock().unwrap(); + self.0.generation.lock().unwrap().finish_rebuild(result, state.from.take()); state.last = Some(result); state.active = false; state.completed = state.completed.checked_add(1).expect("pipeline rebuild serial exhausted"); @@ -1746,7 +1851,8 @@ mod used_tests { next.store(0, Ordering::Release); assert_eq!(rebuild_once(&build), Some(RebuildResult::Failed)); assert_eq!(build.real.load(Ordering::Acquire), first_raw); - assert_eq!(recipe.pin(first_raw).unwrap().id(), 1); + assert_eq!(recipe.pin_with_residency(first_raw).0.unwrap().id(), 1); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Resident); next.store(second_raw, Ordering::Release); assert_eq!(rebuild_once(&build), Some(RebuildResult::Published { generation: 2 })); @@ -1762,6 +1868,136 @@ mod used_tests { assert_eq!(second.refs.load(Ordering::Relaxed), 0); } + #[test] + fn eviction_detaches_both_native_owners_but_an_exact_pin_survives() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + let pin = recipe.pin_with_residency(raw).0.expect("resident generation"); + + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + assert_eq!(build.real.load(Ordering::Acquire), 0); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Evicted); + assert!(recipe.pin_with_residency(raw).0.is_none(), "evicted generation remained current"); + assert_eq!(native.refs.load(Ordering::Relaxed), 1, "the exact pin did not retain the native object"); + assert_eq!(try_evict_current(&build), EvictResult::NotResident, "repeated eviction detached another owner"); + + drop(pin); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn eviction_between_resolution_and_pinning_falls_back_from_the_stale_raw() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let standin = 0x7E57_C154usize; + let recipe = Recipe::new(move || raw); + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + + // Deterministically interleave eviction in the real resolver's gap: it observed `raw`, + // but has not yet taken Build.done and converted that observation into an exact pin. + let resolved = resolve_pending(&pending, standin); + let bound_unbuilt = pending.bound_unbuilt(standin, resolved); + assert_eq!((resolved, bound_unbuilt), (raw, false)); + assert_eq!(try_evict_current(&pending.build), EvictResult::Evicted { generation: 1 }); + assert_eq!(native.refs.load(Ordering::Relaxed), 0, "eviction did not release both unpinned owners"); + + let (chosen, pin, stale_fallback) = pin_resolved(standin, &pending, resolved, bound_unbuilt); + assert_eq!(chosen, standin, "pin validation returned the freed pre-eviction raw pointer"); + assert!(pin.is_none()); + assert!(stale_fallback, "ExecuteIndirect must treat an eviction fallback as unbuilt"); + assert_eq!(released(standin), 0); + } + + #[test] + fn steady_evicted_compute_resolution_remains_fail_closed_as_unbuilt() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let standin = 0x7E57_C155usize; + let recipe = Recipe::new(move || raw); + submit_recipe_keyed(standin, true, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + assert_eq!(try_evict_current(&pending.build), EvictResult::Evicted { generation: 1 }); + + let ((chosen, bound_unbuilt), pin) = resolve_wait_bound_and_pin(standin); + assert_eq!((chosen, bound_unbuilt), (standin, true)); + assert!(pin.is_none()); + assert_eq!(released(standin), 0); + drop(pending); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn eviction_refuses_an_active_rebuild_and_restores_resident_state_on_failure() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + + assert!(matches!(recipe.begin_rebuild(), RebuildTurn::Leader)); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Rebuilding); + assert_eq!(try_evict_current(&build), EvictResult::Active); + assert_eq!(build.real.load(Ordering::Acquire), raw); + recipe.finish_rebuild(RebuildResult::Failed); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Resident); + + let final_raw = build.real.swap(0, Ordering::AcqRel); + drop(build); + drop(recipe); + release(final_raw); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn eviction_refuses_a_build_after_its_last_title_owner_releases() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let standin = 0x7E57_C153usize; + let recipe = Recipe::new(move || raw); + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + + let final_raw = released(standin); + assert_eq!(try_evict_current(&pending.build), EvictResult::Abandoned); + release(final_raw); + drop(pending); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn failed_initial_recipe_has_no_evictable_residency() { + let standin = 0x7E57_C156usize; + let recipe = Recipe::new(|| 0); + submit_recipe_keyed(standin, true, recipe.clone(), false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Failed); + assert_eq!(try_evict_current(&pending.build), EvictResult::NotResident); + let ((chosen, bound_unbuilt), pin) = resolve_wait_bound_and_pin(standin); + assert_eq!((chosen, bound_unbuilt), (standin, false), "a real build failure changed to transient-unbuilt"); + assert!(pin.is_none()); + assert_eq!(released(standin), 0); + } + #[test] fn release_during_rebuild_abandons_and_releases_the_new_raw() { let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; @@ -1880,7 +2116,7 @@ mod used_tests { assert_eq!(request_rebuild_on(build.clone(), &q), RebuildRequest::Queued); assert!(q.try_run_one_between(Priority::Speculative, Priority::Speculative)); assert_eq!(build.real.load(Ordering::Acquire), first_raw); - assert_eq!(recipe.pin(first_raw).unwrap().id(), 1); + assert_eq!(recipe.pin_with_residency(first_raw).0.unwrap().id(), 1); let final_raw = build.real.swap(0, Ordering::AcqRel); drop(build); @@ -3262,25 +3498,34 @@ fn resolve_and_pin_pending(pso: usize, p: &Arc<Pending>, mode: ResolveMode) -> ( ResolveMode::ForBind => resolve_pending(p, pso), }; let bound_unbuilt = p.bound_unbuilt(pso, resolved); - pin_resolved(p, resolved, bound_unbuilt) + let (resolved, generation, _) = pin_resolved(pso, p, resolved, bound_unbuilt); + (resolved, generation) } -fn pin_resolved(p: &Pending, resolved: usize, bound_unbuilt: bool) -> (usize, Option<NativeGeneration>) { - let Some(recipe) = p.build.recipe.as_ref() else { return (resolved, None) }; +fn pin_resolved(pso: usize, p: &Pending, resolved: usize, bound_unbuilt: bool) -> (usize, Option<NativeGeneration>, bool) { + let Some(recipe) = p.build.recipe.as_ref() else { return (resolved, None, false) }; let _done = p.build.done.lock().unwrap(); let current = p.build.real.load(Ordering::Acquire); if current == resolved { - return (resolved, recipe.pin(resolved)); + let (generation, residency) = recipe.pin_with_residency(resolved); + let unavailable = generation.is_none() && matches!(residency, Residency::Evicted | Residency::Rebuilding); + return (resolved, generation, unavailable); } // Preserve a resolver's deliberate stand-in choice. If an eventual rebuild replaced a - // native generation between resolution and this lock, select and pin the current publication - // instead of returning an ownerless stale raw pointer. + // native generation between resolution and this lock, select and pin the current publication. + // Eviction can instead leave no publication: fail closed to the retained stand-in, never the + // ownerless raw pointer which resolution observed before it took this lock. if bound_unbuilt { - return (resolved, None); + return (resolved, None, false); } - match recipe.pin(current) { - Some(generation) => (current, Some(generation)), - None => (resolved, None), + let (generation, residency) = recipe.pin_with_residency(current); + match generation { + Some(generation) => (current, Some(generation), false), + None => { + let stand = p.stand(pso); + let unavailable = resolved != stand || matches!(residency, Residency::Evicted | Residency::Rebuilding); + (stand, None, unavailable) + } } } @@ -3313,8 +3558,8 @@ fn resolve_wait_bound_and_pin(pso: usize) -> ((usize, bool), Option<NativeGenera p.note_use(); let bound = resolve_wait_pending(&p, pso, wait_budget()); let choice = (bound, p.bound_unbuilt(pso, bound)); - let (resolved, generation) = pin_resolved(&p, choice.0, choice.1); - ((resolved, choice.1), generation) + let (resolved, generation, stale_fallback) = pin_resolved(pso, &p, choice.0, choice.1); + ((resolved, choice.1 || stale_fallback), generation) } /// The title released stand-in `pso` for good: forget it (its address may come back for From ab6b3950a5c65f070d9c68e4f4ec7909cee8a908 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:47:49 -0800 Subject: [PATCH 217/265] D3D12.X: split sparse upload gate timing Separate upload-gate acquisition and hold time for title submission preparation from synchronous readback work under XCL_ACTIVITY. Released readback waits include fence retirement and gate reacquisition, while the disabled path performs no clock reads or counter updates. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 3 +- crates/xcl/src/hle/d3d12x/sparse.rs | 176 +++++++++++++++++++++++++--- 2 files changed, 161 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index d82e975104..713ce71de6 100644 --- a/README.md +++ b/README.md @@ -332,7 +332,8 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder pipelines retained behind stand-ins and how many frames ago they were last used, and the active foreground time plus serialization wait spent looking for CPU writes before submits (write-watch bytes/ranges/pages, - sparse queue/fence-state/copy phases and zero/dirty volume, and other refresh work). A negative + sparse queue/fence-state/copy phases and zero/dirty volume, upload-gate wait/hold time split + between submit preparation and synchronous readback, and other refresh work). A negative `other` exposes an overlapping or stale sample; unavailable adapter segments say `unknown`. Where the lines stop changing is where the title stopped. - `XCL_THREAD_DUMP_AT=s1,s2,…`: at each of those seconds after the start, the state of every diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 89c4199471..9fd6d6e775 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -550,11 +550,50 @@ static UPLOAD_STATE_LIFETIME: std::sync::RwLock<()> = std::sync::RwLock::new(()) type UploadGuard = std::sync::MutexGuard<'static, ()>; -fn with_upload_gate_released<T>(guard: &mut Option<UploadGuard>, wait: impl FnOnce() -> T) -> T { - drop(guard.take()); - let result = wait(); - *guard = Some(UPLOAD_GATE.lock().unwrap()); - result +#[derive(Clone, Copy, Default)] +struct UploadGateTimes { + wait_us: u64, + hold_us: u64, + released_us: u64, +} + +struct UploadGateTiming { + enabled: bool, + held_since: Option<std::time::Instant>, + times: UploadGateTimes, +} + +impl UploadGateTiming { + fn acquire(enabled: bool) -> (Option<UploadGuard>, Self) { + let waiting = enabled.then(std::time::Instant::now); + let guard = UPLOAD_GATE.lock().unwrap(); + let acquired = enabled.then(std::time::Instant::now); + let wait_us = waiting.zip(acquired).map_or(0, |(waiting, acquired)| acquired.duration_since(waiting).as_micros() as u64); + (Some(guard), Self { enabled, held_since: acquired, times: UploadGateTimes { wait_us, ..Default::default() } }) + } + + fn with_released<T>(&mut self, guard: &mut Option<UploadGuard>, wait: impl FnOnce() -> T) -> T { + let released = self.enabled.then(std::time::Instant::now); + if let (Some(held_since), Some(released)) = (self.held_since.take(), released) { + self.times.hold_us = self.times.hold_us.wrapping_add(released.duration_since(held_since).as_micros() as u64); + } + drop(guard.take()); + let result = wait(); + *guard = Some(UPLOAD_GATE.lock().unwrap()); + let acquired = self.enabled.then(std::time::Instant::now); + if let (Some(released), Some(acquired)) = (released, acquired) { + self.times.released_us = self.times.released_us.wrapping_add(acquired.duration_since(released).as_micros() as u64); + } + self.held_since = acquired; + result + } + + fn finish(mut self) -> UploadGateTimes { + if let Some(held_since) = self.held_since.take() { + self.times.hold_us = self.times.hold_us.wrapping_add(held_since.elapsed().as_micros() as u64); + } + self.times + } } /// A placement may release `STATE` while the driver creates its reserved resource. Keep sparse @@ -1629,7 +1668,17 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz if ranges.is_empty() { return; } - let _uploads = UPLOAD_GATE.lock().unwrap(); + let measure = super::memory_report::enabled(); + let (mut uploads, timing) = UploadGateTiming::acquire(measure); + readback_after_execute_locked(queue, ranges); + let times = timing.finish(); + drop(uploads.take()); + if measure { + note_readback_gate(times); + } +} + +unsafe fn readback_after_execute_locked(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)]) { let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); @@ -1664,8 +1713,21 @@ pub unsafe fn readback_now(va: usize, len: usize) { if len == 0 { return; } + let measure = super::memory_report::enabled(); let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); - let mut uploads = Some(UPLOAD_GATE.lock().unwrap()); + let (mut uploads, mut timing) = UploadGateTiming::acquire(measure); + readback_now_locked(va, len, &mut uploads, &mut timing); + let times = timing.finish(); + drop(uploads.take()); + drop(_upload_lifetime); + if measure { + note_readback_gate(times); + } +} + +unsafe fn readback_now_locked( + va: usize, len: usize, uploads: &mut Option<UploadGuard>, timing: &mut UploadGateTiming, +) { 'prepare: loop { let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; @@ -1684,7 +1746,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { // may consume it while this thread waits; after reacquiring, restart from state. s.to_zero.extend(zeroed); drop(g); - if !with_upload_gate_released(&mut uploads, || wait_upload_released(ticket)) { return } + if !timing.with_released(uploads, || wait_upload_released(ticket)) { return } continue 'prepare; } UploadStep::Done(_) => { @@ -1720,7 +1782,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { // Dirty bytes were only observed, not removed from a journal. Another uploader // may send them while this thread waits; restart and rescan current hashes. drop(g); - if !with_upload_gate_released(&mut uploads, || wait_upload_released(ticket)) { return } + if !timing.with_released(uploads, || wait_upload_released(ticket)) { return } continue 'prepare; } UploadStep::Done(_) => return, @@ -2113,7 +2175,7 @@ pub fn mapped_ranges() -> Vec<(usize, usize)> { s.runs.clone().unwrap_or_default() } -const LOOK_FIELDS: usize = 14; +const LOOK_FIELDS: usize = 19; const ACTIVE_US: usize = 0; const REFRESH_WAIT_US: usize = 1; const WATCH_US: usize = 2; @@ -2128,6 +2190,11 @@ const UPLOAD_US: usize = 10; const RUNS: usize = 11; const TRANSFER_BYTES: usize = 12; const UPLOAD_WAIT_US: usize = 13; +const SUBMIT_GATE_WAIT_US: usize = 14; +const SUBMIT_GATE_HOLD_US: usize = 15; +const READBACK_GATE_WAIT_US: usize = 16; +const READBACK_GATE_HOLD_US: usize = 17; +const READBACK_GATE_RELEASED_US: usize = 18; /// One complete `XCL_ACTIVITY` look. It is built without shared updates, then published once so /// the reporting thread cannot split one look across adjacent intervals. @@ -2153,6 +2220,21 @@ fn merge_look(total: &mut [u64; LOOK_FIELDS], sample: [u64; LOOK_FIELDS]) { } } +fn add_gate_times(sample: &mut [u64; LOOK_FIELDS], wait: usize, hold: usize, released: Option<usize>, times: UploadGateTimes) { + sample[wait] = sample[wait].wrapping_add(times.wait_us); + sample[hold] = sample[hold].wrapping_add(times.hold_us); + if let Some(released) = released { + sample[released] = sample[released].wrapping_add(times.released_us); + } +} + +fn note_readback_gate(times: UploadGateTimes) { + let mut total = LOOK.lock().unwrap(); + add_gate_times( + &mut total, READBACK_GATE_WAIT_US, READBACK_GATE_HOLD_US, Some(READBACK_GATE_RELEASED_US), times, + ); +} + pub(super) fn note_watch(sample: &mut LookSample, t: std::time::Duration, pages: usize, watched: usize, ranges: usize) { sample.add_time(WATCH_US, t); sample.add(PAGES, pages as u64); @@ -2178,11 +2260,15 @@ pub fn look_delta(now: [u64; LOOK_FIELDS], before: [u64; LOOK_FIELDS]) -> [u64; /// Active foreground elapsed time and serialization wait before title submits in one interval. pub fn look_line(d: [u64; LOOK_FIELDS], secs: u64) -> String { - let [active, refresh_wait, watch, pages, looks, watched, ranges, queue_wait, maintenance, scan, upload, runs, transfer_bytes, upload_wait] = d; + let [ + active, refresh_wait, watch, pages, looks, watched, ranges, queue_wait, maintenance, scan, upload, + runs, transfer_bytes, upload_wait, submit_gate_wait, submit_gate_hold, readback_gate_wait, + readback_gate_hold, readback_gate_released, + ] = d; let ms = |us: u64| us / 1000; let sparse = queue_wait.saturating_add(maintenance).saturating_add(scan).saturating_add(upload).saturating_add(upload_wait); format!( - "looks before submits ({secs} s): {looks} looks did {} ms active work ({:.1} % of the time) after {} ms waiting for the refresh turn: write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); sparse queue wait/fence+state/scan/upload/ownership wait {}/{}/{}/{}/{} ms ({runs} runs, {:.1} MB zero/dirty bytes); other active work {} ms", + "looks before submits ({secs} s): {looks} looks did {} ms active work ({:.1} % of the time) after {} ms waiting for the refresh turn: write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); sparse queue wait/fence+state/scan/upload/ownership wait {}/{}/{}/{}/{} ms ({runs} runs, {:.1} MB zero/dirty bytes); upload gate submit wait/hold {}/{} ms, readback wait/hold/released wait+reacquire {}/{}/{} ms; other active work {} ms", ms(active), active as f64 / (secs.max(1) * 10_000) as f64, ms(refresh_wait), @@ -2195,6 +2281,11 @@ pub fn look_line(d: [u64; LOOK_FIELDS], secs: u64) -> String { ms(upload), ms(upload_wait), transfer_bytes as f64 / (1 << 20) as f64, + ms(submit_gate_wait), + ms(submit_gate_hold), + ms(readback_gate_wait), + ms(readback_gate_hold), + ms(readback_gate_released), ms(active.saturating_sub(watch.saturating_add(sparse))) ) } @@ -2325,11 +2416,30 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], let queue_gate = WAIT_GATES.lock().unwrap().entry(q).or_default().clone(); let _queue_serial = queue_gate.lock().unwrap(); let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); - let mut uploads = Some(UPLOAD_GATE.lock().unwrap()); + let (mut uploads, mut timing) = UploadGateTiming::acquire(look.is_some()); let t_gated = t0.map(|_| std::time::Instant::now()); if let (Some(sample), Some(t0), Some(t_gated)) = (look.as_deref_mut(), t0, t_gated) { sample.add_time(QUEUE_WAIT_US, t_gated.duration_since(t0)); } + let outcome = before_execute_locked(queue, dirty, page, q, t0, &mut look, &mut uploads, &mut timing); + let times = timing.finish(); + drop(uploads.take()); + if let Some(sample) = look.as_deref_mut() { + add_gate_times(&mut sample.0, SUBMIT_GATE_WAIT_US, SUBMIT_GATE_HOLD_US, None, times); + } + outcome +} + +unsafe fn before_execute_locked( + queue: &ID3D12CommandQueue, + dirty: &[usize], + page: usize, + q: usize, + t0: Option<std::time::Instant>, + look: &mut Option<&mut LookSample>, + uploads: &mut Option<UploadGuard>, + timing: &mut UploadGateTiming, +) -> PreparationOutcome { let mut metric_runs = look.is_some().then(|| (BTreeMap::new(), BTreeMap::new())); 'prepare: loop { let t_started = t0.map(|_| std::time::Instant::now()); @@ -2451,7 +2561,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], drop(g); drop(observed); let wait_started = t0.map(|_| std::time::Instant::now()); - if !with_upload_gate_released(&mut uploads, || wait_upload_released(ticket)) { + if !timing.with_released(uploads, || wait_upload_released(ticket)) { if let (Some(sample), Some(wait_started)) = (look.as_deref_mut(), wait_started) { sample.add_time(UPLOAD_WAIT_US, wait_started.elapsed()); } @@ -2658,10 +2768,16 @@ mod tests { 90, 96 << 20, 20_000, + 5_000, + 105_000, + 3_000, + 70_000, + 12_000, ], 2); assert!(line.contains("240 looks did 830 ms active work (41.5 % of the time) after 120 ms waiting"), "{line}"); assert!(line.contains("write-watch 610 ms (1641.0 MB in 69.0 ranges/look, 4800 pages written)"), "{line}"); - assert!(line.contains("sparse queue wait/fence+state/scan/upload/ownership wait 10/30/40/40/20 ms (90 runs, 96.0 MB zero/dirty bytes); other active work 80 ms"), "{line}"); + assert!(line.contains("sparse queue wait/fence+state/scan/upload/ownership wait 10/30/40/40/20 ms (90 runs, 96.0 MB zero/dirty bytes)"), "{line}"); + assert!(line.contains("upload gate submit wait/hold 5/105 ms, readback wait/hold/released wait+reacquire 3/70/12 ms; other active work 80 ms"), "{line}"); let idle = look_line([0; LOOK_FIELDS], 2); assert!(idle.contains("0 looks did 0 ms active work (0.0 % of the time) after 0 ms waiting"), "{idle}"); assert!(idle.contains("0.0 MB in 0.0 ranges/look"), "{idle}"); @@ -2672,6 +2788,30 @@ mod tests { assert_eq!(look_delta([0; LOOK_FIELDS], [u64::MAX; LOOK_FIELDS]), [1; LOOK_FIELDS]); } + #[test] + fn upload_gate_times_accumulate_into_distinct_submit_and_readback_fields() { + let mut sample = [0; LOOK_FIELDS]; + add_gate_times( + &mut sample, + SUBMIT_GATE_WAIT_US, + SUBMIT_GATE_HOLD_US, + None, + UploadGateTimes { wait_us: 11, hold_us: 22, released_us: 33 }, + ); + add_gate_times( + &mut sample, + READBACK_GATE_WAIT_US, + READBACK_GATE_HOLD_US, + Some(READBACK_GATE_RELEASED_US), + UploadGateTimes { wait_us: 44, hold_us: 55, released_us: 66 }, + ); + assert_eq!(sample[SUBMIT_GATE_WAIT_US], 11); + assert_eq!(sample[SUBMIT_GATE_HOLD_US], 22); + assert_eq!(sample[READBACK_GATE_WAIT_US], 44); + assert_eq!(sample[READBACK_GATE_HOLD_US], 55); + assert_eq!(sample[READBACK_GATE_RELEASED_US], 66); + } + #[test] fn retried_upload_ranges_are_counted_once() { let mut zero = BTreeMap::new(); @@ -3637,13 +3777,13 @@ mod tests { fn upload_wait_releases_and_reacquires_its_ownership_gate() { let (acquired_tx, acquired_rx) = std::sync::mpsc::channel(); let (release_tx, release_rx) = std::sync::mpsc::channel(); - let mut guard = Some(UPLOAD_GATE.lock().unwrap()); + let (mut guard, mut timing) = UploadGateTiming::acquire(false); let worker = std::thread::spawn(move || { let _crossing_uploader = UPLOAD_GATE.lock().unwrap(); acquired_tx.send(()).unwrap(); release_rx.recv().unwrap(); }); - let released = with_upload_gate_released(&mut guard, || { + let released = timing.with_released(&mut guard, || { let acquired = acquired_rx.recv_timeout(std::time::Duration::from_secs(1)).is_ok(); release_tx.send(()).unwrap(); worker.join().unwrap(); @@ -3651,6 +3791,8 @@ mod tests { }); assert!(released, "another uploader could not cross the fence wait"); assert!(UPLOAD_GATE.try_lock().is_err(), "the process upload gate was not reacquired"); + let times = timing.finish(); + assert_eq!((times.wait_us, times.hold_us, times.released_us), (0, 0, 0), "disabled timing read the clock"); drop(guard); } From 0bd24ca703d09b212a693b314d1ca1495137513e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:48:50 -0800 Subject: [PATCH 218/265] D3D12.X: batch exact descriptor mutation leases Amortize queue quiescence and descriptor-write exclusion across a deterministic set of tracked SRV generations. Each candidate keeps exact resource and heap owners, is revalidated against its logical generation and raw words, and drops every owner outside tracker and write locks. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/vram.rs | 270 ++++++++++++++++++++++++++++++ 1 file changed, 270 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 8775d3bddf..921e9596cd 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -563,6 +563,114 @@ fn with_exact_tracked_srv_mutation_on<T, Resource, Heap>( .flatten() } +/// One exact tracked descriptor and the native owners which make its resource and heap safe to +/// use during a batch mutation. +#[allow(dead_code)] // consumed by the later descriptor-rewrite policy +struct ExactSrvMutation<'a, Resource, Heap> { + entry: TrackedSrv, + resource: &'a Resource, + heap: &'a Heap, +} + +/// Execute one point-in-time mutation of a batch of tracked SRV generations. One quiescent epoch +/// and one descriptor-write exclusion cover the whole batch; missing leases and stale candidates +/// fail closed independently, in the caller's deterministic order. The operation is not called if +/// no candidate survives revalidation. The supplied operation has the same restrictions as +/// `with_exact_tracked_srv_mutation`: it must use only unhooked descriptor operations and must not +/// submit work or reserve another shared-view epoch. +/// +/// Raw title descriptor writes remain outside XCL's exclusion. All eight words are observed under +/// `WRITE` immediately before the operation, but title code can still race after that point; a +/// future policy must obey the title's descriptor-lifetime rules. +#[allow(dead_code)] // consumed by the later descriptor-rewrite policy +fn with_exact_tracked_srv_mutations<T>( + candidates: &[(SrvSlot, u64)], + mutate: impl FnOnce(&[ExactSrvMutation<'_, ID3D12Resource, super::console_heap::ViewSlotLease>]) -> T, +) -> Option<T> { + with_exact_tracked_srv_mutations_on( + candidates, + lease_tracked_srv_resource, + |slots| super::console_heap::view_slot_words(slots), + mutate, + ) +} + +fn with_exact_tracked_srv_mutations_on<T, Resource, Heap>( + candidates: &[(SrvSlot, u64)], + mut lease: impl FnMut(SrvSlot, u64) -> Option<(TrackedSrv, Resource, Heap)>, + observe_words: impl FnOnce(&[(u64, u32)]) -> Vec<Option<[u32; 8]>>, + mutate: impl FnOnce(&[ExactSrvMutation<Resource, Heap>]) -> T, +) -> Option<T> { + if !srv_tracking_enabled() { + return None; + } + let mut seen = HashSet::new(); + let candidates: Vec<_> = candidates.iter().copied().filter(|candidate| seen.insert(*candidate)).collect(); + if candidates.is_empty() { + return None; + } + with_quiescent_shared_view_heap(|| { + let leased: Vec<_> = candidates + .into_iter() + .filter_map(|(slot, generation)| lease(slot, generation).map(|(snapshot, resource, heap)| { + (slot, generation, snapshot, resource, heap) + })) + .collect(); + if leased.is_empty() { + return None; + } + let slots: Vec<_> = leased.iter().map(|(slot, ..)| (slot.heap_generation, slot.slot)).collect(); + + // `leased` owns every native object and was declared before `write`: unwind therefore + // drops the later-declared guard first, even for candidates rejected below. + let mut valid = Vec::with_capacity(leased.len()); + let write = lock_tracked_srv_write()?; + let observed = observe_words(&slots); + let mut validated = Vec::with_capacity(leased.len()); + { + let mut tracked = TRACKED_SRVS.lock().unwrap(); + let tracked = tracked.as_mut()?; + for (i, (slot, generation, snapshot, ..)) in leased.iter().enumerate() { + let Some(current) = tracked.by_slot.get(slot).copied() else { + validated.push(None); + continue; + }; + if current.generation != *generation { + validated.push(None); + continue; + } + let words = observed.get(i).copied().flatten(); + if words != Some(current.words) { + // `current` was read under this mutex and still names the requested exact + // generation, so removal cannot erase a concurrent replacement. + tracked.by_slot.remove(slot); + validated.push(None); + continue; + } + debug_assert_eq!(snapshot.generation, current.generation); + validated.push(Some(current)); + } + } + for ((_, _, _, resource, heap), entry) in leased.iter().zip(validated) { + if let Some(entry) = entry { + valid.push(ExactSrvMutation { entry, resource, heap }); + } + } + if valid.is_empty() { + drop(write); + drop(valid); + drop(leased); + return None; + } + let result = mutate(&valid); + drop(write); + drop(valid); + drop(leased); + Some(result) + }) + .flatten() +} + /// An exact, on-demand snapshot for a future residency consumer. It is deliberately not on the /// submit path: scanning every live SRV there would turn descriptor count into foreground cost. /// A consumer must still capture descriptor generations with recorded lists and queue fences; @@ -2628,6 +2736,30 @@ mod tests { } } + struct UnwindMutationOwner { + drops: Arc<std::sync::atomic::AtomicUsize>, + unlocked: Arc<std::sync::atomic::AtomicUsize>, + } + + impl Drop for UnwindMutationOwner { + fn drop(&mut self) { + use std::sync::TryLockError; + let available = |mutex: &'static Mutex<()>| match mutex.try_lock() { + Ok(guard) => { drop(guard); true } + Err(TryLockError::Poisoned(error)) => { drop(error.into_inner()); true } + Err(TryLockError::WouldBlock) => false, + }; + let write = available(&TRACKED_SRV_WRITES) as usize; + let tracker = match TRACKED_SRVS.try_lock() { + Ok(guard) => { drop(guard); true } + Err(TryLockError::Poisoned(error)) => { drop(error.into_inner()); true } + Err(TryLockError::WouldBlock) => false, + } as usize; + self.unlocked.fetch_or(write | tracker << 1, std::sync::atomic::Ordering::Relaxed); + self.drops.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + fn begin_mutation_test(entry: TrackedSrv, slot: SrvSlot) -> (u64, [u32; 8]) { SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); *SHARED_VIEW_EPOCHS.lock().unwrap() = SharedViewEpochs::new(); @@ -2736,6 +2868,144 @@ mod tests { end_mutation_test(); } + #[test] + fn exact_srv_batch_deduplicates_and_revalidates_mixed_candidates_once() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + *SHARED_VIEW_EPOCHS.lock().unwrap() = SharedViewEpochs::new(); + let (a, b, c, d, e) = ( + srv_slot(70, 0), srv_slot(70, 1), srv_slot(70, 2), srv_slot(70, 3), srv_slot(70, 4), + ); + let mut tracked = TrackedSrvs::default(); + for (slot, resource, pc) in [(a, 0xA010, 0xB0), (b, 0xB010, 0xB4), (c, 0xC010, 0xB8), (d, 0xD010, 0xBC), (e, 0xE010, 0xC0)] { + tracked.write(slot, Some(tracked_entry(resource, pc))); + } + let old_b = tracked.by_slot[&b]; + let snapshots = tracked.by_slot.clone(); + tracked.write(b, Some(tracked_entry(0xB020, 0xB4))); + let newer_b = tracked.by_slot[&b]; + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + + let candidates = [ + (a, snapshots[&a].generation), + (a, snapshots[&a].generation), + (b, old_b.generation), + (c, snapshots[&c].generation), + (d, snapshots[&d].generation), + (e, snapshots[&e].generation), + ]; + let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut lease_calls = Vec::new(); + let mut observations = 0; + let result = with_exact_tracked_srv_mutations_on( + &candidates, + |slot, generation| { + assert!(SHARED_VIEW_EPOCHS.try_lock().is_err(), "lease escaped the batch epoch"); + assert!(TRACKED_SRV_WRITES.try_lock().is_ok(), "WRITE was taken while leasing owners"); + lease_calls.push((slot, generation)); + (slot != d).then(|| { + let snapshot = snapshots[&slot]; + (snapshot, MutationOwner(Arc::clone(&drops)), MutationOwner(Arc::clone(&drops))) + }) + }, + |slots| { + observations += 1; + assert!(TRACKED_SRV_WRITES.try_lock().is_err(), "raw words were observed outside WRITE"); + assert!(TRACKED_SRVS.try_lock().is_ok(), "tracker lock crossed raw observation"); + assert_eq!(slots, &[(70, 0), (70, 1), (70, 2), (70, 4)]); + let mut changed_c = snapshots[&c].words; + changed_c[6] ^= 1; + vec![Some(snapshots[&a].words), Some(old_b.words), Some(changed_c), Some(snapshots[&e].words)] + }, + |valid| { + assert!(SHARED_VIEW_EPOCHS.try_lock().is_err(), "batch mutation escaped its epoch"); + assert!(TRACKED_SRV_WRITES.try_lock().is_err(), "batch mutation escaped WRITE"); + assert!(TRACKED_SRVS.try_lock().is_ok(), "tracker lock crossed batch mutation"); + assert_eq!(valid.iter().map(|entry| entry.entry.resource).collect::<Vec<_>>(), vec![0xA010, 0xE010]); + // Touch both strong-owner references: the batch exposes only validated owners. + assert!(valid.iter().all(|entry| Arc::ptr_eq(&entry.resource.0, &entry.heap.0))); + 29 + }, + ); + assert_eq!(result, Some(29)); + assert_eq!(lease_calls, vec![ + (a, snapshots[&a].generation), (b, old_b.generation), (c, snapshots[&c].generation), + (d, snapshots[&d].generation), (e, snapshots[&e].generation), + ]); + assert_eq!(observations, 1, "batch observed raw words more than once"); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 8, "strong owners did not drop after the batch"); + { + let tracked = TRACKED_SRVS.lock().unwrap(); + let tracked = tracked.as_ref().unwrap(); + assert_eq!(tracked.by_slot[&b].generation, newer_b.generation, "stale generation removed its replacement"); + assert!(!tracked.by_slot.contains_key(&c), "raw mismatch remained tracked"); + assert!(tracked.by_slot.contains_key(&d), "missing lease removed a still-current candidate"); + } + end_mutation_test(); + } + + #[test] + fn exact_srv_batch_empty_or_tracking_disabled_does_no_work() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + if !srv_tracking_enabled() { + let candidate = [(srv_slot(80, 0), 1)]; + assert_eq!(with_exact_tracked_srv_mutations_on( + &candidate, + |_, _| panic!("tracking-disabled batch leased an owner"), + |_| panic!("tracking-disabled batch observed words"), + |_: &[ExactSrvMutation<'_, (), ()>]| panic!("tracking-disabled batch mutated"), + ), None); + } + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + assert_eq!(with_exact_tracked_srv_mutations_on( + &[], + |_, _| panic!("empty batch leased an owner"), + |_| panic!("empty batch observed words"), + |_: &[ExactSrvMutation<'_, (), ()>]| panic!("empty batch mutated"), + ), None); + let slot = srv_slot(81, 0); + let (generation, _) = begin_mutation_test(tracked_entry(0x8110, 0xD0), slot); + let snapshot = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + assert_eq!(with_exact_tracked_srv_mutations_on( + &[(slot, generation)], + |_, _| Some((snapshot, (), ())), + |_| vec![None], + |_: &[ExactSrvMutation<'_, (), ()>]| panic!("all-stale batch mutated"), + ), None); + assert!(!TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot.contains_key(&slot)); + end_mutation_test(); + } + + #[test] + fn exact_srv_batch_unwind_drops_guards_before_strong_owners() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let slot = srv_slot(82, 0); + let (generation, words) = begin_mutation_test(tracked_entry(0x8210, 0xD4), slot); + let snapshot = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let unlocked = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + with_exact_tracked_srv_mutations_on( + &[(slot, generation)], + |_, _| Some(( + snapshot, + UnwindMutationOwner { drops: Arc::clone(&drops), unlocked: Arc::clone(&unlocked) }, + UnwindMutationOwner { drops: Arc::clone(&drops), unlocked: Arc::clone(&unlocked) }, + )), + |_| vec![Some(words)], + |_| -> () { panic!("test batch unwind") }, + ) + })); + assert!(outcome.is_err()); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 2); + assert_eq!(unlocked.load(std::sync::atomic::Ordering::Relaxed), 3, + "strong owners unwound before WRITE or tracker lock"); + TRACKED_SRV_WRITES.clear_poison(); + SHARED_VIEW_EPOCHS.clear_poison(); + end_mutation_test(); + } + #[test] fn tracked_srv_copy_requires_exact_source_words() { let mut tracked = TrackedSrvs::default(); From 96950cbb17693dfe53fe7bf4a9ad4a6cbc9570bf Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:46:22 -0800 Subject: [PATCH 219/265] D3D12.X: queue evicted pipeline rehydration Reserve absent recipe generations before placing reconstruction on the speculative worker band. Queue refusal, cancellation, and unwind restore a retryable state; release before or during driver work cannot resurrect a generation. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 290 +++++++++++++++++++++++++ 1 file changed, 290 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index e2bf20a903..d1d80fc229 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -503,6 +503,16 @@ enum RebuildRequest { Unavailable, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RehydrateRequest { + Queued, + Coalesced, + NotReady, + Abandoned, + Resident, + Unavailable, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum EvictResult { Evicted { generation: u64 }, @@ -1045,6 +1055,23 @@ impl Recipe { true } + /// Reserve a build only when no native generation is resident. Failed attempts are retryable; + /// a live current generation is never replaced by this path. + fn reserve_rehydrate(&self) -> Result<u64, RehydrateRequest> { + let mut state = self.0.rebuild.lock().unwrap(); + if state.active || state.waiters != 0 { + return Err(RehydrateRequest::Coalesced); + } + let mut generation = self.0.generation.lock().unwrap(); + if !matches!(generation.residency, Residency::Evicted | Residency::Failed) || generation.resident.is_some() { + return Err(RehydrateRequest::Resident); + } + let turn = state.completed; + state.active = true; + state.from = Some(generation.mark_rebuilding()); + Ok(turn) + } + fn finish_rebuild(&self, result: RebuildResult) { let mut state = self.0.rebuild.lock().unwrap(); self.0.generation.lock().unwrap().finish_rebuild(result, state.from.take()); @@ -1053,6 +1080,34 @@ impl Recipe { state.completed = state.completed.checked_add(1).expect("pipeline rebuild serial exhausted"); self.0.rebuild_done.notify_all(); } + + /// A queued reservation was refused or discarded before it ran. Restore its retryable state + /// and wake any synchronous follower which joined it. + fn cancel_reserved_rebuild(&self, turn: u64) { + let mut state = self.0.rebuild.lock().unwrap(); + if !state.active || state.completed != turn { + return; + } + self.0.generation.lock().unwrap().finish_rebuild(RebuildResult::NotReady, state.from.take()); + state.last = Some(RebuildResult::NotReady); + state.active = false; + state.completed = state.completed.checked_add(1).expect("pipeline rebuild serial exhausted"); + self.0.rebuild_done.notify_all(); + } +} + +/// Own one exact accepted rehydration turn until its queued closure completes. Queue refusal, +/// cancellation, shutdown, or an unwind drops the closure and restores a retryable residency; +/// its completed serial prevents an old guard from cancelling a newer turn. +struct RehydrateReservation { + recipe: Recipe, + turn: u64, +} + +impl Drop for RehydrateReservation { + fn drop(&mut self) { + self.recipe.cancel_reserved_rebuild(self.turn); + } } /// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. @@ -1214,6 +1269,14 @@ fn run_reserved_rebuild(build: Arc<Build>, recipe: Recipe) { let _ = rebuild_reserved(&build, &recipe); } +fn run_reserved_rehydrate(build: Arc<Build>, reservation: RehydrateReservation) { + let recipe = reservation.recipe.clone(); + run_reserved_rebuild(build, recipe); + // `rebuild_reserved` completed the turn. Drop is intentionally still armed so an unwind or a + // future early return cannot strand Rebuilding; it observes inactive after normal completion. + drop(reservation); +} + fn request_rebuild_on(build: Arc<Build>, q: &BuildQueue) -> RebuildRequest { let recipe = { let done = build.done.lock().unwrap(); @@ -1237,6 +1300,32 @@ fn request_rebuild_on(build: Arc<Build>, q: &BuildQueue) -> RebuildRequest { RebuildRequest::Queued } +fn request_rehydrate_on(build: Arc<Build>, q: &BuildQueue) -> RehydrateRequest { + let reservation = { + let done = build.done.lock().unwrap(); + if !*done { + return RehydrateRequest::NotReady; + } + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + return RehydrateRequest::Abandoned; + } + if build.real.load(Ordering::Acquire) != 0 { + return RehydrateRequest::Resident; + } + let Some(recipe) = build.recipe.clone() else { return RehydrateRequest::Unavailable }; + let turn = match recipe.reserve_rehydrate() { + Ok(turn) => turn, + Err(result) => return result, + }; + RehydrateReservation { recipe, turn } + }; + if q.submit(Priority::Speculative, Box::new(move || run_reserved_rehydrate(build, reservation))).is_none() { + // The refused work is dropped by `submit`, restoring Evicted/Failed before it returns. + return RehydrateRequest::Unavailable; + } + RehydrateRequest::Queued +} + /// Queue one low-priority replacement build. This is intentionally uncalled until an eviction /// policy has selected a pipeline; requesting never waits for driver work on the title thread. #[allow(dead_code)] @@ -1248,6 +1337,18 @@ fn request_rebuild(pso: usize) -> RebuildRequest { request_rebuild_on(pending.build.clone(), queue()) } +/// Queue low-priority reconstruction only for an absent recipe-backed generation. This is an +/// uncalled foundation: an eviction policy must decide when absence is acceptable before any bind +/// path may trigger it. +#[allow(dead_code)] +fn request_rehydrate(pso: usize) -> RehydrateRequest { + let Some(pending) = entry(pso) else { return RehydrateRequest::Unavailable }; + if !start_preload_workers() { + return RehydrateRequest::Unavailable; + } + request_rehydrate_on(pending.build.clone(), queue()) +} + fn submit_job(q: &BuildQueue, build: &Arc<Build>, priority: Priority, preload: bool, preload_rank: Option<usize>) -> Option<JobHandle> { let queued_build = build.clone(); q.submit_ranked(priority, preload_rank, Box::new(move || { @@ -2170,6 +2271,195 @@ mod used_tests { assert_eq!(first.refs.load(Ordering::Relaxed), 0); } + #[test] + fn async_rehydrate_coalesces_stays_unbuilt_until_worker_publication() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let standin = 0x7E57_C157usize; + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + build_next.load(Ordering::Acquire) + }); + submit_recipe_keyed(standin, true, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + let q = BuildQueue::new(); + assert_eq!(request_rehydrate_on(pending.build.clone(), &q), RehydrateRequest::Resident); + assert_eq!(try_evict_current(&pending.build), EvictResult::Evicted { generation: 1 }); + next.store(replacement_raw, Ordering::Release); + + assert_eq!(request_rehydrate_on(pending.build.clone(), &q), RehydrateRequest::Queued); + assert_eq!(request_rehydrate_on(pending.build.clone(), &q), RehydrateRequest::Coalesced); + assert_eq!(calls.load(Ordering::Relaxed), 1, "requester performed driver work"); + let ((chosen, unbuilt), pin) = resolve_wait_bound_and_pin(standin); + assert_eq!((chosen, unbuilt), (standin, true)); + assert!(pin.is_none()); + + assert!(q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(calls.load(Ordering::Relaxed), 2); + assert_eq!(pending.build.real.load(Ordering::Acquire), replacement_raw); + assert_eq!(pending.build.recipe.as_ref().unwrap().0.generation.lock().unwrap().residency, Residency::Resident); + let ((chosen, unbuilt), pin) = resolve_wait_bound_and_pin(standin); + assert_eq!((chosen, unbuilt), (replacement_raw, false)); + drop(pin); + + let final_raw = released(standin); + release(final_raw); + drop(pending); + assert_eq!((first.refs.load(Ordering::Relaxed), replacement.refs.load(Ordering::Relaxed)), (0, 0)); + } + + #[test] + fn refused_cancelled_and_failed_rehydrate_remain_retryable() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let recipe = Recipe::new(move || build_next.load(Ordering::Acquire)); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + + let refused = BuildQueue::new(); + refused.shutdown(); + assert_eq!(request_rehydrate_on(build.clone(), &refused), RehydrateRequest::Unavailable); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Evicted); + let cancelled = BuildQueue::new(); + assert_eq!(request_rehydrate_on(build.clone(), &cancelled), RehydrateRequest::Queued); + cancelled.shutdown(); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Evicted); + + next.store(0, Ordering::Release); + let failed = BuildQueue::new(); + assert_eq!(request_rehydrate_on(build.clone(), &failed), RehydrateRequest::Queued); + assert!(failed.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Failed); + next.store(replacement_raw, Ordering::Release); + let retry = BuildQueue::new(); + assert_eq!(request_rehydrate_on(build.clone(), &retry), RehydrateRequest::Queued); + assert!(retry.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(build.real.load(Ordering::Acquire), replacement_raw); + + let final_raw = build.real.swap(0, Ordering::AcqRel); + drop(build); + drop(recipe); + release(final_raw); + assert_eq!((first.refs.load(Ordering::Relaxed), replacement.refs.load(Ordering::Relaxed)), (0, 0)); + } + + #[test] + fn completed_rehydrate_guard_cannot_cancel_a_newer_turn() { + let recipe = Recipe::new(|| 0); + recipe.mark_failed(); + let first_turn = recipe.reserve_rehydrate().unwrap(); + let old = RehydrateReservation { recipe: recipe.clone(), turn: first_turn }; + recipe.finish_rebuild(RebuildResult::Failed); + + let second_turn = recipe.reserve_rehydrate().unwrap(); + let new = RehydrateReservation { recipe: recipe.clone(), turn: second_turn }; + assert_eq!((first_turn, second_turn), (0, 1)); + drop(old); + { + let state = recipe.0.rebuild.lock().unwrap(); + assert!(state.active, "old guard cancelled the newer reservation"); + assert_eq!(state.completed, second_turn); + } + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Rebuilding); + + drop(new); + let state = recipe.0.rebuild.lock().unwrap(); + assert!(!state.active); + assert_eq!(state.completed, second_turn + 1); + drop(state); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Failed); + } + + #[test] + fn rehydrate_released_before_worker_does_not_run_or_resurrect() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let standin = 0x7E57_C158usize; + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + first_raw + }); + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + assert_eq!(try_evict_current(&pending.build), EvictResult::Evicted { generation: 1 }); + let q = BuildQueue::new(); + assert_eq!(request_rehydrate_on(pending.build.clone(), &q), RehydrateRequest::Queued); + + assert_eq!(released(standin), 0); + assert!(q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(calls.load(Ordering::Relaxed), 1, "released rehydration ran its recipe"); + assert_eq!(pending.build.real.load(Ordering::Acquire), 0); + drop(pending); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn rehydrate_released_during_worker_abandons_new_raw() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let block = Arc::new((Mutex::new((false, false)), Condvar::new())); + let build_block = block.clone(); + let recipe = Recipe::new(move || { + if build_calls.fetch_add(1, Ordering::Relaxed) != 0 { + let mut state = build_block.0.lock().unwrap(); + state.0 = true; + build_block.1.notify_all(); + while !state.1 { state = build_block.1.wait(state).unwrap(); } + replacement_raw + } else { + first_raw + } + }); + let standin = 0x7E57_C159usize; + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + assert_eq!(try_evict_current(&pending.build), EvictResult::Evicted { generation: 1 }); + let q = Arc::new(BuildQueue::new()); + assert_eq!(request_rehydrate_on(pending.build.clone(), &q), RehydrateRequest::Queued); + let worker_q = q.clone(); + let worker = std::thread::spawn(move || worker_q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + { + let mut state = block.0.lock().unwrap(); + while !state.0 { state = block.1.wait(state).unwrap(); } + } + assert_eq!(released(standin), 0); + block.0.lock().unwrap().1 = true; + block.1.notify_all(); + assert!(worker.join().unwrap()); + assert_eq!(pending.build.real.load(Ordering::Acquire), 0); + assert_eq!(replacement.refs.load(Ordering::Relaxed), 0); + drop(pending); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + #[test] fn capture_preserves_lazy_for_bind_wait_and_identity_choices() { let standin = 0x7E57_C130usize; From c8889e88ef64bc3056453e9bb7eb4d029a4249e0 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:55:11 -0800 Subject: [PATCH 220/265] D3D12.X: model exact sparse upload work claims Represent zero, retry, and dirty page work as generation-tagged claims with monotonic identities. Later observations remain journalled behind the exact owner, and cancellation or unwind restores only that claim without rewinding newer work. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 342 ++++++++++++++++++++++++++++ 1 file changed, 342 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 9fd6d6e775..bf96ccbbd9 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -235,6 +235,255 @@ struct WaitTicket { kind: WaitKind, } +/// Sources which can require one CPU page to be considered by a future immutable upload plan. +/// Multiple sources collapse into one page owner without losing why the page must be revisited. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +struct WorkReasons(u8); + +impl WorkReasons { + const ZERO: Self = Self(1); + const RETRY: Self = Self(2); + const DIRTY: Self = Self(4); + + fn insert(&mut self, other: Self) { self.0 |= other.0; } +} + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +struct WorkClaimToken { + state_generation: u64, + serial: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum WorkClaimResolution { + Committed, + Restored, + AlreadyFinished, + StaleGeneration, +} + +struct ClaimedWork { + token: WorkClaimToken, + pages: Vec<(usize, WorkReasons)>, +} + +/// Inert foundation for splitting sparse planning from its serialized commit phase. Work added +/// while a page is owned stays journalled for a later claim; cancelling an older claim merges its +/// exact reasons back without rewinding or duplicating a newer claim. Tokens include the sparse +/// state generation, so a late completion from replaced state cannot modify the replacement. +#[allow(dead_code)] +struct WorkClaimLedger { + state_generation: u64, + next_serial: u64, + available: BTreeMap<usize, WorkReasons>, + owners: BTreeMap<usize, u64>, + claims: BTreeMap<u64, Vec<(usize, WorkReasons)>>, +} + +#[allow(dead_code)] +impl WorkClaimLedger { + fn new(state_generation: u64) -> Self { + Self { + state_generation, + next_serial: 0, + available: BTreeMap::new(), + owners: BTreeMap::new(), + claims: BTreeMap::new(), + } + } + + fn add_pages(&mut self, pages: impl IntoIterator<Item = usize>, reason: WorkReasons) { + for page in pages { + self.available.entry(page & !(PAGE - 1)).or_default().insert(reason); + } + } + + fn add_zero_ranges(&mut self, ranges: &[(usize, usize)]) { + for &(start, bytes) in ranges { + if bytes == 0 { + continue; + } + let end = start.saturating_add(bytes); + let mut page = start & !(PAGE - 1); + while page < end { + self.available.entry(page).or_default().insert(WorkReasons::ZERO); + let Some(next) = page.checked_add(PAGE) else { break }; + page = next; + } + } + } + + fn add_retry_pages(&mut self, pages: impl IntoIterator<Item = usize>) { + self.add_pages(pages, WorkReasons::RETRY); + } + + fn add_dirty_pages(&mut self, pages: impl IntoIterator<Item = usize>) { + self.add_pages(pages, WorkReasons::DIRTY); + } + + /// Claim at most `limit` pages in address order. A page has one owner even when zero, retry, + /// and fresh dirty work overlap; reasons added after this snapshot remain for the next claim. + fn claim(&mut self, limit: usize) -> Option<ClaimedWork> { + if limit == 0 { + return None; + } + let pages: Vec<_> = self.available + .iter() + .filter(|(page, _)| !self.owners.contains_key(page)) + .take(limit) + .map(|(&page, &reasons)| (page, reasons)) + .collect(); + if pages.is_empty() { + return None; + } + self.next_serial = self.next_serial.checked_add(1).expect("sparse work claim serial exhausted"); + let serial = self.next_serial; + for &(page, _) in &pages { + self.available.remove(&page); + self.owners.insert(page, serial); + } + self.claims.insert(serial, pages.clone()); + Some(ClaimedWork { + token: WorkClaimToken { state_generation: self.state_generation, serial }, + pages, + }) + } + + fn commit(&mut self, token: WorkClaimToken) -> WorkClaimResolution { + self.finish(token, false) + } + + fn restore(&mut self, token: WorkClaimToken) -> WorkClaimResolution { + self.finish(token, true) + } + + fn cancel(&mut self, token: WorkClaimToken) -> WorkClaimResolution { + self.restore(token) + } + + fn finish(&mut self, token: WorkClaimToken, restore: bool) -> WorkClaimResolution { + if token.state_generation != self.state_generation { + return WorkClaimResolution::StaleGeneration; + } + let Some(pages) = self.claims.remove(&token.serial) else { + return WorkClaimResolution::AlreadyFinished; + }; + for (page, reasons) in pages { + if self.owners.get(&page) != Some(&token.serial) { + continue; + } + self.owners.remove(&page); + if restore { + self.available.entry(page).or_default().insert(reasons); + } + } + if restore { WorkClaimResolution::Restored } else { WorkClaimResolution::Committed } + } + + fn replace_generation(&mut self, state_generation: u64) { + self.state_generation = state_generation; + self.available.clear(); + self.owners.clear(); + self.claims.clear(); + } +} + +/// Shared owner used by future planners. A dropped guard restores only its exact still-current +/// claim, so unwind is safe and an old guard cannot cancel work reserved after it finished. +#[derive(Clone)] +#[allow(dead_code)] +struct SparseWorkClaims { + ledger: Arc<Mutex<WorkClaimLedger>>, + state_generation: u64, +} + +#[allow(dead_code)] +impl SparseWorkClaims { + fn new(state_generation: u64) -> Self { + Self { ledger: Arc::new(Mutex::new(WorkClaimLedger::new(state_generation))), state_generation } + } + + fn add_zero_ranges(&self, ranges: &[(usize, usize)]) -> bool { + let mut ledger = self.ledger.lock().unwrap(); + if ledger.state_generation != self.state_generation { + return false; + } + ledger.add_zero_ranges(ranges); + true + } + + fn add_retry_pages(&self, pages: impl IntoIterator<Item = usize>) -> bool { + let mut ledger = self.ledger.lock().unwrap(); + if ledger.state_generation != self.state_generation { + return false; + } + ledger.add_retry_pages(pages); + true + } + + fn add_dirty_pages(&self, pages: impl IntoIterator<Item = usize>) -> bool { + let mut ledger = self.ledger.lock().unwrap(); + if ledger.state_generation != self.state_generation { + return false; + } + ledger.add_dirty_pages(pages); + true + } + + fn claim(&self, limit: usize) -> Option<SparseWorkClaim> { + let claimed = { + let mut ledger = self.ledger.lock().unwrap(); + if ledger.state_generation != self.state_generation { + return None; + } + ledger.claim(limit)? + }; + Some(SparseWorkClaim { ledger: self.ledger.clone(), claimed: Some(claimed) }) + } + + /// Replace only the exact generation this handle names. The returned handle names the new + /// generation; this handle and every clone of it become permanently stale. + fn replace_generation(&self, state_generation: u64) -> Option<Self> { + let mut ledger = self.ledger.lock().unwrap(); + if ledger.state_generation != self.state_generation || state_generation == self.state_generation { + return None; + } + ledger.replace_generation(state_generation); + Some(Self { ledger: self.ledger.clone(), state_generation }) + } +} + +#[allow(dead_code)] +struct SparseWorkClaim { + ledger: Arc<Mutex<WorkClaimLedger>>, + claimed: Option<ClaimedWork>, +} + +#[allow(dead_code)] +impl SparseWorkClaim { + fn pages(&self) -> &[(usize, WorkReasons)] { + self.claimed.as_ref().map_or(&[], |claim| claim.pages.as_slice()) + } + + fn commit(mut self) -> WorkClaimResolution { + let claim = self.claimed.take().expect("finished sparse work claim"); + self.ledger.lock().unwrap().commit(claim.token) + } + + fn cancel(mut self) -> WorkClaimResolution { + let claim = self.claimed.take().expect("finished sparse work claim"); + self.ledger.lock().unwrap().cancel(claim.token) + } +} + +impl Drop for SparseWorkClaim { + fn drop(&mut self) { + if let Some(claim) = self.claimed.take() { + let _ = self.ledger.lock().unwrap().restore(claim.token); + } + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) enum PreparationOutcome { Ready, @@ -2989,6 +3238,99 @@ mod tests { assert_eq!(retry_journal(PreparationOutcome::ExecutedUntracked, vec![0x3000], &runs), [0x1000, 0x2000, 0x3000]); } + #[test] + fn sparse_work_claims_merge_sources_and_reserve_pages_in_order() { + let claims = SparseWorkClaims::new(7); + claims.add_zero_ranges(&[(0x3000, 2 * PAGE)]); + claims.add_retry_pages([0x3001, 0x1000, 0x1000]); + claims.add_dirty_pages([0x4000, 0x6001, 0x6000]); + + let first = claims.claim(2).unwrap(); + assert_eq!(first.pages().iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ + (0x1000, WorkReasons::RETRY.0), + (0x3000, WorkReasons::ZERO.0 | WorkReasons::RETRY.0), + ]); + let second = claims.claim(8).unwrap(); + assert_eq!(second.pages().iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ + (0x4000, WorkReasons::ZERO.0 | WorkReasons::DIRTY.0), + (0x6000, WorkReasons::DIRTY.0), + ]); + assert!(second.claimed.as_ref().unwrap().token.serial > first.claimed.as_ref().unwrap().token.serial); + + // Work observed after the first snapshot stays journalled, but cannot be claimed until + // the exact older owner finishes. + claims.add_dirty_pages([0x1000]); + assert!(claims.claim(1).is_none()); + assert_eq!(second.cancel(), WorkClaimResolution::Restored); + let out_of_order = claims.claim(1).unwrap(); + assert_eq!(out_of_order.pages()[0].0, 0x4000, "a newer cancellation disturbed the older owner"); + assert_eq!(first.commit(), WorkClaimResolution::Committed); + let later = claims.claim(1).unwrap(); + assert_eq!(later.pages().iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ + (0x1000, WorkReasons::DIRTY.0), + ]); + assert_eq!(later.commit(), WorkClaimResolution::Committed); + assert_eq!(out_of_order.cancel(), WorkClaimResolution::Restored); + let restored = claims.claim(8).unwrap(); + assert_eq!(restored.pages().iter().map(|(page, _)| *page).collect::<Vec<_>>(), [0x4000, 0x6000]); + } + + #[test] + fn late_claim_completion_cannot_change_a_newer_owner() { + let mut ledger = WorkClaimLedger::new(11); + ledger.add_dirty_pages([0x8000]); + let old = ledger.claim(1).unwrap(); + assert_eq!(ledger.commit(old.token), WorkClaimResolution::Committed); + + ledger.add_retry_pages([0x8000]); + let newer = ledger.claim(1).unwrap(); + assert_eq!(ledger.restore(old.token), WorkClaimResolution::AlreadyFinished); + assert_eq!(ledger.owners.get(&0x8000), Some(&newer.token.serial)); + assert_eq!(ledger.commit(newer.token), WorkClaimResolution::Committed); + assert!(ledger.available.is_empty()); + } + + #[test] + fn dropped_sparse_work_claim_restores_after_unwind() { + let claims = SparseWorkClaims::new(13); + claims.add_dirty_pages([0xA000, 0x9000]); + let result = std::panic::catch_unwind({ + let claims = claims.clone(); + move || { + let claim = claims.claim(1).unwrap(); + assert_eq!(claim.pages()[0].0, 0x9000); + panic!("planned upload failed"); + } + }); + assert!(result.is_err()); + let restored = claims.claim(2).unwrap(); + assert_eq!(restored.pages().iter().map(|(page, _)| *page).collect::<Vec<_>>(), [0x9000, 0xA000]); + } + + #[test] + fn replaced_sparse_generation_rejects_old_claims_and_producer_clones() { + let claims = SparseWorkClaims::new(17); + let stale_clone = claims.clone(); + assert!(claims.add_zero_ranges(&[(0xB000, PAGE)])); + let old = claims.claim(1).unwrap(); + let old_token = old.claimed.as_ref().unwrap().token; + let current = claims.replace_generation(18).unwrap(); + assert!(!claims.add_dirty_pages([0xC000]), "replaced handle added current work"); + assert!(!stale_clone.add_retry_pages([0xD000]), "stale clone added current work"); + assert!(claims.claim(1).is_none(), "replaced handle claimed current work"); + assert!(stale_clone.replace_generation(19).is_none(), "stale clone replaced current generation"); + assert!(current.add_dirty_pages([0xB000])); + assert_eq!(current.ledger.lock().unwrap().restore(old_token), WorkClaimResolution::StaleGeneration); + drop(old); + + let claim = current.claim(1).unwrap(); + assert_eq!(claim.pages().iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ + (0xB000, WorkReasons::DIRTY.0), + ]); + assert_eq!(claim.commit(), WorkClaimResolution::Committed); + assert!(current.claim(1).is_none(), "stale producers polluted the current journal"); + } + #[test] fn a_failed_title_queue_wait_rolls_back_only_its_reservation() { let mut waited = FxHashMap::from_iter([(1, 4), (2, 7)]); From 96f2be444b2339b6fe8047ac7a01010da98a4eed Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:59:09 -0800 Subject: [PATCH 221/265] Scripts: compare sparse upload gate timing Parse the interval metrics already preserved in performance logs, sum them per cold or warm run, and expose raw baseline/candidate/delta values. Older logs keep explicit missing states instead of inventing zero counters. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 4 ++- scripts/perf-compare.ps1 | 50 ++++++++++++++++++++++++++++++++++ scripts/perf-compare.tests.ps1 | 29 ++++++++++++++++++++ 3 files changed, 82 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 713ce71de6..ab1d4493ed 100644 --- a/README.md +++ b/README.md @@ -394,7 +394,9 @@ Compare two completed artifact folders without modifying them: The console shows raw cold/warm duration, exit/timeout state, stall totals/counts/maxima, the five compute-build coalescing counters, and ranked-preload submissions, starts and promotions. The allocator section also reports execute/chunk topology, retirement-signal outcomes, mark writes and -allocator-state lock timing. The redirected JSON keeps those values, raw deltas, and stall log2 +allocator-state lock timing. Sparse upload-gate submit/readback wait and hold times are summed from +the activity log; artifacts from older builds label those counters missing rather than zero. The +redirected JSON keeps those values, raw deltas, and stall log2 histograms. Missing reports or preparation summaries and unsupported preparation versions remain explicit states; they are not treated as zero. The tool refuses different workload fingerprints or identity algorithm/versions, run order, requested diff --git a/scripts/perf-compare.ps1 b/scripts/perf-compare.ps1 index 99923a22f8..11e00ee2c6 100644 --- a/scripts/perf-compare.ps1 +++ b/scripts/perf-compare.ps1 @@ -151,6 +151,40 @@ function Read-Preparation([string]$Root, [int]$Order, [string]$Label) { return [ordered]@{ status = 'present'; counters = $counters; ranked_status = 'present'; ranked = $ranked; allocator_status = 'present'; allocator = $allocator } } +function Read-SparseUploadGate([string]$Root, [int]$Order, [string]$Label) { + $mode = $Label.Substring(4) + $log = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'xcl.log')) + if (-not (Test-Path -LiteralPath $log -PathType Leaf)) { + return [ordered]@{ status = 'missing_log'; counters = $null } + } + $text = Get-Content -LiteralPath $log -Raw -Encoding utf8 + $marker = 'upload gate submit wait/hold' + $pattern = 'upload gate submit wait/hold (?<submit_wait>\d+)/(?<submit_hold>\d+) ms, readback wait/hold/released wait\+reacquire (?<readback_wait>\d+)/(?<readback_hold>\d+)/(?<readback_released>\d+) ms' + $matches = [regex]::Matches($text, $pattern) + $markers = [regex]::Matches($text, [regex]::Escape($marker)) + if ($matches.Count -ne $markers.Count) { + throw "malformed sparse upload-gate metrics in $log" + } + if ($matches.Count -eq 0) { + return [ordered]@{ status = 'missing_metrics'; counters = $null } + } + $counters = [ordered]@{ + submit_wait_ms = [decimal]0 + submit_hold_ms = [decimal]0 + readback_wait_ms = [decimal]0 + readback_hold_ms = [decimal]0 + readback_released_wait_reacquire_ms = [decimal]0 + } + foreach ($match in $matches) { + $counters.submit_wait_ms += [decimal]$match.Groups['submit_wait'].Value + $counters.submit_hold_ms += [decimal]$match.Groups['submit_hold'].Value + $counters.readback_wait_ms += [decimal]$match.Groups['readback_wait'].Value + $counters.readback_hold_ms += [decimal]$match.Groups['readback_hold'].Value + $counters.readback_released_wait_reacquire_ms += [decimal]$match.Groups['readback_released'].Value + } + return [ordered]@{ status = 'present'; counters = $counters } +} + function Number-Or-Null($Object, [string]$Name) { if ($null -eq $Object -or -not (Has-Property $Object $Name) -or $null -eq $Object.$Name) { return $null } return [long]$Object.$Name @@ -264,6 +298,11 @@ for ($i = 0; $i -lt 2; $i++) { 'lists_marked', 'backing_mark_writes', 'signal_attempts', 'signal_failures', 'state_lock_wait_ns', 'state_lock_hold_ns') $allocatorSubmits = Compare-Counters $beforePreparation.allocator $afterPreparation.allocator $allocatorNames + $beforeSparseGate = Read-SparseUploadGate $baselineRoot ($i + 1) $beforeRun.cache_state + $afterSparseGate = Read-SparseUploadGate $candidateRoot ($i + 1) $afterRun.cache_state + $sparseGateNames = @('submit_wait_ms', 'submit_hold_ms', 'readback_wait_ms', 'readback_hold_ms', + 'readback_released_wait_reacquire_ms') + $sparseUploadGate = Compare-Counters $beforeSparseGate.counters $afterSparseGate.counters $sparseGateNames $comparison = [ordered]@{ label = $beforeRun.cache_state @@ -297,6 +336,11 @@ for ($i = 0; $i -lt 2; $i++) { candidate = $afterPreparation.allocator_status } allocator_submits = $allocatorSubmits + sparse_upload_gate_status = [ordered]@{ + baseline = $beforeSparseGate.status + candidate = $afterSparseGate.status + } + sparse_upload_gate = $sparseUploadGate } $comparisons += $comparison @@ -327,6 +371,12 @@ for ($i = 0; $i -lt 2; $i++) { Write-Host " $($name): $(Display-Value $allocatorSubmits.baseline.$name '') -> $(Display-Value $allocatorSubmits.candidate.$name ''); delta $(Display-Value $allocatorSubmits.delta.$name '')" } } + Write-Host " sparse upload gate: $($beforeSparseGate.status) -> $($afterSparseGate.status)" + if ($beforeSparseGate.status -eq 'present' -or $afterSparseGate.status -eq 'present') { + foreach ($name in $sparseUploadGate.delta.Keys) { + Write-Host " $($name): $(Display-Value $sparseUploadGate.baseline.$name ' ms') -> $(Display-Value $sparseUploadGate.candidate.$name ' ms'); delta $(Display-Value $sparseUploadGate.delta.$name ' ms')" + } + } } [ordered]@{ diff --git a/scripts/perf-compare.tests.ps1 b/scripts/perf-compare.tests.ps1 index aa6d0093dd..2b307e9087 100644 --- a/scripts/perf-compare.tests.ps1 +++ b/scripts/perf-compare.tests.ps1 @@ -63,6 +63,14 @@ try { Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation 3 $beforeRanked $beforeAllocator Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator -ExtraKind [ordered]@{ d3d12 = [ordered]@{} } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $baseline 'runs\02-warm\report.json') -Encoding utf8 + @( + '[00:00:02] upload gate submit wait/hold 1/2 ms, readback wait/hold/released wait+reacquire 3/4/5 ms; other active work 6 ms' + '[00:00:04] upload gate submit wait/hold 10/20 ms, readback wait/hold/released wait+reacquire 30/40/50 ms; other active work 60 ms' + ) | Set-Content -LiteralPath (Join-Path $baseline 'runs\01-cold\xcl.log') -Encoding utf8 + '[00:00:02] upload gate submit wait/hold 7/9 ms, readback wait/hold/released wait+reacquire 11/13/15 ms; other active work 17 ms' | + Set-Content -LiteralPath (Join-Path $candidate 'runs\01-cold\xcl.log') -Encoding utf8 + '[00:00:02] sparse queue wait/fence+state/scan/upload/ownership wait 1/2/3/4/5 ms' | + Set-Content -LiteralPath (Join-Path $baseline 'runs\02-warm\xcl.log') -Encoding utf8 $json = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json if ($json.schema -ne 'xcl-perf-comparison' -or $json.version -ne 1) { throw 'wrong output schema' } @@ -113,6 +121,27 @@ try { $null -ne $json.runs[1].allocator_submits.delta.chunks) { throw 'missing preparation data was treated as zero' } + $gate = $json.runs[0].sparse_upload_gate + if ($json.runs[0].sparse_upload_gate_status.baseline -ne 'present' -or + $json.runs[0].sparse_upload_gate_status.candidate -ne 'present' -or + $gate.baseline.submit_wait_ms -ne 11 -or $gate.baseline.submit_hold_ms -ne 22 -or + $gate.baseline.readback_wait_ms -ne 33 -or $gate.baseline.readback_hold_ms -ne 44 -or + $gate.baseline.readback_released_wait_reacquire_ms -ne 55 -or + $gate.candidate.submit_wait_ms -ne 7 -or $gate.delta.submit_wait_ms -ne -4 -or + $gate.delta.readback_released_wait_reacquire_ms -ne -40) { + throw 'sparse upload-gate counters or deltas are wrong' + } + if ($json.runs[1].sparse_upload_gate_status.baseline -ne 'missing_metrics' -or + $json.runs[1].sparse_upload_gate_status.candidate -ne 'missing_log' -or + $null -ne $json.runs[1].sparse_upload_gate.delta.submit_wait_ms) { + throw 'missing sparse upload-gate metrics were treated as zero' + } + $badGateLog = Join-Path $candidate 'runs\02-warm\xcl.log' + 'upload gate submit wait/hold malformed' | Set-Content -LiteralPath $badGateLog -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed sparse upload-gate metrics' } + Remove-Item -LiteralPath $badGateLog + if (-not $refused) { throw 'a malformed sparse upload-gate activity line was not refused' } if (($json | ConvertTo-Json -Depth 12) -match '"(percent|percentage|ratio|significance|significant)"\s*:') { throw 'output invented a derived significance metric' } From fd5d142fd6047e59cc1e42657c97c45e293be191 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:02:39 -0800 Subject: [PATCH 222/265] D3D12.X: journal bounded pipeline eviction candidates Record recipe-enabled pipeline use in a bounded lock-free weak-identity ring so a future pressure policy can inspect a fixed amount of work without scanning the title registry or retaining released PSOs. Background draining filters exact resident, owned, inactive builds and leaves eviction transitions uncalled. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 333 +++++++++++++++++++++++++ 1 file changed, 333 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index d1d80fc229..8bb619aba9 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -64,6 +64,9 @@ struct Build { last_use_frame: AtomicU64, /// Frame in which `real` became retained; age never begins before the build completed. completed_frame: AtomicU64, + /// This build already has one use record in the bounded eviction-candidate journal. + /// Touched only while recipe retention is enabled. + candidate_queued: AtomicBool, done: Mutex<bool>, cv: Condvar, /// every stand-in interested in this build was released before it finished @@ -77,6 +80,107 @@ struct Build { queued: Mutex<Option<JobHandle>>, } +const EVICTION_CANDIDATE_CAPACITY: usize = 1024; + +/// Bounded lock-free MPMC ring. Bind threads append weak identities, so an unconsumed record does +/// not retain a released pipeline; a future policy can drain a fixed number on a background thread +/// without scanning the title-visible registry. +struct CandidateSlot<T> { + sequence: AtomicUsize, + value: std::cell::UnsafeCell<std::mem::MaybeUninit<Weak<T>>>, +} + +unsafe impl<T: Send + Sync> Sync for CandidateSlot<T> {} + +struct CandidateQueue<T, const N: usize> { + enqueue: AtomicUsize, + dequeue: AtomicUsize, + slots: [CandidateSlot<T>; N], +} + +unsafe impl<T: Send + Sync, const N: usize> Sync for CandidateQueue<T, N> {} + +impl<T, const N: usize> CandidateQueue<T, N> { + fn new() -> Self { + // The sequence protocol needs distinct empty/full generations for each slot. At capacity + // one the producer can observe its just-published sequence as the next empty generation + // and overwrite an unread value. Signed sequence differences also require a half-range + // bound across counter wrap. + assert!(N > 1 && N.is_power_of_two() && N <= isize::MAX as usize); + Self { + enqueue: AtomicUsize::new(0), + dequeue: AtomicUsize::new(0), + slots: std::array::from_fn(|sequence| CandidateSlot { + sequence: AtomicUsize::new(sequence), + value: std::cell::UnsafeCell::new(std::mem::MaybeUninit::uninit()), + }), + } + } + + fn push(&self, value: Weak<T>) -> Result<(), Weak<T>> { + let mut position = self.enqueue.load(Ordering::Relaxed); + loop { + let slot = &self.slots[position & (N - 1)]; + let sequence = slot.sequence.load(Ordering::Acquire); + let difference = sequence.wrapping_sub(position) as isize; + if difference == 0 { + match self.enqueue.compare_exchange_weak( + position, position.wrapping_add(1), Ordering::Relaxed, Ordering::Relaxed, + ) { + Ok(_) => { + unsafe { (*slot.value.get()).write(value) }; + slot.sequence.store(position.wrapping_add(1), Ordering::Release); + return Ok(()); + } + Err(actual) => position = actual, + } + } else if difference < 0 { + return Err(value); + } else { + position = self.enqueue.load(Ordering::Relaxed); + } + } + } + + fn pop(&self) -> Option<Weak<T>> { + let mut position = self.dequeue.load(Ordering::Relaxed); + loop { + let slot = &self.slots[position & (N - 1)]; + let sequence = slot.sequence.load(Ordering::Acquire); + let difference = sequence.wrapping_sub(position.wrapping_add(1)) as isize; + if difference == 0 { + match self.dequeue.compare_exchange_weak( + position, position.wrapping_add(1), Ordering::Relaxed, Ordering::Relaxed, + ) { + Ok(_) => { + let value = unsafe { (*slot.value.get()).assume_init_read() }; + slot.sequence.store(position.wrapping_add(N), Ordering::Release); + return Some(value); + } + Err(actual) => position = actual, + } + } else if difference < 0 { + return None; + } else { + position = self.dequeue.load(Ordering::Relaxed); + } + } + } +} + +impl<T, const N: usize> Drop for CandidateQueue<T, N> { + fn drop(&mut self) { + while self.pop().is_some() {} + } +} + +type EvictionCandidateQueue = CandidateQueue<Build, EVICTION_CANDIDATE_CAPACITY>; + +fn eviction_candidates() -> &'static EvictionCandidateQueue { + static CANDIDATES: OnceLock<EvictionCandidateQueue> = OnceLock::new(); + CANDIDATES.get_or_init(EvictionCandidateQueue::new) +} + /// Submit demand and the preload worker building this pipeline. #[derive(Default)] struct Demand { @@ -203,6 +307,7 @@ impl Build { real: AtomicUsize::new(0), last_use_frame: AtomicU64::new(super::present::presents()), completed_frame: AtomicU64::new(0), + candidate_queued: AtomicBool::new(false), done: Mutex::new(false), cv: Condvar::new(), orphan: Default::default(), @@ -440,6 +545,93 @@ pub fn retention_stats() -> RetentionStats { retention_stats_from(super::present::presents(), builds) } +/// One point-in-time, pressure-ready resident selected off the bind thread. A future policy must +/// still recheck age and call `try_evict_current`, which serializes every ownership transition. +#[allow(dead_code)] +struct EvictionCandidate { + build: Arc<Build>, + last_use_frame: u64, + completed_frame: u64, +} + +impl Drop for EvictionCandidate { + fn drop(&mut self) { + self.build.candidate_queued.store(false, Ordering::Release); + } +} + +/// Recipe-enabled binds append at most one weak identity per build. This path is reached only after +/// the existing `XCL_PSO_REBUILD_RECIPES` gate selected generation-aware resolution; ordinary +/// binds pay no candidate check, queue operation, registry scan, or allocation. +fn note_eviction_candidate_on<const N: usize>(build: &Arc<Build>, frame: u64, candidates: &CandidateQueue<Build, N>) { + build.last_use_frame.fetch_max(frame, Ordering::Relaxed); + if build.candidate_queued.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + return; + } + if candidates.push(Arc::downgrade(build)).is_err() { + build.candidate_queued.store(false, Ordering::Release); + } +} + +fn note_eviction_candidate(build: &Arc<Build>) { + note_eviction_candidate_on(build, super::present::presents(), eviction_candidates()); +} + +fn resident_candidate(build: &Arc<Build>) -> Option<EvictionCandidate> { + let done = build.done.lock().unwrap(); + if !*done || build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + return None; + } + let recipe = build.recipe.as_ref()?; + let rebuild = recipe.0.rebuild.lock().unwrap(); + if rebuild.active || rebuild.waiters != 0 { + return None; + } + let real = build.real.load(Ordering::Acquire); + if real == 0 { + return None; + } + let generation = recipe.0.generation.lock().unwrap(); + if generation.residency != Residency::Resident + || generation.resident.as_ref().is_none_or(|resident| resident.raw != real) + { + return None; + } + let last_use_frame = build.last_use_frame.load(Ordering::Relaxed); + let completed_frame = build.completed_frame.load(Ordering::Relaxed); + drop(generation); + drop(rebuild); + drop(done); + Some(EvictionCandidate { build: build.clone(), last_use_frame, completed_frame }) +} + +/// Drain at most `limit` journal records on a background policy turn. The weak allocation identity +/// prevents a released stand-in address from turning an old record into a new pipeline. +#[allow(dead_code)] +fn drain_eviction_candidates_on<const N: usize>( + candidates: &CandidateQueue<Build, N>, limit: usize, +) -> Vec<EvictionCandidate> { + let mut selected = Vec::new(); + for _ in 0..limit { + let Some(build) = candidates.pop() else { break }; + let Some(build) = build.upgrade() else { continue }; + match resident_candidate(&build) { + Some(candidate) => selected.push(candidate), + None => { + // A released/orphaned/active/nonresident build is not actionable. Allow a later + // use after its state changes to journal it again. + build.candidate_queued.store(false, Ordering::Release); + } + } + } + selected +} + +#[allow(dead_code)] +fn drain_eviction_candidates(limit: usize) -> Vec<EvictionCandidate> { + drain_eviction_candidates_on(eviction_candidates(), limit) +} + fn forget_in_flight(build: &Arc<Build>) { let Some(key) = &build.compute_key else { return }; let mut registry = IN_FLIGHT.lock().unwrap(); @@ -1731,6 +1923,146 @@ mod used_tests { } } + #[test] + fn eviction_candidate_ring_is_bounded_reusable_and_does_not_retain_builds() { + assert!(std::panic::catch_unwind(CandidateQueue::<usize, 0>::new).is_err()); + assert!(std::panic::catch_unwind(CandidateQueue::<usize, 1>::new).is_err()); + let queue = CandidateQueue::<usize, 2>::new(); + let first = Arc::new(1usize); + let second = Arc::new(2usize); + let third = Arc::new(3usize); + assert!(queue.push(Arc::downgrade(&first)).is_ok()); + assert!(queue.push(Arc::downgrade(&second)).is_ok()); + assert!(queue.push(Arc::downgrade(&third)).is_err(), "a full candidate ring accepted an unbounded record"); + assert_eq!(*queue.pop().unwrap().upgrade().unwrap(), 1); + assert!(queue.push(Arc::downgrade(&third)).is_ok(), "a drained ring slot was not reusable"); + assert_eq!(*queue.pop().unwrap().upgrade().unwrap(), 2); + assert_eq!(*queue.pop().unwrap().upgrade().unwrap(), 3); + assert!(queue.pop().is_none()); + + let builds = CandidateQueue::<Build, 2>::new(); + let build = Arc::new(Build::new(Box::new(|| 0), false)); + let weak = Arc::downgrade(&build); + note_eviction_candidate_on(&build, 7, &builds); + drop(build); + assert!(weak.upgrade().is_none(), "an unconsumed candidate retained a released build"); + assert!(builds.pop().unwrap().upgrade().is_none(), "a released build record changed identity"); + } + + #[test] + fn eviction_candidate_ring_mpmc_delivers_every_weak_once() { + const COUNT: usize = 512; + let queue = CandidateQueue::<usize, 64>::new(); + let values: Vec<_> = (0..COUNT).map(Arc::new).collect(); + let seen: Vec<_> = (0..COUNT).map(|_| AtomicUsize::new(0)).collect(); + let consumed = AtomicUsize::new(0); + std::thread::scope(|scope| { + for producer in 0..4 { + let queue = &queue; + let values = &values; + scope.spawn(move || { + for index in (producer..COUNT).step_by(4) { + let mut value = Arc::downgrade(&values[index]); + loop { + match queue.push(value) { + Ok(()) => break, + Err(returned) => { + value = returned; + std::thread::yield_now(); + } + } + } + } + }); + } + for _ in 0..4 { + let queue = &queue; + let seen = &seen; + let consumed = &consumed; + scope.spawn(move || loop { + if consumed.load(Ordering::Acquire) == COUNT { + break; + } + let Some(value) = queue.pop() else { + std::thread::yield_now(); + continue; + }; + let index = *value.upgrade().expect("payload died while retained by the test"); + seen[index].fetch_add(1, Ordering::Relaxed); + consumed.fetch_add(1, Ordering::Release); + }); + } + }); + assert_eq!(consumed.load(Ordering::Relaxed), COUNT); + assert!(seen.iter().all(|count| count.load(Ordering::Relaxed) == 1), "a payload was lost or delivered twice"); + assert!(values.iter().all(|value| Arc::weak_count(value) == 0), "a queued Weak payload was not dropped exactly once"); + assert!(queue.pop().is_none()); + } + + #[test] + fn eviction_candidates_deduplicate_bound_drain_and_filter_ineligible_builds() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut second = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let second_raw = &mut second as *mut RebuildFakePso as usize; + let first_recipe = Recipe::new(move || first_raw); + let second_recipe = Recipe::new(move || second_raw); + let first_build = Arc::new(Build::new_keyed( + first_recipe.initial_job(), false, None, Some(first_recipe.clone()), + )); + let second_build = Arc::new(Build::new_keyed( + second_recipe.initial_job(), false, None, Some(second_recipe.clone()), + )); + let first_job = first_build.job.lock().unwrap().take().unwrap(); + let second_job = second_build.job.lock().unwrap().take().unwrap(); + complete(&first_build, first_job()); + complete(&second_build, second_job()); + let queue = CandidateQueue::<Build, 4>::new(); + + // Ordinary/default resolution bookkeeping does not touch the opt-in candidate journal. + let pending = Pending { + build: first_build.clone(), driver: AtomicUsize::new(0), compute: false, key: 0, + used: AtomicBool::new(false), late: AtomicBool::new(false), spared: AtomicBool::new(false), + }; + pending.note_use(); + assert!(!first_build.candidate_queued.load(Ordering::Acquire)); + + note_eviction_candidate_on(&first_build, 10, &queue); + note_eviction_candidate_on(&first_build, 30, &queue); + note_eviction_candidate_on(&second_build, 20, &queue); + let selected = drain_eviction_candidates_on(&queue, 1); + assert_eq!(selected.len(), 1); + assert!(Arc::ptr_eq(&selected[0].build, &first_build)); + assert_eq!(selected[0].last_use_frame, 30); + assert_eq!(selected[0].completed_frame, first_build.completed_frame.load(Ordering::Relaxed)); + assert_eq!(drain_eviction_candidates_on(&queue, 0).len(), 0, "a zero budget inspected work"); + drop(selected); + let selected = drain_eviction_candidates_on(&queue, 1); + assert_eq!(selected.len(), 1); + assert!(Arc::ptr_eq(&selected[0].build, &second_build)); + drop(selected); + + assert!(matches!(first_recipe.begin_rebuild(), RebuildTurn::Leader)); + note_eviction_candidate_on(&first_build, 40, &queue); + assert!(drain_eviction_candidates_on(&queue, 1).is_empty(), "an active rebuild became evictable"); + first_recipe.finish_rebuild(RebuildResult::Failed); + first_build.owners.store(0, Ordering::Release); + note_eviction_candidate_on(&first_build, 50, &queue); + assert!(drain_eviction_candidates_on(&queue, 1).is_empty(), "a released build became evictable"); + + drop(pending); + let first_final = first_build.real.swap(0, Ordering::AcqRel); + let second_final = second_build.real.swap(0, Ordering::AcqRel); + drop(first_build); + drop(second_build); + drop(first_recipe); + drop(second_recipe); + release(first_final); + release(second_final); + assert_eq!((first.refs.load(Ordering::Relaxed), second.refs.load(Ordering::Relaxed)), (0, 0)); + } + #[test] fn build_retains_a_reusable_recipe_after_its_initial_job_is_consumed() { let calls = Arc::new(AtomicUsize::new(0)); @@ -3794,6 +4126,7 @@ fn resolve_and_pin_pending(pso: usize, p: &Arc<Pending>, mode: ResolveMode) -> ( fn pin_resolved(pso: usize, p: &Pending, resolved: usize, bound_unbuilt: bool) -> (usize, Option<NativeGeneration>, bool) { let Some(recipe) = p.build.recipe.as_ref() else { return (resolved, None, false) }; + note_eviction_candidate(&p.build); let _done = p.build.done.lock().unwrap(); let current = p.build.real.load(Ordering::Acquire); if current == resolved { From b5f7fc0ebb413eee84cb5947877e2231d23819bc Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:03:04 -0800 Subject: [PATCH 223/265] D3D12.X: model immutable sparse upload plans Carry exact mapping, published-hash and source-page identities between a bounded work claim and a future serialized commit phase. Invalid or abandoned plans restore only their exact claim, while only a successful serialized commit closure consumes it without opening allocator, command-list or staging state. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 301 ++++++++++++++++++++++++++++ 1 file changed, 301 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index bf96ccbbd9..16725b3641 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -484,6 +484,162 @@ impl Drop for SparseWorkClaim { } } +/// Point-in-time identities needed to prove that planning and a later serialized upload commit +/// still refer to the same sparse page. `source` names the observed CPU page by chunk hash rather +/// than retaining a raw pointer across the unlocked interval. Title writes are outside sparse +/// state/upload exclusion, so a future commit must own or revalidate the bytes it actually copies. +#[derive(Clone, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct UploadPageObservation { + page: usize, + pool: (u32, u32), + hole: bool, + sent: Option<[u64; CHUNKS]>, + source: [u64; CHUNKS], +} + +#[derive(Clone, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct PlannedUploadPage { + page: usize, + tile: usize, + pool: (u32, u32), + reasons: WorkReasons, + zero: bool, + dirty: bool, + dirty_ranges: Vec<(usize, usize)>, + sent: Option<[u64; CHUNKS]>, + source: [u64; CHUNKS], +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum UploadPlanInvalid { + StateGeneration, + MappingEpoch, + MissingPage, + Mapping, + SentHashes, + SourceHashes, +} + +#[derive(Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum UploadPlanCommitError<E> { + Invalid(UploadPlanInvalid), + Commit(E), +} + +/// Inert immutable work between an exact journal claim and a future short serialized commit. +/// Dropping an uncommitted plan restores its claim. No command allocator, list or staging range is +/// opened or reserved here; those remain responsibilities of the later commit-phase stage. A +/// future caller must run `commit_if_valid` under the serialized sparse-state commit exclusion so +/// validation and publication cannot be separated by a remap. That exclusion does not stop title +/// CPU writes: the fallible closure must own or revalidate source bytes before it returns success. +#[allow(dead_code)] +struct SparseUploadPlan { + claim: Option<SparseWorkClaim>, + state_generation: u64, + mapping_epoch: u64, + pages: Vec<PlannedUploadPage>, +} + +#[allow(dead_code)] +impl SparseUploadPlan { + fn build( + claim: SparseWorkClaim, + state_generation: u64, + mapping_epoch: u64, + mut observe: impl FnMut(usize) -> Option<UploadPageObservation>, + ) -> Option<Self> { + let claimed = claim.claimed.as_ref()?; + if claimed.token.state_generation != state_generation { + return None; + } + let mut pages = Vec::with_capacity(claimed.pages.len()); + for &(page, reasons) in &claimed.pages { + let observation = observe(page)?; + if observation.page != page || observation.hole { + return None; + } + let dirty = reasons.0 & (WorkReasons::DIRTY.0 | WorkReasons::RETRY.0) != 0; + let mut dirty_ranges = Vec::new(); + if dirty { + let sent = observation.sent.as_ref().unwrap_or(&ZERO_HASHES); + for (chunk, (&source, &previous)) in observation.source.iter().zip(sent).enumerate() { + if source != previous { + push_run(&mut dirty_ranges, page + chunk * CHUNK, CHUNK); + } + } + } + pages.push(PlannedUploadPage { + page, + tile: page & !(TILE - 1), + pool: observation.pool, + reasons, + zero: reasons.0 & WorkReasons::ZERO.0 != 0, + dirty, + dirty_ranges, + sent: observation.sent, + source: observation.source, + }); + } + Some(Self { claim: Some(claim), state_generation, mapping_epoch, pages }) + } + + fn pages(&self) -> &[PlannedUploadPage] { + &self.pages + } + + fn validate( + &self, + state_generation: u64, + mapping_epoch: u64, + mut observe: impl FnMut(usize) -> Option<UploadPageObservation>, + ) -> Result<(), UploadPlanInvalid> { + if state_generation != self.state_generation { + return Err(UploadPlanInvalid::StateGeneration); + } + if mapping_epoch != self.mapping_epoch { + return Err(UploadPlanInvalid::MappingEpoch); + } + for planned in &self.pages { + let current = observe(planned.page).ok_or(UploadPlanInvalid::MissingPage)?; + if current.page != planned.page + || current.page & !(TILE - 1) != planned.tile + || current.pool != planned.pool + || current.hole + { + return Err(UploadPlanInvalid::Mapping); + } + if current.sent != planned.sent { + return Err(UploadPlanInvalid::SentHashes); + } + if current.source != planned.source { + return Err(UploadPlanInvalid::SourceHashes); + } + } + Ok(()) + } + + /// Keep the exact work claim armed through the future serialized commit. Only a successful + /// closure consumes it; validation failure, commit refusal, or unwind restores it through the + /// claim guard. The closure must return success only after submission has accepted the work + /// and any source bytes it names can no longer change underneath that submission. + fn commit_if_valid<T, E>( + mut self, + state_generation: u64, + mapping_epoch: u64, + observe: impl FnMut(usize) -> Option<UploadPageObservation>, + commit: impl FnOnce(&[PlannedUploadPage]) -> Result<T, E>, + ) -> Result<(T, WorkClaimResolution), UploadPlanCommitError<E>> { + self.validate(state_generation, mapping_epoch, observe).map_err(UploadPlanCommitError::Invalid)?; + let result = commit(&self.pages).map_err(UploadPlanCommitError::Commit)?; + let claim = self.claim.take().expect("finished sparse upload plan"); + Ok((result, claim.commit())) + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) enum PreparationOutcome { Ready, @@ -3331,6 +3487,151 @@ mod tests { assert!(current.claim(1).is_none(), "stale producers polluted the current journal"); } + fn upload_observation(page: usize, pool: (u32, u32), source_word: u64) -> UploadPageObservation { + let mut source = ZERO_HASHES; + source[1] = source_word; + source[2] = source_word; + UploadPageObservation { page, pool, hole: false, sent: Some(ZERO_HASHES), source } + } + + fn one_page_upload_plan() -> (SparseWorkClaims, SparseUploadPlan, UploadPageObservation) { + let claims = SparseWorkClaims::new(31); + assert!(claims.add_dirty_pages([0x2_1000])); + let claim = claims.claim(1).unwrap(); + let observation = upload_observation(0x2_1000, (4, 9), 0xA5); + let plan = SparseUploadPlan::build(claim, 31, 7, |_| Some(observation.clone())).unwrap(); + (claims, plan, observation) + } + + #[test] + fn sparse_upload_plan_preserves_claim_order_intent_and_source_ranges() { + let claims = SparseWorkClaims::new(29); + assert!(claims.add_zero_ranges(&[(0x1_1000, PAGE)])); + assert!(claims.add_dirty_pages([0x1_1000])); + assert!(claims.add_retry_pages([0x1_2000])); + let claim = claims.claim(2).unwrap(); + let first = upload_observation(0x1_1000, (2, 3), 0x91); + let second = upload_observation(0x1_2000, (2, 3), ZERO_HASH); + let plan = SparseUploadPlan::build(claim, 29, 5, |page| match page { + 0x1_1000 => Some(first.clone()), + 0x1_2000 => Some(second.clone()), + _ => None, + }).unwrap(); + + assert_eq!(plan.pages().iter().map(|page| page.page).collect::<Vec<_>>(), [0x1_1000, 0x1_2000]); + assert!(plan.pages()[0].zero); + assert!(plan.pages()[0].dirty); + assert_eq!(plan.pages()[0].dirty_ranges, [(0x1_1000 + CHUNK, 2 * CHUNK)]); + assert!(!plan.pages()[1].zero); + assert!(plan.pages()[1].dirty, "retry work lost its dirty intent when no chunks changed"); + assert!(plan.pages()[1].dirty_ranges.is_empty()); + assert_eq!( + plan.commit_if_valid( + 29, + 5, + |page| match page { + 0x1_1000 => Some(first.clone()), + 0x1_2000 => Some(second.clone()), + _ => None, + }, + |_| Ok::<_, ()>(17), + ), + Ok((17, WorkClaimResolution::Committed)), + ); + assert!(claims.claim(1).is_none(), "committed plan restored its claim"); + } + + #[test] + fn sparse_upload_plan_generation_and_epoch_failures_restore_the_claim() { + let (claims, plan, observation) = one_page_upload_plan(); + assert_eq!( + plan.commit_if_valid(32, 7, |_| Some(observation.clone()), |_| Ok::<_, ()>(())), + Err(UploadPlanCommitError::Invalid(UploadPlanInvalid::StateGeneration)), + ); + let restored = claims.claim(1).expect("generation failure restored work"); + assert_eq!(restored.cancel(), WorkClaimResolution::Restored); + + let claim = claims.claim(1).unwrap(); + let plan = SparseUploadPlan::build(claim, 31, 7, |_| Some(observation.clone())).unwrap(); + assert_eq!( + plan.commit_if_valid(31, 8, |_| Some(observation.clone()), |_| Ok::<_, ()>(())), + Err(UploadPlanCommitError::Invalid(UploadPlanInvalid::MappingEpoch)), + ); + assert!(claims.claim(1).is_some(), "epoch failure did not restore work"); + } + + #[test] + fn sparse_upload_plan_revalidates_mapping_sent_and_source_identities() { + for expected in [ + UploadPlanInvalid::MissingPage, + UploadPlanInvalid::Mapping, + UploadPlanInvalid::SentHashes, + UploadPlanInvalid::SourceHashes, + ] { + let (claims, plan, observation) = one_page_upload_plan(); + let result = plan.commit_if_valid( + 31, + 7, + |_| { + let mut changed = observation.clone(); + match expected { + UploadPlanInvalid::MissingPage => return None, + UploadPlanInvalid::Mapping => changed.pool.1 += 1, + UploadPlanInvalid::SentHashes => changed.sent.as_mut().unwrap()[3] ^= 1, + UploadPlanInvalid::SourceHashes => changed.source[3] ^= 1, + _ => unreachable!(), + } + Some(changed) + }, + |_| Ok::<_, ()>(()), + ); + assert_eq!(result, Err(UploadPlanCommitError::Invalid(expected))); + assert!(claims.claim(1).is_some(), "{expected:?} did not restore work"); + } + } + + #[test] + fn sparse_upload_plan_commit_failure_restores_the_validated_claim() { + let (claims, plan, observation) = one_page_upload_plan(); + let result = plan.commit_if_valid( + 31, + 7, + |_| Some(observation.clone()), + |pages| { + assert_eq!(pages.len(), 1, "validated commit lost its planned page"); + Err::<(), _>("queue refused upload") + }, + ); + assert_eq!(result, Err(UploadPlanCommitError::Commit("queue refused upload"))); + assert!(claims.claim(1).is_some(), "failed commit consumed its exact work claim"); + } + + #[test] + fn sparse_upload_plan_commit_unwind_restores_the_validated_claim() { + let (claims, plan, observation) = one_page_upload_plan(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = plan.commit_if_valid( + 31, + 7, + |_| Some(observation.clone()), + |_| -> Result<(), ()> { panic!("driver submission panicked") }, + ); + })); + assert!(result.is_err()); + assert!(claims.claim(1).is_some(), "panicked commit consumed its exact work claim"); + } + + #[test] + fn incomplete_sparse_upload_plan_construction_restores_its_claim() { + let claims = SparseWorkClaims::new(37); + assert!(claims.add_dirty_pages([0x3_0000, 0x3_1000])); + let claim = claims.claim(2).unwrap(); + assert!(SparseUploadPlan::build(claim, 37, 1, |page| { + (page == 0x3_0000).then(|| upload_observation(page, (5, 1), 7)) + }).is_none()); + assert_eq!(claims.claim(2).unwrap().pages().len(), 2); + } + #[test] fn a_failed_title_queue_wait_rolls_back_only_its_reservation() { let mut waited = FxHashMap::from_iter([(1, 4), (2, 7)]); From ba798d8fe610a2e79feaa7c50a410abf7c13e328 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:07:08 -0800 Subject: [PATCH 224/265] D3D12.X: rank bounded pipeline eviction candidates Apply conservative frame-age thresholds to a bounded background drain and order eligible resident pipelines oldest-first. Selection re-reads use/completion ages, treats frame-counter wrap as recent, and leaves pressure admission and eviction uncalled. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 194 +++++++++++++++++++++++-- 1 file changed, 184 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 8bb619aba9..28cb8bea6b 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -552,11 +552,27 @@ struct EvictionCandidate { build: Arc<Build>, last_use_frame: u64, completed_frame: u64, + clear_queued_on_drop: bool, } impl Drop for EvictionCandidate { fn drop(&mut self) { - self.build.candidate_queued.store(false, Ordering::Release); + if self.clear_queued_on_drop { + self.build.candidate_queued.store(false, Ordering::Release); + } + } +} + +impl EvictionCandidate { + /// Return a deferred candidate to the bounded weak journal without opening a duplicate-record + /// window. If a crossing producer filled the freed slot, dropping this owner clears the flag + /// so a later bind can retry instead of leaving the build permanently marked as queued. + fn requeue_on<const N: usize>(mut self, candidates: &CandidateQueue<Build, N>) -> bool { + if candidates.push(Arc::downgrade(&self.build)).is_err() { + return false; + } + self.clear_queued_on_drop = false; + true } } @@ -602,7 +618,9 @@ fn resident_candidate(build: &Arc<Build>) -> Option<EvictionCandidate> { drop(generation); drop(rebuild); drop(done); - Some(EvictionCandidate { build: build.clone(), last_use_frame, completed_frame }) + Some(EvictionCandidate { + build: build.clone(), last_use_frame, completed_frame, clear_queued_on_drop: true, + }) } /// Drain at most `limit` journal records on a background policy turn. The weak allocation identity @@ -632,6 +650,88 @@ fn drain_eviction_candidates(limit: usize) -> Vec<EvictionCandidate> { drain_eviction_candidates_on(eviction_candidates(), limit) } +#[derive(Clone, Copy)] +struct EvictionSelectionLimits { + max_scan: usize, + max_select: usize, + min_unused_frames: u64, + min_resident_frames: u64, +} + +/// One bounded, point-in-time policy candidate. Actual eviction must still call +/// `try_evict_current`, which revalidates every ownership transition. +#[allow(dead_code)] +struct SelectedEvictionCandidate { + candidate: EvictionCandidate, + unused_frames: u64, + resident_frames: u64, +} + +/// Frame counters practically never wrap. If they do, treating pre-wrap timestamps as recent is +/// conservative: a policy pauses eviction instead of assigning an enormous, false age. +fn conservative_frame_age(now: u64, since: u64) -> u64 { + now.checked_sub(since).unwrap_or(0) +} + +fn partition_eviction_candidates( + candidates: Vec<EvictionCandidate>, now: u64, limits: EvictionSelectionLimits, +) -> (Vec<SelectedEvictionCandidate>, Vec<EvictionCandidate>) { + if limits.max_select == 0 { + return (Vec::new(), candidates); + } + let mut selected = Vec::new(); + let mut deferred = Vec::new(); + for candidate in candidates { + // A bind after the journal record was drained still updates this atomic while the + // candidate's dedup flag prevents another record. Use that latest point-in-time age, + // not the older snapshot captured by `resident_candidate`. + let last_use = candidate.build.last_use_frame.load(Ordering::Relaxed); + let completed = candidate.build.completed_frame.load(Ordering::Relaxed); + let unused_frames = conservative_frame_age(now, last_use); + let resident_frames = conservative_frame_age(now, completed); + if unused_frames >= limits.min_unused_frames && resident_frames >= limits.min_resident_frames { + selected.push(SelectedEvictionCandidate { candidate, unused_frames, resident_frames }); + } else { + deferred.push(candidate); + } + } + selected.sort_unstable_by(|a, b| { + b.unused_frames + .cmp(&a.unused_frames) + .then_with(|| b.resident_frames.cmp(&a.resident_frames)) + .then_with(|| { + (Arc::as_ptr(&a.candidate.build) as usize).cmp(&(Arc::as_ptr(&b.candidate.build) as usize)) + }) + }); + if selected.len() > limits.max_select { + deferred.extend(selected.drain(limits.max_select..).map(|selected| selected.candidate)); + } + (selected, deferred) +} + +/// Inspect and rank a bounded amount of journalled work on a future background policy turn. This +/// remains deliberately uncalled: pressure admission and the eviction/rehydration trigger are +/// separate stages. +#[allow(dead_code)] +fn select_eviction_candidates_on<const N: usize>( + candidates: &CandidateQueue<Build, N>, now: u64, limits: EvictionSelectionLimits, +) -> Vec<SelectedEvictionCandidate> { + if limits.max_scan == 0 || limits.max_select == 0 { + return Vec::new(); + } + let (selected, deferred) = + partition_eviction_candidates(drain_eviction_candidates_on(candidates, limits.max_scan), now, limits); + for candidate in deferred { + let _ = candidate.requeue_on(candidates); + } + selected +} + +#[allow(dead_code)] +fn select_eviction_candidates(limits: EvictionSelectionLimits) -> Vec<SelectedEvictionCandidate> { + select_eviction_candidates_on(eviction_candidates(), super::present::presents(), limits) +} + fn forget_in_flight(build: &Arc<Build>) { let Some(key) = &build.compute_key else { return }; let mut registry = IN_FLIGHT.lock().unwrap(); @@ -2031,25 +2131,41 @@ mod used_tests { note_eviction_candidate_on(&first_build, 10, &queue); note_eviction_candidate_on(&first_build, 30, &queue); note_eviction_candidate_on(&second_build, 20, &queue); - let selected = drain_eviction_candidates_on(&queue, 1); + let limits = EvictionSelectionLimits { + max_scan: 2, max_select: 1, min_unused_frames: 0, min_resident_frames: 0, + }; + let selected = select_eviction_candidates_on(&queue, 100, limits); assert_eq!(selected.len(), 1); - assert!(Arc::ptr_eq(&selected[0].build, &first_build)); - assert_eq!(selected[0].last_use_frame, 30); - assert_eq!(selected[0].completed_frame, first_build.completed_frame.load(Ordering::Relaxed)); + assert!(Arc::ptr_eq(&selected[0].candidate.build, &second_build)); + assert_eq!(selected[0].unused_frames, 80); assert_eq!(drain_eviction_candidates_on(&queue, 0).len(), 0, "a zero budget inspected work"); drop(selected); - let selected = drain_eviction_candidates_on(&queue, 1); + let selected = select_eviction_candidates_on(&queue, 100, limits); assert_eq!(selected.len(), 1); - assert!(Arc::ptr_eq(&selected[0].build, &second_build)); + assert!(Arc::ptr_eq(&selected[0].candidate.build, &first_build)); + drop(selected); + + let recent_limits = EvictionSelectionLimits { + max_scan: 2, max_select: 1, min_unused_frames: 10, min_resident_frames: 0, + }; + note_eviction_candidate_on(&first_build, 95, &queue); + for _ in 0..3 { + assert!(select_eviction_candidates_on(&queue, 100, recent_limits).is_empty()); + assert!(first_build.candidate_queued.load(Ordering::Acquire)); + } + let selected = select_eviction_candidates_on(&queue, 105, recent_limits); + assert_eq!(selected.len(), 1, "a deferred candidate required another bind to reappear"); + assert!(Arc::ptr_eq(&selected[0].candidate.build, &first_build)); + assert!(queue.pop().is_none(), "repeated deferral duplicated a candidate record"); drop(selected); assert!(matches!(first_recipe.begin_rebuild(), RebuildTurn::Leader)); note_eviction_candidate_on(&first_build, 40, &queue); - assert!(drain_eviction_candidates_on(&queue, 1).is_empty(), "an active rebuild became evictable"); + assert!(select_eviction_candidates_on(&queue, 100, limits).is_empty(), "an active rebuild became evictable"); first_recipe.finish_rebuild(RebuildResult::Failed); first_build.owners.store(0, Ordering::Release); note_eviction_candidate_on(&first_build, 50, &queue); - assert!(drain_eviction_candidates_on(&queue, 1).is_empty(), "a released build became evictable"); + assert!(select_eviction_candidates_on(&queue, 100, limits).is_empty(), "a released build became evictable"); drop(pending); let first_final = first_build.real.swap(0, Ordering::AcqRel); @@ -2063,6 +2179,64 @@ mod used_tests { assert_eq!((first.refs.load(Ordering::Relaxed), second.refs.load(Ordering::Relaxed)), (0, 0)); } + #[test] + fn eviction_candidate_policy_uses_latest_age_and_orders_oldest_first() { + let make = |last_use, completed| { + let build = Arc::new(Build::new(Box::new(|| 0), false)); + build.last_use_frame.store(last_use, Ordering::Relaxed); + build.completed_frame.store(completed, Ordering::Relaxed); + build.candidate_queued.store(true, Ordering::Release); + EvictionCandidate { + build, last_use_frame: last_use, completed_frame: completed, + clear_queued_on_drop: true, + } + }; + let oldest = make(10, 5); + let next = make(20, 1); + let recent = make(95, 0); + let young_resident = make(1, 95); + let wrapped = make(u64::MAX, 0); + let oldest_build = oldest.build.clone(); + let next_build = next.build.clone(); + let limits = EvictionSelectionLimits { + max_scan: 4, max_select: 2, min_unused_frames: 10, min_resident_frames: 20, + }; + + let (selected, _) = + partition_eviction_candidates(vec![recent, next, wrapped, young_resident, oldest], 100, limits); + assert_eq!(selected.len(), 2); + assert!(Arc::ptr_eq(&selected[0].candidate.build, &oldest_build)); + assert_eq!((selected[0].unused_frames, selected[0].resident_frames), (90, 95)); + assert!(Arc::ptr_eq(&selected[1].candidate.build, &next_build)); + + // A use after background drain is still visible through the Build atomic, even though the + // candidate's dedup flag prevents a second journal record while this owner exists. + let used_after_drain = make(30, 1); + used_after_drain.build.last_use_frame.store(99, Ordering::Relaxed); + assert!(partition_eviction_candidates(vec![used_after_drain], 100, limits).0.is_empty()); + assert_eq!(conservative_frame_age(3, u64::MAX), 0, "frame wrap assigned a false old age"); + } + + #[test] + fn eviction_candidate_requeue_full_clears_the_dedup_flag() { + let queue = CandidateQueue::<Build, 2>::new(); + let retained = [ + Arc::new(Build::new(Box::new(|| 0), false)), + Arc::new(Build::new(Box::new(|| 0), false)), + ]; + assert!(queue.push(Arc::downgrade(&retained[0])).is_ok()); + assert!(queue.push(Arc::downgrade(&retained[1])).is_ok()); + + let build = Arc::new(Build::new(Box::new(|| 0), false)); + build.candidate_queued.store(true, Ordering::Release); + let candidate = EvictionCandidate { + build: build.clone(), last_use_frame: 0, completed_frame: 0, + clear_queued_on_drop: true, + }; + assert!(!candidate.requeue_on(&queue)); + assert!(!build.candidate_queued.load(Ordering::Acquire)); + } + #[test] fn build_retains_a_reusable_recipe_after_its_initial_job_is_consumed() { let calls = Arc::new(AtomicUsize::new(0)); From 3116f06f8b82122bc5551d3155c90bc6877e7bf9 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:13:22 -0800 Subject: [PATCH 225/265] D3D12.X: model sparse upload ring reservations Track generation-bound slot and ring ownership with monotonic reservation serials. Retire only a contiguous prefix backed by exact submission receipts, and fail closed when an ordering signal cannot be established. Keep the model private and inert so later commit-phase work can adopt it without changing live sparse upload behavior. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 378 ++++++++++++++++++++++++++++ 1 file changed, 378 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 16725b3641..d941fe4e1d 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -640,6 +640,276 @@ impl SparseUploadPlan { } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct UploadReservationToken { + state_generation: u64, + serial: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct UploadRingRange { + start: u64, + end: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct UploadSubmissionReceipt { + token: UploadReservationToken, + fence: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum UploadReservationState { + Reserved, + Submitted { fence: u64, retired: bool }, + Cancelled, + Poisoned, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum UploadReservationError { + Poisoned, + StaleGeneration, + Slot, + SlotBusy, + Empty, + TooLarge, + Full, + Exhausted, + Missing, + State, + Fence, +} + +struct UploadReservationRecord { + slot: usize, + range: UploadRingRange, + state: UploadReservationState, +} + +/// Inert ownership model for a later short upload commit phase. Ring positions only advance; +/// cancellation leaves a retired interval in the ordered ledger instead of rewinding across a +/// newer reservation. Submitted intervals become reusable only after their exact fence retires and +/// every older interval has retired. A failed ordering signal poisons the whole generation. +#[allow(dead_code)] +struct UploadReservationLedger { + state_generation: u64, + capacity: u64, + alignment: u64, + next_serial: u64, + cursor: u64, + reclaimed: u64, + poisoned: bool, + slots: Vec<Option<u64>>, + order: VecDeque<u64>, + records: BTreeMap<u64, UploadReservationRecord>, +} + +#[allow(dead_code)] +impl UploadReservationLedger { + fn new(state_generation: u64, slots: usize, capacity: usize, alignment: usize) -> Self { + assert!(slots > 0); + assert!(capacity > 0); + assert!(alignment > 0 && alignment.is_power_of_two() && capacity % alignment == 0); + Self { + state_generation, + capacity: capacity as u64, + alignment: alignment as u64, + next_serial: 0, + cursor: 0, + reclaimed: 0, + poisoned: false, + slots: vec![None; slots], + order: VecDeque::new(), + records: BTreeMap::new(), + } + } + + fn reserve( + &mut self, state_generation: u64, slot: usize, bytes: usize, + ) -> Result<(UploadReservationToken, UploadRingRange), UploadReservationError> { + if state_generation != self.state_generation { + return Err(UploadReservationError::StaleGeneration); + } + if self.poisoned { + return Err(UploadReservationError::Poisoned); + } + let owner = self.slots.get(slot).ok_or(UploadReservationError::Slot)?; + if owner.is_some() { + return Err(UploadReservationError::SlotBusy); + } + if bytes == 0 { + return Err(UploadReservationError::Empty); + } + if bytes as u64 > self.capacity { + return Err(UploadReservationError::TooLarge); + } + let (cursor, reclaimed) = if self.order.is_empty() { + let offset = self.cursor % self.capacity; + let boundary = if offset == 0 { + self.cursor + } else { + self.cursor.checked_add(self.capacity - offset).ok_or(UploadReservationError::Exhausted)? + }; + (boundary, boundary) + } else { + (self.cursor, self.reclaimed) + }; + let mask = self.alignment - 1; + let mut start = cursor.checked_add(mask).ok_or(UploadReservationError::Exhausted)? & !mask; + let offset = start % self.capacity; + if offset.checked_add(bytes as u64).ok_or(UploadReservationError::Exhausted)? > self.capacity { + start = start.checked_add(self.capacity - offset).ok_or(UploadReservationError::Exhausted)?; + } + let end = start.checked_add(bytes as u64).ok_or(UploadReservationError::Exhausted)?; + if end.checked_sub(reclaimed).ok_or(UploadReservationError::Exhausted)? > self.capacity { + return Err(UploadReservationError::Full); + } + let serial = self.next_serial.checked_add(1).ok_or(UploadReservationError::Exhausted)?; + self.next_serial = serial; + self.cursor = end; + self.reclaimed = reclaimed; + self.slots[slot] = Some(serial); + let range = UploadRingRange { start, end }; + self.order.push_back(serial); + self.records.insert(serial, UploadReservationRecord { slot, range, state: UploadReservationState::Reserved }); + Ok((UploadReservationToken { state_generation, serial }, range)) + } + + fn submit(&mut self, token: UploadReservationToken, fence: u64) -> Result<(), UploadReservationError> { + let record = self.record_mut(token)?; + if record.state != UploadReservationState::Reserved || fence == 0 { + return Err(UploadReservationError::State); + } + record.state = UploadReservationState::Submitted { fence, retired: false }; + Ok(()) + } + + fn complete(&mut self, receipt: UploadSubmissionReceipt) -> Result<u64, UploadReservationError> { + let record = self.record_mut(receipt.token)?; + match record.state { + UploadReservationState::Submitted { fence: expected, retired: false } if expected == receipt.fence => { + record.state = UploadReservationState::Submitted { fence: receipt.fence, retired: true }; + let slot = record.slot; + self.slots[slot] = None; + Ok(self.reclaim()) + } + UploadReservationState::Submitted { fence: expected, .. } if expected != receipt.fence => { + Err(UploadReservationError::Fence) + } + _ => Err(UploadReservationError::State), + } + } + + fn cancel(&mut self, token: UploadReservationToken) -> Result<u64, UploadReservationError> { + let record = self.record_mut(token)?; + if record.state != UploadReservationState::Reserved { + return Err(UploadReservationError::State); + } + record.state = UploadReservationState::Cancelled; + let slot = record.slot; + self.slots[slot] = None; + Ok(self.reclaim()) + } + + fn poison(&mut self, token: UploadReservationToken) -> Result<(), UploadReservationError> { + let record = self.record_mut(token)?; + if record.state != UploadReservationState::Reserved { + return Err(UploadReservationError::State); + } + record.state = UploadReservationState::Poisoned; + self.poisoned = true; + Ok(()) + } + + fn record_mut( + &mut self, token: UploadReservationToken, + ) -> Result<&mut UploadReservationRecord, UploadReservationError> { + if token.state_generation != self.state_generation { + return Err(UploadReservationError::StaleGeneration); + } + self.records.get_mut(&token.serial).ok_or(UploadReservationError::Missing) + } + + fn reclaim(&mut self) -> u64 { + while let Some(&serial) = self.order.front() { + let retired = self.records.get(&serial).is_some_and(|record| match record.state { + UploadReservationState::Cancelled => true, + UploadReservationState::Submitted { retired, .. } => retired, + UploadReservationState::Reserved | UploadReservationState::Poisoned => false, + }); + if !retired { + break; + } + let record = self.records.remove(&serial).unwrap(); + self.reclaimed = record.range.end; + self.order.pop_front(); + } + self.reclaimed + } +} + +#[derive(Clone)] +#[allow(dead_code)] +struct UploadReservations(Arc<Mutex<UploadReservationLedger>>); + +#[allow(dead_code)] +impl UploadReservations { + fn new(state_generation: u64, slots: usize, capacity: usize, alignment: usize) -> Self { + Self(Arc::new(Mutex::new(UploadReservationLedger::new(state_generation, slots, capacity, alignment)))) + } + + fn reserve(&self, slot: usize, bytes: usize) -> Result<UploadReservation, UploadReservationError> { + let mut ledger = self.0.lock().unwrap(); + let generation = ledger.state_generation; + let (token, range) = ledger.reserve(generation, slot, bytes)?; + Ok(UploadReservation { ledger: self.0.clone(), token: Some(token), range }) + } + + fn complete(&self, receipt: UploadSubmissionReceipt) -> Result<u64, UploadReservationError> { + self.0.lock().unwrap().complete(receipt) + } +} + +#[allow(dead_code)] +struct UploadReservation { + ledger: Arc<Mutex<UploadReservationLedger>>, + token: Option<UploadReservationToken>, + range: UploadRingRange, +} + +#[allow(dead_code)] +impl UploadReservation { + fn range(&self) -> UploadRingRange { self.range } + + fn submit(mut self, fence: u64) -> Result<UploadSubmissionReceipt, UploadReservationError> { + let token = self.token.unwrap(); + self.ledger.lock().unwrap().submit(token, fence)?; + self.token.take(); + Ok(UploadSubmissionReceipt { token, fence }) + } + + fn poison(mut self) -> Result<(), UploadReservationError> { + let token = self.token.unwrap(); + self.ledger.lock().unwrap().poison(token)?; + self.token.take(); + Ok(()) + } +} + +impl Drop for UploadReservation { + fn drop(&mut self) { + if let Some(token) = self.token.take() { + let _ = self.ledger.lock().unwrap().cancel(token); + } + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) enum PreparationOutcome { Ready, @@ -3632,6 +3902,114 @@ mod tests { assert_eq!(claims.claim(2).unwrap().pages().len(), 2); } + #[test] + fn upload_reservations_reclaim_only_a_contiguous_retired_prefix() { + let reservations = UploadReservations::new(41, 2, 256, 64); + let first = reservations.reserve(0, 80).unwrap(); + let second = reservations.reserve(1, 80).unwrap(); + assert_eq!(first.range(), UploadRingRange { start: 0, end: 80 }); + assert_eq!(second.range(), UploadRingRange { start: 128, end: 208 }); + let first = first.submit(5).unwrap(); + let second = second.submit(6).unwrap(); + + assert_eq!(reservations.complete(second), Ok(0), "later retirement crossed an older owner"); + assert!(matches!(reservations.reserve(1, 64), Err(UploadReservationError::Full))); + assert_eq!(reservations.complete(first), Ok(208)); + + let wrapped = reservations.reserve(1, 64).unwrap(); + assert_eq!(wrapped.range(), UploadRingRange { start: 256, end: 320 }); + assert_eq!(wrapped.submit(7).and_then(|receipt| reservations.complete(receipt)), Ok(320)); + } + + #[test] + fn an_empty_ring_discards_tail_padding_before_a_full_capacity_reservation() { + let reservations = UploadReservations::new(42, 1, 256, 64); + drop(reservations.reserve(0, 64).unwrap()); + { + let ledger = reservations.0.lock().unwrap(); + assert_eq!((ledger.cursor, ledger.reclaimed), (64, 64)); + } + + let full = reservations.reserve(0, 256).unwrap(); + assert_eq!(full.range(), UploadRingRange { start: 256, end: 512 }); + let ledger = reservations.0.lock().unwrap(); + assert_eq!((ledger.cursor, ledger.reclaimed), (512, 256)); + } + + #[test] + fn failed_empty_ring_reservation_does_not_publish_boundary_normalization() { + let mut ledger = UploadReservationLedger::new(42, 1, 256, 64); + let token = ledger.reserve(42, 0, 64).unwrap().0; + assert_eq!(ledger.cancel(token), Ok(64)); + ledger.next_serial = u64::MAX; + + assert!(matches!(ledger.reserve(42, 0, 256), Err(UploadReservationError::Exhausted))); + assert_eq!((ledger.cursor, ledger.reclaimed), (64, 64)); + assert_eq!(ledger.next_serial, u64::MAX); + assert!(ledger.order.is_empty()); + assert!(ledger.records.is_empty()); + assert!(ledger.slots[0].is_none()); + } + + #[test] + fn cancelling_an_older_reservation_never_rewinds_newer_ring_work() { + let reservations = UploadReservations::new(43, 3, 512, 64); + let first = reservations.reserve(0, 64).unwrap(); + let middle = reservations.reserve(1, 64).unwrap(); + let third = reservations.reserve(2, 64).unwrap(); + let middle_token = middle.token.unwrap(); + drop(middle); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 0); + + let later = reservations.reserve(1, 64).unwrap(); + assert!(later.range().start >= third.range().end, "a cancellation rewound across newer work"); + drop(first); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 128); + assert_eq!(reservations.0.lock().unwrap().cancel(middle_token), Err(UploadReservationError::Missing)); + + let third = third.submit(8).unwrap(); + assert_eq!(reservations.complete(UploadSubmissionReceipt { fence: 9, ..third }), Err(UploadReservationError::Fence)); + assert_eq!(reservations.complete(third), Ok(192)); + drop(later); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 256); + } + + #[test] + fn dropped_reservation_cancels_exactly_it_and_signal_failure_poisons_reuse() { + let reservations = UploadReservations::new(47, 2, 256, 64); + let abandoned = reservations.reserve(0, 64).unwrap(); + let stale = abandoned.token.unwrap(); + drop(abandoned); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 64); + assert_eq!(reservations.0.lock().unwrap().cancel(stale), Err(UploadReservationError::Missing)); + + let poisoned = reservations.reserve(0, 64).unwrap(); + poisoned.poison().unwrap(); + let ledger = reservations.0.lock().unwrap(); + assert!(ledger.poisoned); + assert_eq!(ledger.slots[0], Some(2), "poison released an allocator with untracked GPU work"); + drop(ledger); + assert!(matches!(reservations.reserve(1, 64), Err(UploadReservationError::Poisoned))); + } + + #[test] + fn upload_reservation_bounds_generation_and_monotonic_overflow_fail_closed() { + let mut ledger = UploadReservationLedger::new(53, 1, 256, 64); + assert!(matches!(ledger.reserve(52, 0, 64), Err(UploadReservationError::StaleGeneration))); + assert!(matches!(ledger.reserve(53, 1, 0), Err(UploadReservationError::Slot))); + assert!(matches!(ledger.reserve(53, 0, 0), Err(UploadReservationError::Empty))); + assert!(matches!(ledger.reserve(53, 0, 257), Err(UploadReservationError::TooLarge))); + + ledger.cursor = u64::MAX - 31; + assert!(matches!(ledger.reserve(53, 0, 64), Err(UploadReservationError::Exhausted))); + ledger.cursor = 0; + ledger.next_serial = u64::MAX; + assert!(matches!(ledger.reserve(53, 0, 64), Err(UploadReservationError::Exhausted))); + assert!(ledger.records.is_empty()); + assert!(ledger.order.is_empty()); + assert!(ledger.slots[0].is_none()); + } + #[test] fn a_failed_title_queue_wait_rolls_back_only_its_reservation() { let mut waited = FxHashMap::from_iter([(1, 4), (2, 7)]); From ab323147e7339591484adb724989c02056e4dce3 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:18:06 -0800 Subject: [PATCH 226/265] Tests: compare flat and guarded heap-window reads Port direct-DXIL output-parity coverage for flat versus guarded heap reads across four and the maximum supported window count. Keep one window as a root-UAV-only degenerate baseline, and exercise null, outside-UMA, inactive-lane, and view-boundary reads in native and forced split-wave64 forms when supported. Assisted-by: Codex (GPT-5.6-sol) --- .../xcl/src/gpu/recomp/heap_window_tests.rs | 127 ++++++++++++++++++ 1 file changed, 127 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/heap_window_tests.rs b/crates/xcl/src/gpu/recomp/heap_window_tests.rs index 1ae5c75a4e..2f0084b2f0 100644 --- a/crates/xcl/src/gpu/recomp/heap_window_tests.rs +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -209,6 +209,133 @@ fn compile_variant(code: &[u8], direct: bool, heap: bool, mem_windows: u32) -> V } } +/// Direct-DXIL flat heap reads produce the same output as guarded heap reads for four windows +/// and the largest supported heap. This includes inactive lanes, null and outside-UMA +/// addresses, and a dwordx2 load ending at the raw view boundary. The one-window case is a +/// root-UAV-only degenerate baseline (heap flags intentionally collapse to that form). +/// Run native and explicitly split wave64 forms wherever the adapter supports them. +#[test] +fn gpu_heap_flat_reads_match_guarded_and_root_output() { + use crate::gpu::dxil::kernel::{translate, KernelOptions}; + + if let Err(err) = super::runner::adapter() { + println!("GPU unavailable – skipping ({err})"); + super::runner::skip_test("no GPU"); + return; + } + let mut wave_modes = Vec::new(); + if super::runner::wave64_supported() == Ok(true) { + wave_modes.push(("native wave64", false)); + } + if super::runner::wave32_supported() == Ok(true) { + wave_modes.push(("split wave64", true)); + } + if wave_modes.is_empty() { + println!("GPU has neither native wave64 nor wave32 for split wave64 – skipping"); + super::runner::skip_test("no wave64"); + return; + } + + let e = |n: &str, enc: &str, f: &[(&str, u64)]| crate::gpu::rdna2::encode(n, enc, f, None).unwrap(); + let mut code = Vec::new(); + code.extend(e("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 30), ("SBASE", 1), ("OFFSET", 0)])); + code.extend(e("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 31), ("SBASE", 2), ("OFFSET", 0)])); + code.extend(e("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 4), ("OFFSET", 4)])); + // Only lanes 33..63 execute the vector reads; inactive lanes retain their sentinels. + code.extend(e("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 160), ("VSRC1", 0)])); + code.extend(e("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 7), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)])); + code.extend(e("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 6), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", 0)])); + code.extend(e("GLOBAL_LOAD_DWORDX2", "ENC_FLAT_GLBL", &[("VDST", 8), ("ADDR", 10), ("SADDR", 0x7D), ("OFFSET", 0)])); + code.extend(e("S_ENDPGM", "ENC_SOPP", &[])); + + const BYTES: usize = 1 << 20; + const OLD: u32 = 0x7777_7777; + for windows in [1usize, 4, crate::gpu::uma::MAX_HEAP_WINDOWS] { + let arena = crate::gpu::uma::Uma::with_windows(windows, BYTES).unwrap(); + let bases: Vec<u64> = (0..windows).map(|k| arena.window(k).0 as u64).collect(); + let base_hi = (bases[0] >> 32) as u32; + let target = windows - 1; + let word = |a: u64| unsafe { &mut *(a as *mut u32) }; + for (k, &base) in bases.iter().enumerate() { + *word(base + 0x40) = 0xA000 + k as u32; + for lane in 0..64u64 { + *word(base + 0x100 + 4 * lane) = (k as u32 + 1) * 1000 + lane as u32; + } + *word(base + BYTES as u64 - 8) = 0xD000 + k as u32; + *word(base + BYTES as u64 - 4) = 0xE000 + k as u32; + } + + let mut st = super::runner::KernelState::default(); + st.sgpr[2..4].copy_from_slice(&[0x40, base_hi + target as u32]); + st.sgpr[4..6].copy_from_slice(&[0x40, base_hi + windows as u32 + 1]); + st.sgpr[8..12].copy_from_slice(&[0x100, (base_hi + target as u32) & 0xFFFF, 0x400, 0]); + st.sgpr[12..16].copy_from_slice(&[0x100, (base_hi + target as u32) & 0xFFFF | 4 << 16, 64, 0]); + for (lane, r) in st.vgpr.iter_mut().enumerate() { + let lane = lane as u32; + r[0] = lane; + r[4] = if lane % 8 == 6 { 0 } else { 0x100 + 4 * lane }; + r[5] = match lane % 8 { + 6 => 0, // null + 7 => base_hi + windows as u32 + 1, // outside UMA + _ => base_hi + lane % windows as u32, + }; + r[6..10].fill(OLD); + // One window uses a root UAV (no descriptor bounds); heap forms use the + // straddling read to verify the descriptor-view boundary. + r[10] = BYTES as u32 - if windows == 1 { 8 } else { 4 }; + r[11] = base_hi + target as u32; + } + + for &(wave, split) in &wave_modes { + let run = |mem_windows, state: &super::runner::KernelState| { + let dxil = translate(&code, KernelOptions { wave64: true, split, mem_windows, sampler_base: 0 }) + .unwrap_or_else(|err| panic!("{wave}, {windows} windows ({mem_windows:#x}): {err}")); + super::runner::run_in_arena(&dxil, state, &arena) + .unwrap_or_else(|err| panic!("{wave}, {windows} windows ({mem_windows:#x}): {err}")) + }; + let output = if windows == 1 { + run(1, &st) + } else { + let guarded = run(windows as u32 | super::HEAP_WINDOWS, &st); + let flat = run(windows as u32 | super::HEAP_WINDOWS | super::HEAP_FLAT, &st); + assert_eq!(guarded.sgpr[..32], flat.sgpr[..32], "{wave}, {windows} heap windows: SGPR parity"); + for lane in 0..64 { + assert_eq!(guarded.vgpr[lane][..12], flat.vgpr[lane][..12], "{wave}, {windows} heap windows: lane {lane} parity"); + } + flat + }; + if windows == crate::gpu::uma::MAX_WINDOWS { + // Root UAVs have no view bounds, so use an in-view dwordx2 for this baseline. + let mut root_st = st.clone(); + for r in &mut root_st.vgpr { + r[10] = BYTES as u32 - 8; + } + let root = run(windows as u32, &root_st); + let guarded_root = run(windows as u32 | super::HEAP_WINDOWS, &root_st); + assert_eq!(guarded_root.sgpr[..32], root.sgpr[..32], "{wave}, {windows} windows: branchless root-UAV SGPR baseline"); + for lane in 0..64 { + assert_eq!(guarded_root.vgpr[lane][..12], root.vgpr[lane][..12], "{wave}, {windows} windows: branchless root-UAV lane {lane} baseline"); + } + } + + assert_eq!((output.sgpr[30], output.sgpr[31]), (0xA000 + target as u32, 0), "{wave}, {windows} windows: scalar valid/outside"); + assert_eq!(output.sgpr[24..28], [1000 * windows as u32 + 1, 1000 * windows as u32 + 2, 1000 * windows as u32 + 3, 1000 * windows as u32 + 4], "{wave}, {windows} windows: scalar vector load"); + for lane in 0..64u32 { + let v = &output.vgpr[lane as usize]; + let active = lane > 32; + assert_eq!(v[7], if active { 1000 * windows as u32 + lane } else { OLD }, "{wave}, {windows} windows, lane {lane}: buffer load"); + let global = match lane % 8 { + 6 | 7 => 0, + _ => (lane % windows as u32 + 1) * 1000 + lane, + }; + assert_eq!(v[6], if active { global } else { OLD }, "{wave}, {windows} windows, lane {lane}: null/outside global load"); + let edge = if windows == 1 { [0xD000, 0xE000] } else { [0xE000 + target as u32, 0] }; + assert_eq!(v[8..10], if active { edge } else { [OLD, OLD] }, "{wave}, {windows} windows, lane {lane}: end-of-view dwordx2"); + } + } + } +} + /// Divergent per-lane window indexing (`NonUniformResourceIndex`): in a single wave, lanes hit /// window 0 (`l % 3 == 0`), window 1 (`l % 3 == 1`), and out-of-UMA (`l % 3 == 2`, aliasing w0 /// under `& 3`) simultaneously on loads, stores, and atomics. HLSL and direct DXIL must match From fa2167b202f6b4ff27eb11737d52c2a29bfaf6eb Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:18:01 -0800 Subject: [PATCH 227/265] D3D12.X: model pipeline pressure admission Define a default-off, pure pressure state over explicit DXGI budget samples. High/low hysteresis keeps decisions stable, while per-turn eviction limits and exponential rehydrate backoff bound future policy work. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 299 +++++++++++++++++++++++++ 1 file changed, 299 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 28cb8bea6b..5bf4336558 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -732,6 +732,162 @@ fn select_eviction_candidates(limits: EvictionSelectionLimits) -> Vec<SelectedEv select_eviction_candidates_on(eviction_candidates(), super::present::presents(), limits) } +/// Pure admission for a future background eviction/rehydration policy. It deliberately consumes +/// an explicit memory-report sample: sampling DXGI here would put adapter work on whichever thread +/// asked for a decision. Nothing constructs this state today, and its default remains disabled. +#[allow(dead_code)] +#[derive(Clone, Copy)] +struct PressureAdmissionConfig { + enabled: bool, + low_basis_points: u16, + high_basis_points: u16, + max_sample_age_turns: u64, + max_evictions_per_turn: usize, + rehydrate_backoff_turns: u64, + max_rehydrate_backoff_turns: u64, +} + +impl Default for PressureAdmissionConfig { + fn default() -> Self { + Self { + enabled: false, + low_basis_points: 7_500, + high_basis_points: 9_000, + max_sample_age_turns: 1, + max_evictions_per_turn: 1, + rehydrate_backoff_turns: 2, + max_rehydrate_backoff_turns: 64, + } + } +} + +#[allow(dead_code)] +#[derive(Clone, Copy)] +struct PressureSample { + observed_turn: u64, + segment: super::memory_report::Segment, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum PressureMode { + #[default] + Idle, + Evicting, + Rehydrating, +} + +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct PressureDecision { + max_evictions: usize, + allow_rehydrate: bool, +} + +#[allow(dead_code)] +struct PressureAdmission { + config: PressureAdmissionConfig, + mode: PressureMode, + last_observed_turn: Option<u64>, + eviction_budget_turn: Option<u64>, + evictions_issued: usize, + retry_rehydrate_at: Option<u64>, + next_rehydrate_backoff: u64, +} + +const PRESSURE_MAX_TURN_HORIZON: u64 = u64::MAX / 2; + +/// Serial turns practically never differ by half their range. Treat a small wrapped difference as +/// forward progress so one wrap does not make every subsequent pressure sample permanently stale. +fn pressure_turn_after(turn: u64, previous: u64) -> bool { + let difference = turn.wrapping_sub(previous); + difference != 0 && difference <= PRESSURE_MAX_TURN_HORIZON +} + +#[allow(dead_code)] +impl PressureAdmission { + fn new(config: PressureAdmissionConfig) -> Option<Self> { + (config.low_basis_points < config.high_basis_points + && config.high_basis_points <= 10_000 + && config.max_sample_age_turns <= PRESSURE_MAX_TURN_HORIZON + && config.rehydrate_backoff_turns != 0 + && config.rehydrate_backoff_turns <= config.max_rehydrate_backoff_turns + && config.max_rehydrate_backoff_turns <= PRESSURE_MAX_TURN_HORIZON) + .then_some(Self { + next_rehydrate_backoff: config.rehydrate_backoff_turns, + config, + mode: PressureMode::Idle, + last_observed_turn: None, + eviction_budget_turn: None, + evictions_issued: 0, + retry_rehydrate_at: None, + }) + } + + fn decide(&mut self, now: u64, sample: Option<PressureSample>) -> PressureDecision { + if !self.config.enabled { + return PressureDecision::default(); + } + let Some(sample) = sample else { return PressureDecision::default() }; + if sample.segment.budget == 0 + || pressure_turn_after(sample.observed_turn, now) + || now.wrapping_sub(sample.observed_turn) > self.config.max_sample_age_turns + || self.last_observed_turn.is_some_and(|last| !pressure_turn_after(sample.observed_turn, last)) + { + return PressureDecision::default(); + } + self.last_observed_turn = Some(sample.observed_turn); + let usage = u128::from(sample.segment.usage) * 10_000; + let budget = u128::from(sample.segment.budget); + if usage >= budget * u128::from(self.config.high_basis_points) { + self.mode = PressureMode::Evicting; + } else if usage <= budget * u128::from(self.config.low_basis_points) + && self.mode == PressureMode::Evicting + { + self.mode = PressureMode::Rehydrating; + } + match self.mode { + PressureMode::Idle => PressureDecision::default(), + PressureMode::Evicting => { + if self.eviction_budget_turn != Some(now) { + self.eviction_budget_turn = Some(now); + self.evictions_issued = 0; + } + let max_evictions = self.config.max_evictions_per_turn.saturating_sub(self.evictions_issued); + self.evictions_issued += max_evictions; + PressureDecision { max_evictions, allow_rehydrate: false } + } + PressureMode::Rehydrating => PressureDecision { + max_evictions: 0, + allow_rehydrate: self.retry_rehydrate_at.is_none_or(|retry| { + now == retry || pressure_turn_after(now, retry) + }), + }, + } + } + + fn note_rehydrate_result(&mut self, now: u64, succeeded: bool) { + if self.mode != PressureMode::Rehydrating { + return; + } + if succeeded { + self.retry_rehydrate_at = None; + self.next_rehydrate_backoff = self.config.rehydrate_backoff_turns; + return; + } + let delay = self.next_rehydrate_backoff; + self.retry_rehydrate_at = Some(now.wrapping_add(delay)); + self.next_rehydrate_backoff = delay.saturating_mul(2).min(self.config.max_rehydrate_backoff_turns); + } + + fn note_rehydration_complete(&mut self) { + if self.mode == PressureMode::Rehydrating { + self.mode = PressureMode::Idle; + self.retry_rehydrate_at = None; + self.next_rehydrate_backoff = self.config.rehydrate_backoff_turns; + } + } +} + fn forget_in_flight(build: &Arc<Build>) { let Some(key) = &build.compute_key else { return }; let mut registry = IN_FLIGHT.lock().unwrap(); @@ -2014,6 +2170,149 @@ mod used_tests { (*(this as *mut RebuildFakePso)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 } + fn pressure_config() -> PressureAdmissionConfig { + PressureAdmissionConfig { + enabled: true, + low_basis_points: 7_000, + high_basis_points: 9_000, + max_sample_age_turns: 1, + max_evictions_per_turn: 3, + rehydrate_backoff_turns: 2, + max_rehydrate_backoff_turns: 8, + } + } + + fn pressure_sample(turn: u64, usage: u64) -> PressureSample { + PressureSample { + observed_turn: turn, + segment: super::super::memory_report::Segment { usage, budget: 100 }, + } + } + + #[test] + fn pressure_admission_rejects_ambiguous_serial_horizons() { + let mut config = pressure_config(); + config.max_sample_age_turns = PRESSURE_MAX_TURN_HORIZON; + config.rehydrate_backoff_turns = PRESSURE_MAX_TURN_HORIZON; + config.max_rehydrate_backoff_turns = PRESSURE_MAX_TURN_HORIZON; + assert!(PressureAdmission::new(config).is_some(), "the exact serial horizon was rejected"); + + let ambiguous = PRESSURE_MAX_TURN_HORIZON + 1; + let mut sample_age = pressure_config(); + sample_age.max_sample_age_turns = ambiguous; + assert!(PressureAdmission::new(sample_age).is_none()); + let mut initial_backoff = pressure_config(); + initial_backoff.rehydrate_backoff_turns = ambiguous; + initial_backoff.max_rehydrate_backoff_turns = ambiguous; + assert!(PressureAdmission::new(initial_backoff).is_none()); + let mut maximum_backoff = pressure_config(); + maximum_backoff.max_rehydrate_backoff_turns = ambiguous; + assert!(PressureAdmission::new(maximum_backoff).is_none()); + } + + #[test] + fn pressure_admission_maximum_cooldown_does_not_appear_expired() { + let mut config = pressure_config(); + config.max_sample_age_turns = PRESSURE_MAX_TURN_HORIZON; + config.rehydrate_backoff_turns = PRESSURE_MAX_TURN_HORIZON; + config.max_rehydrate_backoff_turns = PRESSURE_MAX_TURN_HORIZON; + let mut state = PressureAdmission::new(config).unwrap(); + assert_eq!(state.decide(0, Some(pressure_sample(0, 95))).max_evictions, 3); + assert!(state.decide(1, Some(pressure_sample(1, 60))).allow_rehydrate); + state.note_rehydrate_result(1, false); + assert!(!state.decide(2, Some(pressure_sample(2, 60))).allow_rehydrate, + "a maximum unambiguous cooldown appeared immediately expired"); + assert!(!state.decide(PRESSURE_MAX_TURN_HORIZON, + Some(pressure_sample(PRESSURE_MAX_TURN_HORIZON, 60))).allow_rehydrate); + let retry = PRESSURE_MAX_TURN_HORIZON + 1; + assert!(state.decide(retry, Some(pressure_sample(retry, 60))).allow_rehydrate); + } + + #[test] + fn pressure_admission_hysteresis_bounds_each_eviction_turn() { + let mut state = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(state.decide(1, Some(pressure_sample(1, 85))), PressureDecision::default()); + assert_eq!(state.decide(2, Some(pressure_sample(2, 90))).max_evictions, 3); + assert_eq!(state.decide(3, Some(pressure_sample(3, 85))).max_evictions, 3, + "falling below the high watermark churned the policy"); + assert!(state.decide(4, Some(pressure_sample(4, 70))).allow_rehydrate); + assert!(state.decide(5, Some(pressure_sample(5, 85))).allow_rehydrate, + "rising above the low watermark churned the policy"); + assert_eq!(state.decide(6, Some(pressure_sample(6, 90))).max_evictions, 3); + } + + #[test] + fn pressure_admission_shares_one_eviction_budget_within_a_turn() { + let mut state = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(state.decide(10, Some(pressure_sample(9, 95))).max_evictions, 3); + assert_eq!(state.decide(10, Some(pressure_sample(10, 95))).max_evictions, 0, + "a second fresh sample replenished the same policy turn"); + assert_eq!(state.decide(11, Some(pressure_sample(11, 95))).max_evictions, 3, + "a new policy turn did not replenish its bounded allowance"); + } + + #[test] + fn pressure_admission_rejects_missing_invalid_and_stale_samples() { + let mut state = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(state.decide(1, Some(pressure_sample(1, 95))).max_evictions, 3); + assert_eq!(state.decide(2, None), PressureDecision::default()); + assert_eq!(state.decide(2, Some(pressure_sample(1, 95))), PressureDecision::default()); + assert_eq!(state.decide(4, Some(pressure_sample(2, 50))), PressureDecision::default()); + let invalid = PressureSample { + observed_turn: 4, + segment: super::super::memory_report::Segment { usage: 95, budget: 0 }, + }; + assert_eq!(state.decide(4, Some(invalid)), PressureDecision::default()); + assert_eq!(state.decide(5, Some(pressure_sample(5, 85))).max_evictions, 3, + "an unusable sample changed pressure state"); + + let mut disabled = PressureAdmission::new(PressureAdmissionConfig::default()).unwrap(); + assert_eq!(disabled.decide(1, Some(pressure_sample(1, 100))), PressureDecision::default()); + } + + #[test] + fn pressure_admission_freshness_is_conservative_across_turn_wrap() { + let mut state = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(state.decide(u64::MAX, Some(pressure_sample(0, 95))), PressureDecision::default(), + "a post-wrap sample was accepted before its turn"); + assert_eq!(state.decide(u64::MAX, Some(pressure_sample(u64::MAX, 95))).max_evictions, 3); + assert_eq!(state.decide(0, Some(pressure_sample(0, 95))).max_evictions, 3, + "turn wrap did not advance the sample and eviction budget"); + assert_eq!(state.decide(0, Some(pressure_sample(u64::MAX, 95))), PressureDecision::default(), + "a pre-wrap sample was accepted twice"); + assert_eq!(state.decide(2, Some(pressure_sample(0, 95))), PressureDecision::default(), + "a wrapped sample older than the configured age was accepted"); + + let mut recovery = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(recovery.decide(u64::MAX - 2, Some(pressure_sample(u64::MAX - 2, 95))).max_evictions, 3); + assert!(recovery.decide(u64::MAX - 1, Some(pressure_sample(u64::MAX - 1, 60))).allow_rehydrate); + recovery.note_rehydrate_result(u64::MAX - 1, false); + assert!(!recovery.decide(u64::MAX, Some(pressure_sample(u64::MAX, 60))).allow_rehydrate); + assert!(recovery.decide(0, Some(pressure_sample(0, 60))).allow_rehydrate, + "rehydration backoff did not expire across turn wrap"); + } + + #[test] + fn pressure_admission_backs_off_failures_and_resets_after_recovery() { + let mut state = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(state.decide(1, Some(pressure_sample(1, 95))).max_evictions, 3); + assert!(state.decide(2, Some(pressure_sample(2, 60))).allow_rehydrate); + state.note_rehydrate_result(2, false); + assert!(!state.decide(3, Some(pressure_sample(3, 60))).allow_rehydrate); + assert!(state.decide(4, Some(pressure_sample(4, 60))).allow_rehydrate); + state.note_rehydrate_result(4, false); + assert!(!state.decide(7, Some(pressure_sample(7, 60))).allow_rehydrate); + assert!(state.decide(8, Some(pressure_sample(8, 60))).allow_rehydrate); + state.note_rehydrate_result(8, true); + assert!(state.decide(9, Some(pressure_sample(9, 60))).allow_rehydrate); + state.note_rehydrate_result(9, false); + assert!(!state.decide(10, Some(pressure_sample(10, 60))).allow_rehydrate, + "a successful recovery did not reset the failure backoff"); + assert!(state.decide(11, Some(pressure_sample(11, 60))).allow_rehydrate); + state.note_rehydration_complete(); + assert_eq!(state.decide(12, Some(pressure_sample(12, 60))), PressureDecision::default()); + } + #[test] fn rebuild_recipe_gate_requires_exact_one() { assert!(recipe_gate_value(Some("1"))); From 4e0b3555026bed009772c85a2f42925283282428 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:22:50 -0800 Subject: [PATCH 228/265] D3D12.X: model serialized sparse upload commits Compose immutable upload plans with exact slot and ring reservations while keeping the protocol private and disconnected from live D3D12. Pre-submit failures restore work; accepted executions publish receipts or poison their generation. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 272 ++++++++++++++++++++++++++++ 1 file changed, 272 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index d941fe4e1d..8b0bd4ed6c 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -530,6 +530,26 @@ enum UploadPlanCommitError<E> { Commit(E), } +#[derive(Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum SparseUploadCommitError<C, E, S> { + Invalid(UploadPlanInvalid), + Reserve(UploadReservationError), + Copy(C), + StagingSize, + Prepare(E), + Signal(S), + Publish(UploadReservationError), +} + +/// Private owned stand-in for a future mapped staging allocation. Keeping the copied bytes here +/// makes it impossible for the record/execute callback to retain a borrowed title-memory view. +#[allow(dead_code)] +struct OwnedUploadStaging { + range: UploadRingRange, + bytes: Box<[u8]>, +} + /// Inert immutable work between an exact journal claim and a future short serialized commit. /// Dropping an uncommitted plan restores its claim. No command allocator, list or staging range is /// opened or reserved here; those remain responsibilities of the later commit-phase stage. A @@ -638,6 +658,43 @@ impl SparseUploadPlan { let claim = self.claim.take().expect("finished sparse upload plan"); Ok((result, claim.commit())) } + + /// Inert model of the future short serialized commit phase. Callers must hold the sparse + /// commit exclusion and make `copy` produce the bytes whose identities `observe` validated. + /// No live allocator, command list, queue, or staging allocation is touched by this model. + fn commit_reserved<C, E, S>( + mut self, + state_generation: u64, + mapping_epoch: u64, + observe: impl FnMut(usize) -> Option<UploadPageObservation>, + reservations: &UploadReservations, + slot: usize, + bytes: usize, + copy: impl FnOnce(UploadRingRange, &[PlannedUploadPage]) -> Result<Vec<u8>, C>, + prepare: impl FnOnce(&OwnedUploadStaging, &[PlannedUploadPage]) -> Result<(), E>, + execute: impl FnOnce(&OwnedUploadStaging, &[PlannedUploadPage]), + signal: impl FnOnce() -> Result<u64, S>, + ) -> Result<(UploadSubmissionReceipt, WorkClaimResolution), SparseUploadCommitError<C, E, S>> { + self.validate(state_generation, mapping_epoch, observe).map_err(SparseUploadCommitError::Invalid)?; + let reservation = reservations.reserve(slot, bytes).map_err(SparseUploadCommitError::Reserve)?; + let range = reservation.range(); + let copied = copy(range, &self.pages).map_err(SparseUploadCommitError::Copy)?; + if copied.len() != bytes { + return Err(SparseUploadCommitError::StagingSize); + } + let staging = OwnedUploadStaging { range, bytes: copied.into_boxed_slice() }; + prepare(&staging, &self.pages).map_err(SparseUploadCommitError::Prepare)?; + + // Arm fail-closed ownership before crossing the void execution boundary: execution may + // have accepted work even if the callback unwinds before it can report anything. + let accepted = AcceptedSparseUpload { + reservation: Some(reservation), + claim: self.claim.take(), + }; + execute(&staging, &self.pages); + let fence = signal().map_err(SparseUploadCommitError::Signal)?; + accepted.publish(fence).map_err(SparseUploadCommitError::Publish) + } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -900,6 +957,24 @@ impl UploadReservation { self.token.take(); Ok(()) } + + /// Publish after execute acceptance. Publication failure is fail-closed: the exact record and + /// its entire generation are poisoned instead of being cancelled by this guard's destructor. + fn publish_after_accept(mut self, fence: u64) -> Result<UploadSubmissionReceipt, UploadReservationError> { + let token = self.token.take().expect("finished upload reservation"); + let mut ledger = self.ledger.lock().unwrap(); + if fence == 0 { + let _ = ledger.poison(token); + return Err(UploadReservationError::State); + } + match ledger.submit(token, fence) { + Ok(()) => Ok(UploadSubmissionReceipt { token, fence }), + Err(error) => { + let _ = ledger.poison(token); + Err(error) + } + } + } } impl Drop for UploadReservation { @@ -910,6 +985,32 @@ impl Drop for UploadReservation { } } +/// Owns both exact ledgers once execute has accepted work. Dropping it is deliberately not a +/// rollback: an untracked execution must quarantine its slot/ring and must not be retried. +struct AcceptedSparseUpload { + reservation: Option<UploadReservation>, + claim: Option<SparseWorkClaim>, +} + +impl AcceptedSparseUpload { + fn publish(mut self, fence: u64) -> Result<(UploadSubmissionReceipt, WorkClaimResolution), UploadReservationError> { + let result = self.reservation.take().unwrap().publish_after_accept(fence); + let resolution = self.claim.take().unwrap().commit(); + result.map(|receipt| (receipt, resolution)) + } +} + +impl Drop for AcceptedSparseUpload { + fn drop(&mut self) { + if let Some(reservation) = self.reservation.take() { + let _ = reservation.poison(); + } + if let Some(claim) = self.claim.take() { + let _ = claim.commit(); + } + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) enum PreparationOutcome { Ready, @@ -3902,6 +4003,177 @@ mod tests { assert_eq!(claims.claim(2).unwrap().pages().len(), 2); } + #[test] + fn sparse_commit_protocol_orders_owned_copy_execute_publish_and_consume() { + let (claims, plan, observation) = one_page_upload_plan(); + let reservations = UploadReservations::new(31, 1, 256, 64); + let events = std::cell::RefCell::new(Vec::new()); + let result = plan.commit_reserved( + 31, + 7, + |_| { + events.borrow_mut().push("validate"); + Some(observation.clone()) + }, + &reservations, + 0, + 64, + |range, pages| { + assert!(reservations.0.lock().unwrap().slots[0].is_some(), "copy preceded reservation"); + assert_eq!(pages.len(), 1); + assert_eq!(range, UploadRingRange { start: 0, end: 64 }); + events.borrow_mut().push("copy"); + Ok::<_, ()>(vec![0xA5; 64]) + }, + |staging, pages| { + assert_eq!(staging.range, UploadRingRange { start: 0, end: 64 }); + assert_eq!(&*staging.bytes, &[0xA5; 64]); + assert_eq!(pages[0].page, 0x2_1000); + events.borrow_mut().push("prepare"); + Ok::<_, ()>(()) + }, + |staging, _| { + assert_eq!(&*staging.bytes, &[0xA5; 64]); + events.borrow_mut().push("execute"); + }, + || { + events.borrow_mut().push("signal"); + Ok::<_, ()>(9) + }, + ); + let (receipt, resolution) = result.unwrap(); + assert_eq!(&*events.borrow(), &["validate", "copy", "prepare", "execute", "signal"]); + assert_eq!(resolution, WorkClaimResolution::Committed); + assert!(claims.claim(1).is_none(), "accepted submission restored its work"); + assert_eq!(reservations.complete(receipt), Ok(64)); + } + + #[test] + fn sparse_commit_protocol_restores_every_pre_execute_failure() { + let reservations = UploadReservations::new(31, 1, 256, 64); + let (claims, plan, observation) = one_page_upload_plan(); + let result = plan.commit_reserved( + 32, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, || Ok::<_, ()>(1), + ); + assert_eq!(result, Err(SparseUploadCommitError::Invalid(UploadPlanInvalid::StateGeneration))); + assert!(claims.claim(1).is_some(), "validation failure consumed work"); + + let occupied = reservations.reserve(0, 64).unwrap(); + let (claims, plan, observation) = one_page_upload_plan(); + let result = plan.commit_reserved( + 31, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, || Ok::<_, ()>(1), + ); + assert_eq!(result, Err(SparseUploadCommitError::Reserve(UploadReservationError::SlotBusy))); + assert!(claims.claim(1).is_some(), "reservation refusal consumed work"); + drop(occupied); + + for failure in ["copy", "size", "prepare"] { + let reservations = UploadReservations::new(31, 1, 256, 64); + let (claims, plan, observation) = one_page_upload_plan(); + let result = plan.commit_reserved( + 31, + 7, + |_| Some(observation.clone()), + &reservations, + 0, + 64, + |_, _| match failure { + "copy" => Err("copy"), + "size" => Ok(vec![0; 63]), + _ => Ok(vec![0; 64]), + }, + |_, _| if failure == "prepare" { Err("prepare") } else { Ok(()) }, + |_, _| {}, + || Ok::<_, &'static str>(1), + ); + match failure { + "copy" => assert_eq!(result, Err(SparseUploadCommitError::Copy("copy"))), + "size" => assert_eq!(result, Err(SparseUploadCommitError::StagingSize)), + _ => assert_eq!(result, Err(SparseUploadCommitError::Prepare("prepare"))), + } + assert!(claims.claim(1).is_some(), "{failure} failure consumed work"); + let ledger = reservations.0.lock().unwrap(); + assert!(!ledger.poisoned); + assert!(ledger.slots[0].is_none(), "{failure} failure retained its slot"); + } + } + + #[test] + fn sparse_commit_protocol_unwind_changes_from_rollback_to_poison_after_accept() { + let reservations = UploadReservations::new(31, 1, 256, 64); + let (claims, plan, observation) = one_page_upload_plan(); + let before = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = plan.commit_reserved( + 31, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| -> Result<Vec<u8>, ()> { panic!("copy panicked") }, + |_, _| Ok::<_, ()>(()), |_, _| {}, || Ok::<_, ()>(1), + ); + })); + assert!(before.is_err()); + assert!(claims.claim(1).is_some(), "pre-execute unwind consumed work"); + assert!(!reservations.0.lock().unwrap().poisoned); + + let reservations = UploadReservations::new(31, 1, 256, 64); + let (claims, plan, observation) = one_page_upload_plan(); + let submitted = std::cell::Cell::new(false); + let after = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = plan.commit_reserved( + 31, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), + |_, _| { + submitted.set(true); // Model the void ExecuteCommandLists side effect. + panic!("execute panicked after submit") + }, + || Ok::<_, ()>(1), + ); + })); + assert!(after.is_err()); + assert!(submitted.get()); + assert!(claims.claim(1).is_none(), "accepted execution was made retryable"); + let ledger = reservations.0.lock().unwrap(); + assert!(ledger.poisoned); + assert!(matches!(ledger.records[&1].state, UploadReservationState::Poisoned)); + } + + #[test] + fn sparse_commit_protocol_signal_failure_poison_and_receipts_retire_in_order() { + let reservations = UploadReservations::new(31, 2, 256, 64); + let (failed_claims, failed, observation) = one_page_upload_plan(); + let result = failed.commit_reserved( + 31, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, + || Err::<u64, _>("signal"), + ); + assert_eq!(result, Err(SparseUploadCommitError::Signal("signal"))); + assert!(failed_claims.claim(1).is_none()); + assert!(reservations.0.lock().unwrap().poisoned); + + let reservations = UploadReservations::new(31, 1, 256, 64); + let (failed_claims, failed, observation) = one_page_upload_plan(); + let result = failed.commit_reserved( + 31, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, || Ok::<_, ()>(0), + ); + assert_eq!(result, Err(SparseUploadCommitError::Publish(UploadReservationError::State))); + assert!(failed_claims.claim(1).is_none(), "accepted work was restored after failed publication"); + assert!(reservations.0.lock().unwrap().poisoned); + + let reservations = UploadReservations::new(31, 2, 256, 64); + let mut receipts = Vec::new(); + for (slot, fence) in [(0, 3), (1, 4)] { + let (_, plan, observation) = one_page_upload_plan(); + receipts.push(plan.commit_reserved( + 31, 7, |_| Some(observation.clone()), &reservations, slot, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, + || Ok::<_, ()>(fence), + ).unwrap().0); + } + assert_eq!(reservations.complete(receipts[1]), Ok(0), "newer receipt reclaimed older work"); + assert_eq!(reservations.complete(receipts[0]), Ok(128)); + } + #[test] fn upload_reservations_reclaim_only_a_contiguous_retired_prefix() { let reservations = UploadReservations::new(41, 2, 256, 64); From 7d0487c4cb7242de549dadc4134d3dcf2b8b0f76 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:30:23 -0800 Subject: [PATCH 229/265] D3D12.X: model sparse claim receipt frontier Keep planner-owned batches visible to foreground queues until an exact receipt or obsolete resolution closes their epoch. Lease rotation makes pre-accept takeover safe while accepted work remains wait-only. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 284 ++++++++++++++++++++++++++++ 1 file changed, 284 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 8b0bd4ed6c..b231d7c793 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -484,6 +484,194 @@ impl Drop for SparseWorkClaim { } } +/// Identity of one future sparse batch while it crosses planning and queue acceptance. `lease` +/// changes on takeover, so an old owner cannot publish or discard the new owner's batch. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct ClaimFrontierToken { + state_generation: u64, + epoch: u64, + lease: u64, + owner: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ClaimFrontierState { + Pending, + Accepted, + Receipted(u64), + Obsolete, +} + +#[allow(dead_code)] +struct ClaimFrontierRecord { + lease: u64, + owner: u64, + state: ClaimFrontierState, + prefix_fence: Option<u64>, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum ClaimFrontierAction { + Ready { through: u64, required_fence: Option<u64> }, + Progress(ClaimFrontierToken), + TakeOver(ClaimFrontierToken), + WaitForReceipt(ClaimFrontierToken), +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum ClaimFrontierError { + StaleGeneration, + UnknownEpoch, + StaleToken, + WrongState, + Fence, + Exhausted, +} + +/// Inert coordination model for future asynchronous sparse planning. Every observed epoch remains +/// visible until it is receipted or explicitly consumed as obsolete; a foreground queue therefore +/// cannot mistake work owned by another planner for an empty journal. There are no callers yet. +#[allow(dead_code)] +struct ClaimFrontier { + state_generation: u64, + next_epoch: u64, + next_lease: u64, + retired_through: u64, + records: BTreeMap<u64, ClaimFrontierRecord>, +} + +#[allow(dead_code)] +impl ClaimFrontier { + fn new(state_generation: u64) -> Self { + Self { + state_generation, + next_epoch: 0, + next_lease: 0, + retired_through: 0, + records: BTreeMap::new(), + } + } + + fn claim(&mut self, owner: u64) -> Result<ClaimFrontierToken, ClaimFrontierError> { + let epoch = self.next_epoch.checked_add(1).ok_or(ClaimFrontierError::Exhausted)?; + let lease = self.next_lease.checked_add(1).ok_or(ClaimFrontierError::Exhausted)?; + let token = ClaimFrontierToken { state_generation: self.state_generation, epoch, lease, owner }; + self.records.insert(epoch, ClaimFrontierRecord { + lease, + owner, + state: ClaimFrontierState::Pending, + prefix_fence: None, + }); + self.next_epoch = epoch; + self.next_lease = lease; + Ok(token) + } + + fn observe( + &self, state_generation: u64, through: u64, requester: u64, + ) -> Result<ClaimFrontierAction, ClaimFrontierError> { + if state_generation != self.state_generation { + return Err(ClaimFrontierError::StaleGeneration); + } + if through > self.next_epoch { + return Err(ClaimFrontierError::UnknownEpoch); + } + if through <= self.retired_through { + let required_fence = (through != 0) + .then(|| self.records.get(&through).and_then(|record| record.prefix_fence)) + .flatten(); + return Ok(ClaimFrontierAction::Ready { through, required_fence }); + } + let epoch = self.retired_through.checked_add(1).ok_or(ClaimFrontierError::Exhausted)?; + let record = self.records.get(&epoch).ok_or(ClaimFrontierError::UnknownEpoch)?; + let token = ClaimFrontierToken { + state_generation: self.state_generation, + epoch, + lease: record.lease, + owner: record.owner, + }; + Ok(match record.state { + ClaimFrontierState::Pending if record.owner == requester => ClaimFrontierAction::Progress(token), + ClaimFrontierState::Pending => ClaimFrontierAction::TakeOver(token), + ClaimFrontierState::Accepted => ClaimFrontierAction::WaitForReceipt(token), + ClaimFrontierState::Receipted(_) | ClaimFrontierState::Obsolete => unreachable!("terminal frontier did not advance"), + }) + } + + fn take_over( + &mut self, token: ClaimFrontierToken, owner: u64, + ) -> Result<ClaimFrontierToken, ClaimFrontierError> { + self.validate(token, ClaimFrontierState::Pending)?; + let lease = self.next_lease.checked_add(1).ok_or(ClaimFrontierError::Exhausted)?; + let record = self.records.get_mut(&token.epoch).unwrap(); + record.lease = lease; + record.owner = owner; + self.next_lease = lease; + Ok(ClaimFrontierToken { state_generation: self.state_generation, epoch: token.epoch, lease, owner }) + } + + fn accept(&mut self, token: ClaimFrontierToken) -> Result<(), ClaimFrontierError> { + self.validate(token, ClaimFrontierState::Pending)?; + self.records.get_mut(&token.epoch).unwrap().state = ClaimFrontierState::Accepted; + Ok(()) + } + + fn receipt(&mut self, token: ClaimFrontierToken, fence: u64) -> Result<(), ClaimFrontierError> { + self.validate(token, ClaimFrontierState::Accepted)?; + if fence == 0 { + return Err(ClaimFrontierError::Fence); + } + self.records.get_mut(&token.epoch).unwrap().state = ClaimFrontierState::Receipted(fence); + self.advance(); + Ok(()) + } + + fn consume_obsolete(&mut self, token: ClaimFrontierToken) -> Result<(), ClaimFrontierError> { + self.validate(token, ClaimFrontierState::Pending)?; + self.records.get_mut(&token.epoch).unwrap().state = ClaimFrontierState::Obsolete; + self.advance(); + Ok(()) + } + + fn validate( + &self, token: ClaimFrontierToken, expected: ClaimFrontierState, + ) -> Result<(), ClaimFrontierError> { + if token.state_generation != self.state_generation { + return Err(ClaimFrontierError::StaleGeneration); + } + let record = self.records.get(&token.epoch).ok_or(ClaimFrontierError::StaleToken)?; + if record.lease != token.lease || record.owner != token.owner { + return Err(ClaimFrontierError::StaleToken); + } + if record.state != expected { + return Err(ClaimFrontierError::WrongState); + } + Ok(()) + } + + fn advance(&mut self) { + let mut prefix_fence = if self.retired_through == 0 { + 0 + } else { + self.records[&self.retired_through].prefix_fence.unwrap_or(0) + }; + loop { + let Some(next) = self.retired_through.checked_add(1) else { return }; + let Some(record) = self.records.get_mut(&next) else { return }; + match record.state { + ClaimFrontierState::Receipted(fence) => prefix_fence = prefix_fence.max(fence), + ClaimFrontierState::Obsolete => {} + ClaimFrontierState::Pending | ClaimFrontierState::Accepted => return, + } + record.prefix_fence = (prefix_fence != 0).then_some(prefix_fence); + self.retired_through = next; + } + } +} + /// Point-in-time identities needed to prove that planning and a later serialized upload commit /// still refer to the same sparse page. `source` names the observed CPU page by chunk hash rather /// than retaining a raw pointer across the unlocked interval. Title writes are outside sparse @@ -3858,6 +4046,102 @@ mod tests { assert!(current.claim(1).is_none(), "stale producers polluted the current journal"); } + #[test] + fn foreground_queue_cannot_pass_or_steal_an_unreceipted_claim() { + let mut frontier = ClaimFrontier::new(23); + let planner = frontier.claim(100).unwrap(); + assert_eq!( + frontier.observe(23, planner.epoch, 200), + Ok(ClaimFrontierAction::TakeOver(planner)), + "another queue mistook pending planner work for an empty frontier", + ); + + let helper = frontier.take_over(planner, 200).unwrap(); + assert_eq!(frontier.accept(planner), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.receipt(planner, 7), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.consume_obsolete(planner), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.take_over(planner, 300), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.observe(23, helper.epoch, 200), Ok(ClaimFrontierAction::Progress(helper))); + + frontier.accept(helper).unwrap(); + assert_eq!(frontier.take_over(helper, 100), Err(ClaimFrontierError::WrongState)); + assert_eq!(frontier.consume_obsolete(helper), Err(ClaimFrontierError::WrongState)); + assert_eq!( + frontier.observe(23, helper.epoch, 100), + Ok(ClaimFrontierAction::WaitForReceipt(helper)), + "accepted GPU work was exposed for retry", + ); + frontier.receipt(helper, 7).unwrap(); + assert_eq!( + frontier.observe(23, helper.epoch, 100), + Ok(ClaimFrontierAction::Ready { through: helper.epoch, required_fence: Some(7) }), + ); + } + + #[test] + fn receipts_and_obsolete_holes_advance_only_a_contiguous_frontier() { + let mut frontier = ClaimFrontier::new(29); + let first = frontier.claim(1).unwrap(); + let second = frontier.claim(2).unwrap(); + let hole = frontier.claim(3).unwrap(); + frontier.accept(first).unwrap(); + frontier.accept(second).unwrap(); + frontier.receipt(second, 11).unwrap(); + frontier.consume_obsolete(hole).unwrap(); + + assert_eq!(frontier.retired_through, 0, "out-of-order terminal work crossed the first claim"); + assert_eq!( + frontier.observe(29, hole.epoch, 9), + Ok(ClaimFrontierAction::WaitForReceipt(first)), + ); + frontier.receipt(first, 8).unwrap(); + assert_eq!(frontier.retired_through, hole.epoch, "an obsolete hole left the frontier stuck"); + assert_eq!( + frontier.observe(29, hole.epoch, 9), + Ok(ClaimFrontierAction::Ready { through: hole.epoch, required_fence: Some(11) }), + ); + assert_eq!( + frontier.observe(29, first.epoch, 9), + Ok(ClaimFrontierAction::Ready { through: first.epoch, required_fence: Some(8) }), + "an older observer unnecessarily inherited a newer fence", + ); + } + + #[test] + fn frontier_rejects_wrong_generations_unknown_epochs_and_invalid_receipts() { + let mut frontier = ClaimFrontier::new(31); + let token = frontier.claim(4).unwrap(); + assert_eq!(frontier.observe(30, token.epoch, 4), Err(ClaimFrontierError::StaleGeneration)); + assert_eq!(frontier.observe(31, token.epoch + 1, 4), Err(ClaimFrontierError::UnknownEpoch)); + assert_eq!(frontier.receipt(token, 1), Err(ClaimFrontierError::WrongState)); + frontier.accept(token).unwrap(); + assert_eq!(frontier.receipt(token, 0), Err(ClaimFrontierError::Fence)); + assert_eq!(frontier.observe(31, 0, 4), Ok(ClaimFrontierAction::Ready { through: 0, required_fence: None })); + + let stale_generation = ClaimFrontierToken { state_generation: 32, ..token }; + assert_eq!(frontier.receipt(stale_generation, 1), Err(ClaimFrontierError::StaleGeneration)); + } + + #[test] + fn frontier_epoch_and_lease_overflow_fail_without_partial_publication() { + let mut epoch = ClaimFrontier::new(37); + epoch.next_epoch = u64::MAX; + assert_eq!(epoch.claim(1), Err(ClaimFrontierError::Exhausted)); + assert!(epoch.records.is_empty()); + + let mut lease = ClaimFrontier::new(41); + lease.next_lease = u64::MAX; + assert_eq!(lease.claim(1), Err(ClaimFrontierError::Exhausted)); + assert_eq!(lease.next_epoch, 0); + assert!(lease.records.is_empty()); + + let mut takeover = ClaimFrontier::new(43); + let token = takeover.claim(1).unwrap(); + takeover.next_lease = u64::MAX; + assert_eq!(takeover.take_over(token, 2), Err(ClaimFrontierError::Exhausted)); + assert_eq!(takeover.observe(43, token.epoch, 1), Ok(ClaimFrontierAction::Progress(token))); + } + fn upload_observation(page: usize, pool: (u32, u32), source_word: u64) -> UploadPageObservation { let mut source = ZERO_HASHES; source[1] = source_word; From b628cfb4df7d93bc52a557c98b9aa7dfe26baf86 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:30:46 -0800 Subject: [PATCH 230/265] D3D12.X: extract exact synchronous dirty upload batches Keep each upload slot, ring rollback point, and unpublished hash plan in one prepared batch. Pure copy planning now makes the existing window and ring split boundaries explicit without changing submission or wait behavior. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 230 +++++++++++++++++++++------- 1 file changed, 177 insertions(+), 53 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b231d7c793..80b87b7709 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1386,6 +1386,39 @@ struct HashUpdate { const MAX_BATCH_HASH_UPDATES: usize = STAGING / CHUNK; +/// One synchronously-recorded dirty upload batch. The slot, ring rollback point, and unpublished +/// hash plan move together so a failed submission cannot publish bytes that have no fence receipt. +struct PreparedDirtyBatch { + slot: usize, + ring_start: u64, + updates: Vec<HashUpdate>, +} + +impl PreparedDirtyBatch { + fn new(slot: usize, ring_start: u64) -> Self { + Self { slot, ring_start, updates: Vec::new() } + } + + fn reopen(mut self, slot: usize, ring_start: u64) -> Self { + debug_assert!(self.updates.is_empty()); + self.slot = slot; + self.ring_start = ring_start; + self + } + + fn hash_plan_would_overflow(&self, bytes: usize) -> bool { + batch_hash_plan_would_overflow(self.updates.len(), bytes) + } + + fn append_hashes(&mut self, at: usize, bytes: &[u8]) { + append_hash_updates(at, bytes, &mut self.updates); + } + + fn clear_after_submit(&mut self) { + self.updates.clear(); + } +} + fn batch_hash_plan_would_overflow(current: usize, bytes: usize) -> bool { bytes / CHUNK > MAX_BATCH_HASH_UPDATES.saturating_sub(current) } @@ -1495,6 +1528,35 @@ fn plan_ring_chunk(ring_write: u64, want: usize, cap: usize) -> (u64, usize) { (aligned, chunk) } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct PreparedDirtyCopy { + ring_start: u64, + staging_offset: usize, + window_offset: usize, + bytes: usize, +} + +/// Bound one dirty copy to both its sparse window and its contiguous staging-ring allocation. +/// Keeping this arithmetic pure lets planning and recording use exactly the same split points. +fn prepare_dirty_copy( + at: usize, + remaining: usize, + window_base: usize, + window_size: usize, + ring_write: u64, + staging_cap: usize, +) -> PreparedDirtyCopy { + debug_assert!(at >= window_base && at < window_base + window_size); + let to_window_end = window_base + window_size - at; + let (ring_start, bytes) = plan_ring_chunk(ring_write, remaining.min(to_window_end), staging_cap); + PreparedDirtyCopy { + ring_start, + staging_offset: ring_start as usize % staging_cap, + window_offset: at - window_base, + bytes, + } +} + // D3D12 objects are free-threaded; staging pointers and event handle are only used under STATE lock unsafe impl Send for State {} @@ -2319,6 +2381,30 @@ impl State { publish_hash_updates(&mut self.mapped, updates); } + /// Submit one exact dirty batch. Until submission succeeds its ring bytes and hash plan are + /// provisional; a close/cast failure rolls the ring cursor back to this batch's start. + unsafe fn submit_dirty_batch( + &mut self, + mut batch: PreparedDirtyBatch, + reclaim: bool, + ) -> Result<PreparedDirtyBatch, PreparationOutcome> { + match self.submit_slot(batch.slot) { + SubmitResult::Submitted => { + self.publish_hashes(&batch.updates); + batch.clear_after_submit(); + if reclaim { + self.reclaim_ring(); + } + Ok(batch) + } + SubmitResult::NotSubmitted => { + self.ring_write = batch.ring_start; + Err(PreparationOutcome::RetryRequired) + } + SubmitResult::Unordered => Err(PreparationOutcome::ExecutedUntracked), + } + } + /// Copy `ranges` (address, bytes) from sparse VRAM back into the CPU view and refresh /// `sent` hashes. Caller has already ordered `self.queue` after any GPU writes if needed. unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)]) { @@ -2467,9 +2553,8 @@ impl State { let Some(p) = self.staging_ptr() else { return UploadStep::Done(PreparationOutcome::RetryRequired); }; - let mut open_slot: Option<usize> = None; - let mut batch_start = self.ring_write; - let mut batch_updates = Vec::new(); + let mut batch: Option<PreparedDirtyBatch> = None; + let mut recycled_batch: Option<PreparedDirtyBatch> = None; let mut last_wi: Option<usize> = None; for &(a, n) in runs { let mut done = 0usize; @@ -2483,34 +2568,32 @@ impl State { i } None => { - if open_slot.is_some() { - self.ring_write = batch_start; + if let Some(batch) = batch { + self.ring_write = batch.ring_start; } return UploadStep::Done(PreparationOutcome::RetryRequired); } }, }; let b = self.windows[wi].0; - let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; - let (aligned, chunk) = plan_ring_chunk(self.ring_write, (n - done).min(to_win_end), STAGING); - if (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { + let copy = prepare_dirty_copy( + cur, + n - done, + b, + crate::gpu::uma::WINDOW, + self.ring_write, + STAGING, + ); + if (copy.ring_start + copy.bytes as u64).saturating_sub(self.ring_free) > STAGING as u64 { self.reclaim_ring(); - if (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { - if let Some(slot_idx) = open_slot.take() { - match self.submit_slot(slot_idx) { - SubmitResult::Submitted => { - self.publish_hashes(&batch_updates); - batch_updates.clear(); - } - SubmitResult::NotSubmitted => { - self.ring_write = batch_start; - return UploadStep::Done(PreparationOutcome::RetryRequired); - } - SubmitResult::Unordered => return UploadStep::Done(PreparationOutcome::ExecutedUntracked), + if (copy.ring_start + copy.bytes as u64).saturating_sub(self.ring_free) > STAGING as u64 { + if let Some(ready) = batch.take() { + match self.submit_dirty_batch(ready, true) { + Ok(recycled) => recycled_batch = Some(recycled), + Err(outcome) => return UploadStep::Done(outcome), } - self.reclaim_ring(); } - while (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { + while (copy.ring_start + copy.bytes as u64).saturating_sub(self.ring_free) > STAGING as u64 { let Some(&(fv, _)) = self.inflight.front() else { crate::xlog_warn!("sparse: the staging ring is full without a retirement fence; the unsubmitted CPU writes will be retried"); return UploadStep::Done(PreparationOutcome::RetryRequired); @@ -2527,51 +2610,47 @@ impl State { } } } - if open_slot.is_some() && batch_hash_plan_would_overflow(batch_updates.len(), chunk) { - let slot_idx = open_slot.take().unwrap(); - match self.submit_slot(slot_idx) { - SubmitResult::Submitted => { - self.publish_hashes(&batch_updates); - batch_updates.clear(); - self.reclaim_ring(); - } - SubmitResult::NotSubmitted => { - self.ring_write = batch_start; - return UploadStep::Done(PreparationOutcome::RetryRequired); - } - SubmitResult::Unordered => return UploadStep::Done(PreparationOutcome::ExecutedUntracked), + if batch.as_ref().is_some_and(|batch| batch.hash_plan_would_overflow(copy.bytes)) { + match self.submit_dirty_batch(batch.take().unwrap(), true) { + Ok(recycled) => recycled_batch = Some(recycled), + Err(outcome) => return UploadStep::Done(outcome), } } - let slot_idx = match open_slot { - Some(idx) => idx, + let slot_idx = match batch.as_ref() { + Some(batch) => batch.slot, None => { let idx = match self.begin_slot() { BeginSlot::Ready(index) => index, BeginSlot::Wait(ticket) => return UploadStep::Wait(ticket), BeginSlot::RetryRequired => return UploadStep::Done(PreparationOutcome::RetryRequired), }; - batch_start = self.ring_write; - open_slot = Some(idx); + batch = Some(match recycled_batch.take() { + Some(recycled) => recycled.reopen(idx, self.ring_write), + None => PreparedDirtyBatch::new(idx, self.ring_write), + }); idx } }; - let dst_off = (aligned as usize) % STAGING; - std::ptr::copy_nonoverlapping(cur as *const u8, p.add(dst_off), chunk); - append_hash_updates(cur, std::slice::from_raw_parts(p.add(dst_off), chunk), &mut batch_updates); + std::ptr::copy_nonoverlapping(cur as *const u8, p.add(copy.staging_offset), copy.bytes); + batch.as_mut().unwrap().append_hashes( + cur, + std::slice::from_raw_parts(p.add(copy.staging_offset), copy.bytes), + ); let staging_res = &self.staging.as_ref().unwrap().0; - self.slots[slot_idx].list.CopyBufferRegion(&self.windows[wi].1, (cur - b) as u64, staging_res, dst_off as u64, chunk as u64); - self.ring_write = aligned + chunk as u64; - done += chunk; + self.slots[slot_idx].list.CopyBufferRegion( + &self.windows[wi].1, + copy.window_offset as u64, + staging_res, + copy.staging_offset as u64, + copy.bytes as u64, + ); + self.ring_write = copy.ring_start + copy.bytes as u64; + done += copy.bytes; } } - if let Some(slot_idx) = open_slot { - match self.submit_slot(slot_idx) { - SubmitResult::Submitted => self.publish_hashes(&batch_updates), - SubmitResult::NotSubmitted => { - self.ring_write = batch_start; - return UploadStep::Done(PreparationOutcome::RetryRequired); - } - SubmitResult::Unordered => return UploadStep::Done(PreparationOutcome::ExecutedUntracked), + if let Some(batch) = batch { + if let Err(outcome) = self.submit_dirty_batch(batch, false) { + return UploadStep::Done(outcome); } } UploadStep::Done(PreparationOutcome::Ready) @@ -4893,6 +4972,51 @@ mod tests { assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES / 2 + 1, STAGING / 2)); } + #[test] + fn prepared_dirty_batch_keeps_exact_hash_plan_and_rollback_point() { + let mut batch = PreparedDirtyBatch::new(3, 0x12_3400); + let bytes = [0xA5; 2 * CHUNK]; + batch.append_hashes(0x20_0000, &bytes); + assert_eq!(batch.slot, 3); + assert_eq!(batch.ring_start, 0x12_3400); + assert_eq!(batch.updates.len(), 2); + assert_eq!(batch.updates[0], HashUpdate { at: 0x20_0000, hash: chunk_hash(&bytes[..CHUNK]) }); + assert_eq!(batch.updates[1], HashUpdate { at: 0x20_0000 + CHUNK, hash: chunk_hash(&bytes[CHUNK..]) }); + assert!(!batch.hash_plan_would_overflow(CHUNK)); + + let storage = batch.updates.as_ptr(); + let capacity = batch.updates.capacity(); + for index in 0..3 { + batch.clear_after_submit(); + batch = batch.reopen(4 + index, 0x20_0000 + index as u64 * PAGE as u64); + batch.append_hashes(0x30_0000, &bytes); + assert_eq!(batch.updates.as_ptr(), storage, "batch {index} replaced its hash-plan allocation"); + assert_eq!(batch.updates.capacity(), capacity); + } + } + + #[test] + fn prepared_dirty_copy_splits_at_windows_and_ring_wrap() { + let window = 4 * PAGE; + let base = 0x10_0000; + let first = prepare_dirty_copy(base + window - CHUNK, 2 * CHUNK, base, window, 0, 8 * PAGE); + assert_eq!(first, PreparedDirtyCopy { + ring_start: 0, + staging_offset: 0, + window_offset: window - CHUNK, + bytes: CHUNK, + }); + let second = prepare_dirty_copy(base + window, CHUNK, base + window, window, CHUNK as u64, 8 * PAGE); + assert_eq!(second.window_offset, 0); + assert_eq!(second.bytes, CHUNK); + + let cap = 8 * PAGE; + let wrapped = prepare_dirty_copy(base, PAGE, base, window, (cap - 512) as u64, cap); + assert_eq!(wrapped.ring_start, cap as u64); + assert_eq!(wrapped.staging_offset, 0); + assert_eq!(wrapped.bytes, PAGE); + } + /// Ring-buffer planner keeps every chunk contiguous, 64-byte aligned, <= cap/2, and splits /// cleanly across the end of the ring buffer without wrapping mid-copy. #[test] From 54039442b4a9c5044f1fca1f14997224b6bb11d6 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:38:38 -0800 Subject: [PATCH 231/265] D3D12.X: couple sparse batch ownership Keep work claims and their visibility frontier under one atomic ledger. Lease rotation revokes stale planners without restoring their work, while unsealed reasons and accepted failures remain visible or fail closed. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 399 ++++++++++++++++++++++++++++ 1 file changed, 399 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 80b87b7709..16d2d94507 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -672,6 +672,290 @@ impl ClaimFrontier { } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum SparseBatchError { + StaleGeneration, + Poisoned, + Unsealed, + Exhausted, + Corrupt, + Frontier(ClaimFrontierError), +} + +/// One atomic owner for work claims and their visibility frontier. This remains inert: no live +/// sparse state, command list, queue or fence uses it yet. Keeping both ledgers under one mutex is +/// what makes a lease rotation revoke the old planner without restoring or duplicating its work. +#[allow(dead_code)] +struct SparseBatchLedger { + work: WorkClaimLedger, + frontier: ClaimFrontier, + bindings: BTreeMap<u64, WorkClaimToken>, + poisoned: bool, +} + +#[allow(dead_code)] +impl SparseBatchLedger { + fn new(state_generation: u64) -> Self { + Self { + work: WorkClaimLedger::new(state_generation), + frontier: ClaimFrontier::new(state_generation), + bindings: BTreeMap::new(), + poisoned: false, + } + } + + fn check(&self, state_generation: u64) -> Result<(), SparseBatchError> { + if state_generation != self.work.state_generation { + return Err(SparseBatchError::StaleGeneration); + } + if self.poisoned { + return Err(SparseBatchError::Poisoned); + } + Ok(()) + } + + fn seal( + &mut self, state_generation: u64, owner: u64, limit: usize, + ) -> Result<Option<(ClaimFrontierToken, Vec<(usize, WorkReasons)>)>, SparseBatchError> { + self.check(state_generation)?; + if self.work.next_serial == u64::MAX { + return Err(SparseBatchError::Exhausted); + } + let Some(claimed) = self.work.claim(limit) else { return Ok(None) }; + let token = match self.frontier.claim(owner) { + Ok(token) => token, + Err(error) => { + let _ = self.work.restore(claimed.token); + return Err(SparseBatchError::Frontier(error)); + } + }; + self.bindings.insert(token.epoch, claimed.token); + Ok(Some((token, claimed.pages))) + } + + fn pages(&self, token: ClaimFrontierToken) -> Result<Vec<(usize, WorkReasons)>, SparseBatchError> { + self.check(token.state_generation)?; + self.frontier.validate(token, ClaimFrontierState::Pending).map_err(SparseBatchError::Frontier)?; + let work = self.bindings.get(&token.epoch).ok_or(SparseBatchError::Corrupt)?; + self.work.claims.get(&work.serial).cloned().ok_or(SparseBatchError::Corrupt) + } + + fn take_over( + &mut self, token: ClaimFrontierToken, owner: u64, + ) -> Result<(ClaimFrontierToken, Vec<(usize, WorkReasons)>), SparseBatchError> { + let pages = self.pages(token)?; + let token = self.frontier.take_over(token, owner).map_err(SparseBatchError::Frontier)?; + Ok((token, pages)) + } + + fn observe( + &self, state_generation: u64, through: u64, requester: u64, + ) -> Result<ClaimFrontierAction, SparseBatchError> { + self.check(state_generation)?; + if !self.work.available.is_empty() { + return Err(SparseBatchError::Unsealed); + } + self.frontier.observe(state_generation, through, requester).map_err(SparseBatchError::Frontier) + } + + fn through(&self, state_generation: u64) -> Result<u64, SparseBatchError> { + self.check(state_generation)?; + if !self.work.available.is_empty() { + return Err(SparseBatchError::Unsealed); + } + Ok(self.frontier.next_epoch) + } + + fn accept(&mut self, token: ClaimFrontierToken) -> Result<(), SparseBatchError> { + self.check(token.state_generation)?; + self.binding(token, ClaimFrontierState::Pending)?; + self.frontier.accept(token).map_err(SparseBatchError::Frontier) + } + + fn receipt(&mut self, token: ClaimFrontierToken, fence: u64) -> Result<(), SparseBatchError> { + self.check(token.state_generation)?; + if fence == 0 { + return Err(SparseBatchError::Frontier(ClaimFrontierError::Fence)); + } + let work = self.binding(token, ClaimFrontierState::Accepted)?; + if self.work.commit(work) != WorkClaimResolution::Committed { + self.poisoned = true; + return Err(SparseBatchError::Corrupt); + } + if let Err(error) = self.frontier.receipt(token, fence) { + self.poisoned = true; + return Err(SparseBatchError::Frontier(error)); + } + self.bindings.remove(&token.epoch); + Ok(()) + } + + fn obsolete(&mut self, token: ClaimFrontierToken) -> Result<(), SparseBatchError> { + self.check(token.state_generation)?; + let work = self.binding(token, ClaimFrontierState::Pending)?; + if self.work.commit(work) != WorkClaimResolution::Committed { + self.poisoned = true; + return Err(SparseBatchError::Corrupt); + } + if let Err(error) = self.frontier.consume_obsolete(token) { + self.poisoned = true; + return Err(SparseBatchError::Frontier(error)); + } + self.bindings.remove(&token.epoch); + Ok(()) + } + + fn poison(&mut self, token: ClaimFrontierToken) -> Result<(), SparseBatchError> { + self.check(token.state_generation)?; + let work = self.binding(token, ClaimFrontierState::Accepted)?; + if self.work.commit(work) != WorkClaimResolution::Committed { + return Err(SparseBatchError::Corrupt); + } + self.bindings.remove(&token.epoch); + self.poisoned = true; + Ok(()) + } + + fn binding( + &self, token: ClaimFrontierToken, state: ClaimFrontierState, + ) -> Result<WorkClaimToken, SparseBatchError> { + self.frontier.validate(token, state).map_err(SparseBatchError::Frontier)?; + let work = *self.bindings.get(&token.epoch).ok_or(SparseBatchError::Corrupt)?; + self.work.claims.contains_key(&work.serial).then_some(work).ok_or(SparseBatchError::Corrupt) + } + + fn replace_generation(&mut self, current: u64, replacement: u64) -> Result<(), SparseBatchError> { + if current != self.work.state_generation { + return Err(SparseBatchError::StaleGeneration); + } + // Generations are identities, not labels: reuse could resurrect an old epoch/lease tuple. + if replacement <= current { + return Err(SparseBatchError::StaleGeneration); + } + self.work.replace_generation(replacement); + self.frontier = ClaimFrontier::new(replacement); + self.bindings.clear(); + self.poisoned = false; + Ok(()) + } +} + +#[derive(Clone)] +#[allow(dead_code)] +struct SparseBatches { + ledger: Arc<Mutex<SparseBatchLedger>>, + state_generation: u64, +} + +#[allow(dead_code)] +impl SparseBatches { + fn new(state_generation: u64) -> Self { + Self { ledger: Arc::new(Mutex::new(SparseBatchLedger::new(state_generation))), state_generation } + } + + fn add_pages(&self, pages: impl IntoIterator<Item = usize>, reason: WorkReasons) -> bool { + // Iterator code is caller code: finish it before taking the non-reentrant ledger mutex. + let mut pages: Vec<_> = pages.into_iter().map(|page| page & !(PAGE - 1)).collect(); + pages.sort_unstable(); + pages.dedup(); + let mut ledger = self.ledger.lock().unwrap(); + if ledger.check(self.state_generation).is_err() { return false } + ledger.work.add_pages(pages, reason); + true + } + + fn add_dirty_pages(&self, pages: impl IntoIterator<Item = usize>) -> bool { + self.add_pages(pages, WorkReasons::DIRTY) + } + + fn add_retry_pages(&self, pages: impl IntoIterator<Item = usize>) -> bool { + self.add_pages(pages, WorkReasons::RETRY) + } + + fn add_zero_ranges(&self, ranges: &[(usize, usize)]) -> bool { + let mut ledger = self.ledger.lock().unwrap(); + if ledger.check(self.state_generation).is_err() { return false } + ledger.work.add_zero_ranges(ranges); + true + } + + fn seal(&self, owner: u64, limit: usize) -> Result<Option<SparseBatchLease>, SparseBatchError> { + let result = self.ledger.lock().unwrap().seal(self.state_generation, owner, limit)?; + Ok(result.map(|(token, pages)| SparseBatchLease { ledger: self.ledger.clone(), token, pages })) + } + + fn observe(&self, through: u64, requester: u64) -> Result<ClaimFrontierAction, SparseBatchError> { + self.ledger.lock().unwrap().observe(self.state_generation, through, requester) + } + + fn through(&self) -> Result<u64, SparseBatchError> { + self.ledger.lock().unwrap().through(self.state_generation) + } + + fn take_over( + &self, token: ClaimFrontierToken, owner: u64, + ) -> Result<SparseBatchLease, SparseBatchError> { + let (token, pages) = self.ledger.lock().unwrap().take_over(token, owner)?; + Ok(SparseBatchLease { ledger: self.ledger.clone(), token, pages }) + } + + fn replace_generation(&self, replacement: u64) -> Result<Self, SparseBatchError> { + self.ledger.lock().unwrap().replace_generation(self.state_generation, replacement)?; + Ok(Self { ledger: self.ledger.clone(), state_generation: replacement }) + } +} + +#[allow(dead_code)] +struct SparseBatchLease { + ledger: Arc<Mutex<SparseBatchLedger>>, + token: ClaimFrontierToken, + pages: Vec<(usize, WorkReasons)>, +} + +#[allow(dead_code)] +impl SparseBatchLease { + fn pages(&self) -> &[(usize, WorkReasons)] { &self.pages } + + fn take_over(&self, owner: u64) -> Result<Self, SparseBatchError> { + let (token, pages) = self.ledger.lock().unwrap().take_over(self.token, owner)?; + Ok(Self { ledger: self.ledger.clone(), token, pages }) + } + + fn accept(self) -> Result<AcceptedSparseBatch, SparseBatchError> { + self.ledger.lock().unwrap().accept(self.token)?; + Ok(AcceptedSparseBatch { ledger: self.ledger.clone(), token: Some(self.token) }) + } + + fn obsolete(self) -> Result<(), SparseBatchError> { + self.ledger.lock().unwrap().obsolete(self.token) + } +} + +/// Accepted work is fail-closed: losing its owner consumes the claim and poisons the generation. +#[allow(dead_code)] +struct AcceptedSparseBatch { + ledger: Arc<Mutex<SparseBatchLedger>>, + token: Option<ClaimFrontierToken>, +} + +#[allow(dead_code)] +impl AcceptedSparseBatch { + fn receipt(mut self, fence: u64) -> Result<(), SparseBatchError> { + let result = self.ledger.lock().unwrap().receipt(self.token.unwrap(), fence); + if result.is_ok() { self.token.take(); } + result + } +} + +impl Drop for AcceptedSparseBatch { + fn drop(&mut self) { + if let Some(token) = self.token.take() { + let _ = self.ledger.lock().unwrap().poison(token); + } + } +} + /// Point-in-time identities needed to prove that planning and a later serialized upload commit /// still refer to the same sparse page. `source` names the observed CPU page by chunk hash rather /// than retaining a raw pointer across the unlocked interval. Title writes are outside sparse @@ -4221,6 +4505,121 @@ mod tests { assert_eq!(takeover.observe(43, token.epoch, 1), Ok(ClaimFrontierAction::Progress(token))); } + #[test] + fn sparse_batch_takeover_revokes_without_restoring_or_duplicating_work() { + let batches = SparseBatches::new(47); + assert!(batches.add_dirty_pages([0x1_1000])); + let old = batches.seal(1, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + assert_eq!(old.pages()[0].0, 0x1_1000); + + let replacement = old.take_over(2).unwrap(); + assert!(matches!( + old.obsolete(), + Err(SparseBatchError::Frontier(ClaimFrontierError::StaleToken)), + )); + assert_eq!(replacement.pages()[0].0, 0x1_1000); + replacement.accept().unwrap().receipt(5).unwrap(); + assert_eq!( + batches.observe(through, 9), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(5) }), + "the revoked owner restored or duplicated its work", + ); + assert!(batches.seal(3, 1).unwrap().is_none()); + } + + #[test] + fn dropped_pending_batch_remains_visible_for_foreground_takeover() { + let batches = SparseBatches::new(53); + assert!(batches.add_dirty_pages([0x2_1000])); + let abandoned = batches.seal(10, 1).unwrap().unwrap(); + let token = abandoned.token; + let through = batches.through().unwrap(); + drop(abandoned); + assert_eq!(batches.observe(through, 20), Ok(ClaimFrontierAction::TakeOver(token))); + + let foreground = batches.take_over(token, 20).unwrap(); + foreground.accept().unwrap().receipt(7).unwrap(); + assert_eq!( + batches.observe(through, 20), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(7) }), + ); + } + + #[test] + fn sparse_batch_producers_are_collected_before_locking() { + use std::sync::atomic::{AtomicBool, Ordering}; + let batches = SparseBatches::new(57); + let unlocked = AtomicBool::new(false); + let ledger = batches.ledger.clone(); + let pages = std::iter::once_with(|| { unlocked.store(ledger.try_lock().is_ok(), Ordering::Relaxed); 0x2_2001 }); + assert!(batches.add_dirty_pages(pages)); + assert!(unlocked.load(Ordering::Relaxed), "a producer iterator ran under the batch lock"); + assert_eq!(batches.seal(1, 1).unwrap().unwrap().pages()[0].0, 0x2_2000); + } + + #[test] + fn sparse_batch_ready_requires_new_reasons_to_be_sealed() { + let batches = SparseBatches::new(59); + assert!(batches.add_dirty_pages([0x3_1000])); + let first = batches.seal(1, 1).unwrap().unwrap(); + let first_epoch = batches.through().unwrap(); + assert!(batches.add_dirty_pages([0x3_1001])); + assert_eq!(batches.through(), Err(SparseBatchError::Unsealed)); + assert_eq!(batches.observe(first_epoch, 2), Err(SparseBatchError::Unsealed)); + + first.accept().unwrap().receipt(8).unwrap(); + assert_eq!(batches.through(), Err(SparseBatchError::Unsealed)); + let successor = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + assert!(through > first_epoch); + successor.obsolete().unwrap(); + assert_eq!( + batches.observe(through, 2), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(8) }), + ); + } + + #[test] + fn sparse_batch_receipts_are_contiguous_and_acceptance_is_fail_closed() { + let batches = SparseBatches::new(61); + assert!(batches.add_dirty_pages([0x4_1000, 0x4_2000])); + let first = batches.seal(1, 1).unwrap().unwrap(); + let second = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + let first_token = first.token; + let first = first.accept().unwrap(); + let second = second.accept().unwrap(); + second.receipt(11).unwrap(); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::WaitForReceipt(first_token))); + first.receipt(8).unwrap(); + assert_eq!( + batches.observe(through, 3), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(11) }), + ); + + assert!(batches.add_dirty_pages([0x4_3000])); + let accepted = batches.seal(4, 1).unwrap().unwrap().accept().unwrap(); + let accepted_token = accepted.token.unwrap(); + assert!(matches!( + batches.take_over(accepted_token, 5), + Err(SparseBatchError::Frontier(ClaimFrontierError::WrongState)), + )); + drop(accepted); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + + let current = batches.replace_generation(62).unwrap(); + assert_eq!(batches.through(), Err(SparseBatchError::StaleGeneration)); + assert!(matches!(current.replace_generation(61), Err(SparseBatchError::StaleGeneration))); + assert!(matches!(current.take_over(accepted_token, 6), Err(SparseBatchError::StaleGeneration))); + assert!(current.add_dirty_pages([0x5_1000])); + let stale = current.seal(6, 1).unwrap().unwrap(); + let replacement = current.replace_generation(63).unwrap(); + assert_eq!(stale.obsolete(), Err(SparseBatchError::StaleGeneration)); + assert_eq!(replacement.through(), Ok(0)); + assert!(matches!(SparseBatches::new(u64::MAX).replace_generation(0), Err(SparseBatchError::StaleGeneration))); + } + fn upload_observation(page: usize, pool: (u32, u32), source_word: u64) -> UploadPageObservation { let mut source = ZERO_HASHES; source[1] = source_word; From a4f0399f19e4b9887bcf972a909e98a3ceab0505 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:38:54 -0800 Subject: [PATCH 232/265] D3D12.X: track bounded evicted pipeline identities Add an inert ledger which reserves bounded capacity before native detachment and validates every later transition against the exact build allocation, native generation, slot generation, and serial. Armed failures remain visible until explicitly retired. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 348 +++++++++++++++++++++++++ 1 file changed, 348 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 5bf4336558..aeb4e121bf 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -888,6 +888,243 @@ impl PressureAdmission { } } +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct LedgerNativeGeneration { + id: u64, + identity: usize, +} + +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum EvictedBuildState { + Reserved, + Evicted, + RehydrateQueued, + Restored, + Released, + Poisoned, +} + +impl EvictedBuildState { + fn terminal(self) -> bool { + matches!(self, Self::Restored | Self::Released | Self::Poisoned) + } +} + +#[allow(dead_code)] +#[derive(Clone)] +struct EvictedBuildToken { + ledger_generation: u64, + ledger_instance: u64, + slot: usize, + slot_generation: u64, + serial: u64, + build: Weak<Build>, + native: LedgerNativeGeneration, +} + +impl EvictedBuildToken { + fn exact(&self, other: &Self) -> bool { + self.ledger_generation == other.ledger_generation + && self.ledger_instance == other.ledger_instance + && self.slot == other.slot + && self.slot_generation == other.slot_generation + && self.serial == other.serial + && Weak::ptr_eq(&self.build, &other.build) + && self.native == other.native + } +} + +struct EvictedBuildEntry { + token: EvictedBuildToken, + state: EvictedBuildState, +} + +struct EvictedBuildSlot { + generation: u64, + entry: Option<EvictedBuildEntry>, +} + +struct EvictedBuildLedgerInner<const N: usize> { + serial: u64, + exhausted: bool, + slots: [EvictedBuildSlot; N], +} + +/// A future eviction path must reserve and arm one exact record before detaching native owners. +/// This remains private and unconstructed; snapshots contain only weak identities and hold no +/// ledger lock while a later pressure worker inspects Build or D3D state. +#[allow(dead_code)] +struct EvictedBuildLedger<const N: usize> { + generation: u64, + instance: u64, + inner: Mutex<EvictedBuildLedgerInner<N>>, +} + +#[allow(dead_code)] +#[derive(Clone)] +struct EvictedBuildRecord { + token: EvictedBuildToken, + state: EvictedBuildState, +} + +static NEXT_EVICTED_LEDGER_INSTANCE: AtomicU64 = AtomicU64::new(1); + +fn allocate_evicted_ledger_instance(counter: &AtomicU64) -> Option<u64> { + let mut current = counter.load(Ordering::Relaxed); + loop { + let next = current.checked_add(1)?; + match counter.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return Some(current), + Err(actual) => current = actual, + } + } +} + +#[allow(dead_code)] +impl<const N: usize> EvictedBuildLedger<N> { + fn new(generation: u64) -> Option<Self> { + if N == 0 || generation == 0 { + return None; + } + let instance = allocate_evicted_ledger_instance(&NEXT_EVICTED_LEDGER_INSTANCE)?; + Some(Self { + generation, + instance, + inner: Mutex::new(EvictedBuildLedgerInner { + serial: 0, + exhausted: false, + slots: std::array::from_fn(|_| EvictedBuildSlot { generation: 0, entry: None }), + }), + }) + } + + fn reserve<'a>( + &'a self, build: &Arc<Build>, native: LedgerNativeGeneration, + ) -> Option<EvictedBuildReservation<'a, N>> { + let mut inner = self.inner.lock().unwrap(); + if inner.exhausted { + return None; + } + let slot = inner.slots.iter().position(|slot| slot.entry.is_none())?; + let Some(serial) = inner.serial.checked_add(1) else { + inner.exhausted = true; + return None; + }; + let Some(slot_generation) = inner.slots[slot].generation.checked_add(1) else { + inner.exhausted = true; + return None; + }; + let token = EvictedBuildToken { + ledger_generation: self.generation, + ledger_instance: self.instance, + slot, + slot_generation, + serial, + build: Arc::downgrade(build), + native, + }; + inner.serial = serial; + inner.slots[slot].generation = slot_generation; + inner.slots[slot].entry = Some(EvictedBuildEntry { token: token.clone(), state: EvictedBuildState::Reserved }); + Some(EvictedBuildReservation { ledger: self, token, armed: false }) + } + + fn set_state(&self, token: &EvictedBuildToken, from: EvictedBuildState, to: EvictedBuildState) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + if entry.state != from || !entry.token.exact(token) { + return false; + } + entry.state = to; + true + } + + fn rehydrate_queued(&self, token: &EvictedBuildToken) -> bool { + self.set_state(token, EvictedBuildState::Evicted, EvictedBuildState::RehydrateQueued) + } + + fn finish(&self, token: &EvictedBuildToken, terminal: EvictedBuildState) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + if !entry.token.exact(token) { + return false; + } + let allowed = match terminal { + EvictedBuildState::Restored => entry.state == EvictedBuildState::RehydrateQueued, + EvictedBuildState::Released | EvictedBuildState::Poisoned => { + matches!(entry.state, EvictedBuildState::Evicted | EvictedBuildState::RehydrateQueued) + } + _ => false, + }; + if !allowed { return false } + entry.state = terminal; + true + } + + fn retire(&self, token: &EvictedBuildToken) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(slot) = inner.slots.get_mut(token.slot) else { return false }; + if slot.entry.as_ref().is_none_or(|entry| !entry.state.terminal() || !entry.token.exact(token)) { + return false; + } + slot.entry = None; + true + } + + fn records(&self, limit: usize) -> Vec<EvictedBuildRecord> { + let mut inner = self.inner.lock().unwrap(); + let mut records = Vec::new(); + for slot in &mut inner.slots { + let Some(entry) = slot.entry.as_mut() else { continue }; + if !entry.state.terminal() && entry.token.build.strong_count() == 0 { + entry.state = EvictedBuildState::Released; + } + if records.len() == limit { + break; + } + records.push(EvictedBuildRecord { token: entry.token.clone(), state: entry.state }); + } + records + } +} + +#[allow(dead_code)] +struct EvictedBuildReservation<'a, const N: usize> { + ledger: &'a EvictedBuildLedger<N>, + token: EvictedBuildToken, + armed: bool, +} + +#[allow(dead_code)] +impl<const N: usize> EvictedBuildReservation<'_, N> { + /// Arm before native detachment. From this point, dropping either this guard or its returned + /// token cannot erase the fail-closed record; a failed detach must finish it as Poisoned. + fn arm_detach(mut self) -> Option<EvictedBuildToken> { + if !self.ledger.set_state(&self.token, EvictedBuildState::Reserved, EvictedBuildState::Evicted) { + return None; + } + self.armed = true; + Some(self.token.clone()) + } +} + +impl<const N: usize> Drop for EvictedBuildReservation<'_, N> { + fn drop(&mut self) { + if !self.armed { + let mut inner = self.ledger.inner.lock().unwrap(); + if let Some(slot) = inner.slots.get_mut(self.token.slot) { + if slot.entry.as_ref().is_some_and(|entry| { + entry.state == EvictedBuildState::Reserved && entry.token.exact(&self.token) + }) { + slot.entry = None; + } + } + } + } +} + fn forget_in_flight(build: &Arc<Build>) { let Some(key) = &build.compute_key else { return }; let mut registry = IN_FLIGHT.lock().unwrap(); @@ -1325,6 +1562,10 @@ impl NativeGeneration { pub(super) fn same(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } // The owner allocation, rather than `raw`, distinguishes ABA reuse by a later generation. fn identity(&self) -> usize { Arc::as_ptr(&self.0) as usize } + #[allow(dead_code)] + fn ledger_identity(&self) -> LedgerNativeGeneration { + LedgerNativeGeneration { id: self.id(), identity: self.identity() } + } } struct GenerationRetirements<G, R> { @@ -2189,6 +2430,14 @@ mod used_tests { } } + fn ledger_build() -> Arc<Build> { + Arc::new(Build::new(Box::new(|| 0), false)) + } + + fn ledger_native(id: u64) -> LedgerNativeGeneration { + LedgerNativeGeneration { id, identity: id as usize + 0x1000 } + } + #[test] fn pressure_admission_rejects_ambiguous_serial_horizons() { let mut config = pressure_config(); @@ -2313,6 +2562,105 @@ mod used_tests { assert_eq!(state.decide(12, Some(pressure_sample(12, 60))), PressureDecision::default()); } + #[test] + fn evicted_ledger_reserves_before_detach_and_stays_bounded() { + let ledger = EvictedBuildLedger::<2>::new(7).unwrap(); + let builds = [ledger_build(), ledger_build(), ledger_build()]; + drop(ledger.reserve(&builds[0], ledger_native(1)).unwrap()); + assert!(ledger.records(2).is_empty(), "a pre-detach reservation drop stayed live"); + + let first = ledger.reserve(&builds[0], ledger_native(1)).unwrap().arm_detach().unwrap(); + let second = ledger.reserve(&builds[1], ledger_native(2)).unwrap().arm_detach().unwrap(); + assert!(ledger.reserve(&builds[2], ledger_native(3)).is_none(), "a full ledger admitted a detach"); + assert_eq!(ledger.records(1).len(), 1, "enumeration ignored its bound"); + let failed = first.clone(); + drop(first); + assert_eq!(ledger.records(2).len(), 2, "dropping an armed token erased detached state"); + assert!(ledger.finish(&failed, EvictedBuildState::Poisoned)); + assert_eq!(ledger.records(2)[0].state, EvictedBuildState::Poisoned); + assert!(ledger.finish(&second, EvictedBuildState::Released)); + } + + #[test] + fn evicted_ledger_instance_identity_prevents_cross_ledger_mutation() { + let first = EvictedBuildLedger::<1>::new(7).unwrap(); + let second = EvictedBuildLedger::<1>::new(7).unwrap(); + let build = ledger_build(); + let native = ledger_native(3); + let first_token = first.reserve(&build, native).unwrap().arm_detach().unwrap(); + let second_token = second.reserve(&build, native).unwrap().arm_detach().unwrap(); + assert_ne!(first_token.ledger_instance, second_token.ledger_instance); + assert!(!second.rehydrate_queued(&first_token), "a token crossed identical caller generations"); + assert_eq!(second.records(1)[0].state, EvictedBuildState::Evicted); + assert!(second.rehydrate_queued(&second_token)); + } + + #[test] + fn evicted_ledger_rejects_stale_identity_and_out_of_order_terminal() { + let ledger = EvictedBuildLedger::<1>::new(9).unwrap(); + let first_build = ledger_build(); + let first = ledger.reserve(&first_build, ledger_native(4)).unwrap().arm_detach().unwrap(); + let mut wrong_native = first.clone(); + wrong_native.native = ledger_native(5); + assert!(!ledger.rehydrate_queued(&wrong_native)); + let mut wrong_ledger = first.clone(); + wrong_ledger.ledger_generation += 1; + assert!(!ledger.rehydrate_queued(&wrong_ledger)); + assert!(!ledger.finish(&first, EvictedBuildState::Restored), + "an evicted build was restored before rehydration queued"); + assert!(ledger.rehydrate_queued(&first)); + assert!(ledger.finish(&first, EvictedBuildState::Restored)); + assert!(!ledger.finish(&first, EvictedBuildState::Released), "a terminal state changed out of order"); + assert!(ledger.retire(&first)); + + let second_build = ledger_build(); + let second = ledger.reserve(&second_build, ledger_native(5)).unwrap().arm_detach().unwrap(); + assert_eq!(first.slot, second.slot); + assert_ne!(first.slot_generation, second.slot_generation); + assert!(!ledger.finish(&first, EvictedBuildState::Poisoned), "a stale token mutated a reused slot"); + assert_eq!(ledger.records(1)[0].state, EvictedBuildState::Evicted); + assert!(ledger.rehydrate_queued(&second)); + assert!(ledger.finish(&second, EvictedBuildState::Poisoned)); + assert!(ledger.retire(&second)); + + let third = ledger.reserve(&second_build, ledger_native(6)).unwrap().arm_detach().unwrap(); + assert!(ledger.rehydrate_queued(&third)); + assert!(ledger.finish(&third, EvictedBuildState::Released)); + } + + #[test] + fn evicted_ledger_retires_expired_weak_build_identity() { + let ledger = EvictedBuildLedger::<1>::new(11).unwrap(); + let build = ledger_build(); + let token = ledger.reserve(&build, ledger_native(6)).unwrap().arm_detach().unwrap(); + drop(build); + assert_eq!(ledger.records(1)[0].state, EvictedBuildState::Released); + + let replacement = ledger_build(); + let mut reused_address = token.clone(); + reused_address.build = Arc::downgrade(&replacement); + assert!(!ledger.retire(&reused_address), "a different allocation identity retired the entry"); + assert!(ledger.retire(&token)); + } + + #[test] + fn evicted_ledger_counter_overflow_fails_closed() { + let build = ledger_build(); + let serial = EvictedBuildLedger::<1>::new(13).unwrap(); + serial.inner.lock().unwrap().serial = u64::MAX; + assert!(serial.reserve(&build, ledger_native(7)).is_none()); + assert!(serial.inner.lock().unwrap().exhausted); + + let generation = EvictedBuildLedger::<1>::new(14).unwrap(); + generation.inner.lock().unwrap().slots[0].generation = u64::MAX; + assert!(generation.reserve(&build, ledger_native(8)).is_none()); + assert!(generation.inner.lock().unwrap().exhausted); + + let instance = AtomicU64::new(u64::MAX - 1); + assert_eq!(allocate_evicted_ledger_instance(&instance), Some(u64::MAX - 1)); + assert_eq!(allocate_evicted_ledger_instance(&instance), None); + } + #[test] fn rebuild_recipe_gate_requires_exact_one() { assert!(recipe_gate_value(Some("1"))); From d98343d2d7ea60dbfaddb2b77b942bd6cdd1405f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:32:05 -0800 Subject: [PATCH 233/265] D3D12.X: observe bounded pipeline pressure candidates Run pressure admission and bounded candidate inspection only from the existing activity observer, using its completed DXGI sample. Every live popped identity is requeued or conserved weakly without clearing its dedup flag, so crossing binds, transient rebuilds, and journal saturation lose no candidate or retain a released generation. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 395 ++++++++++++++++++++++++- crates/xcl/src/host.rs | 5 + 2 files changed, 395 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index aeb4e121bf..98c1aa125d 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -564,15 +564,40 @@ impl Drop for EvictionCandidate { } impl EvictionCandidate { + fn try_requeue_on<const N: usize>(mut self, candidates: &CandidateQueue<Build, N>) -> Result<(), Self> { + if candidates.push(Arc::downgrade(&self.build)).is_err() { + return Err(self); + } + self.clear_queued_on_drop = false; + Ok(()) + } + /// Return a deferred candidate to the bounded weak journal without opening a duplicate-record /// window. If a crossing producer filled the freed slot, dropping this owner clears the flag /// so a later bind can retry instead of leaving the build permanently marked as queued. - fn requeue_on<const N: usize>(mut self, candidates: &CandidateQueue<Build, N>) -> bool { - if candidates.push(Arc::downgrade(&self.build)).is_err() { - return false; - } + fn requeue_on<const N: usize>(self, candidates: &CandidateQueue<Build, N>) -> bool { + self.try_requeue_on(candidates).is_ok() + } + + fn into_held(mut self) -> HeldEvictionCandidate { + let build = Arc::downgrade(&self.build); self.clear_queued_on_drop = false; - true + HeldEvictionCandidate { build } + } +} + +/// A saturated observer must conserve the deduplicated identity without retaining the pipeline, +/// its rebuild recipe, or its native generation after the title releases them. +struct HeldEvictionCandidate { build: Weak<Build> } +enum HeldRequeue { Requeued, Held(HeldEvictionCandidate), Expired } + +impl HeldEvictionCandidate { + fn try_requeue_on<const N: usize>(self, candidates: &CandidateQueue<Build, N>) -> HeldRequeue { + if self.build.upgrade().is_none() { return HeldRequeue::Expired } + match candidates.push(self.build.clone()) { + Ok(()) => HeldRequeue::Requeued, + Err(_) => HeldRequeue::Held(self), + } } } @@ -1125,6 +1150,154 @@ impl<const N: usize> Drop for EvictedBuildReservation<'_, N> { } } +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct PressureObservation { + mode: PressureMode, + scanned: usize, + eligible: usize, + deferred: usize, + discarded: usize, + requeue_saturated: usize, +} + +impl PressureObservation { + fn line(self) -> String { + format!( + "pipeline pressure observation: {:?}; {} scanned, {} eligible, {} deferred, {} discarded, {} requeue saturated", + self.mode, self.scanned, self.eligible, self.deferred, self.discarded, self.requeue_saturated, + ) + } +} + +struct PressureObserver { + admission: PressureAdmission, + limits: EvictionSelectionLimits, + held: Vec<HeldEvictionCandidate>, +} + +impl PressureObserver { + fn new(config: PressureAdmissionConfig, limits: EvictionSelectionLimits) -> Option<Self> { + PressureAdmission::new(config).map(|admission| Self { + admission, held: Vec::with_capacity(limits.max_scan), limits, + }) + } + + /// Observe and immediately requeue every actionable candidate. This deliberately cannot evict: + /// the diagnostic validates pressure admission and candidate flow without changing residency. + fn observe_on<const N: usize>( + &mut self, + candidates: &CandidateQueue<Build, N>, + turn: u64, + frame: u64, + sample: Option<PressureSample>, + ) -> PressureObservation { + self.observe_on_after_drain(candidates, turn, frame, sample, || {}) + } + + fn observe_on_after_drain<const N: usize>( + &mut self, + candidates: &CandidateQueue<Build, N>, + turn: u64, + frame: u64, + sample: Option<PressureSample>, + after_drain: impl FnOnce(), + ) -> PressureObservation { + let decision = self.admission.decide(turn, sample); + let mut observation = PressureObservation { mode: self.admission.mode, ..Default::default() }; + + // Conserve exact weak identities until this one-scan backlog returns to the journal. + let pending = std::mem::replace(&mut self.held, Vec::with_capacity(self.limits.max_scan)); + for candidate in pending { + match candidate.try_requeue_on(candidates) { + HeldRequeue::Requeued => {} + HeldRequeue::Held(candidate) => self.held.push(candidate), + HeldRequeue::Expired => observation.discarded += 1, + } + } + observation.requeue_saturated = self.held.len(); + if !self.held.is_empty() || decision.max_evictions == 0 { + return observation; + } + let limits = EvictionSelectionLimits { + max_scan: self.limits.max_scan.min(decision.max_evictions), + max_select: self.limits.max_select.min(decision.max_evictions), + ..self.limits + }; + let mut drained = Vec::new(); + let mut nonactionable = Vec::new(); + for _ in 0..limits.max_scan { + let Some(weak) = candidates.pop() else { break }; + observation.scanned += 1; + let Some(build) = weak.upgrade() else { + observation.discarded += 1; + continue; + }; + match resident_candidate(&build) { + Some(candidate) => drained.push(candidate), + None => nonactionable.push(HeldEvictionCandidate { build: weak }), + } + } + after_drain(); + let (selected, deferred) = partition_eviction_candidates(drained, frame, limits); + observation.eligible = selected.len(); + observation.deferred = deferred.len() + nonactionable.len(); + for candidate in selected.into_iter().map(|selected| selected.candidate).chain(deferred) { + if let Err(candidate) = candidate.try_requeue_on(candidates) { + self.held.push(candidate.into_held()); + } + } + for candidate in nonactionable { + match candidate.try_requeue_on(candidates) { + HeldRequeue::Requeued => {} + HeldRequeue::Held(candidate) => self.held.push(candidate), + HeldRequeue::Expired => observation.discarded += 1, + } + } + observation.requeue_saturated = self.held.len(); + observation + } +} + +fn pressure_observe_gate_value(value: Option<&str>) -> bool { value.is_some_and(|value| value.trim() == "1") } + +fn pressure_observer() -> Option<&'static Mutex<PressureObserver>> { + static OBSERVER: OnceLock<Option<Mutex<PressureObserver>>> = OnceLock::new(); + OBSERVER.get_or_init(|| { + let requested = std::env::var("XCL_PSO_PRESSURE_OBSERVE").ok(); + if !pressure_observe_gate_value(requested.as_deref()) || !rebuild_recipes_enabled() { + return None; + } + let config = PressureAdmissionConfig { + enabled: true, + max_sample_age_turns: 0, + max_evictions_per_turn: 8, + ..Default::default() + }; + let limits = EvictionSelectionLimits { + max_scan: 32, + max_select: 8, + min_unused_frames: 600, + min_resident_frames: 60, + }; + crate::xlog_info!( + "D3D12.X: XCL_PSO_PRESSURE_OBSERVE=1 - observing pipeline pressure only; pipelines are not evicted" + ); + PressureObserver::new(config, limits).map(Mutex::new) + }).as_ref() +} + +/// Called only by the existing activity observer after it has obtained and released the DXGI +/// memory snapshot. No title or submission thread samples the adapter or scans candidates. +pub(crate) fn observe_pressure_turn( + turn: u64, local: Option<super::memory_report::Segment>, +) -> Option<String> { + let observer = pressure_observer()?; + let sample = local.map(|segment| PressureSample { observed_turn: turn, segment }); + Some(observer.lock().unwrap().observe_on( + eviction_candidates(), turn, super::present::presents(), sample, + ).line()) +} + fn forget_in_flight(build: &Arc<Build>) { let Some(key) = &build.compute_key else { return }; let mut registry = IN_FLIGHT.lock().unwrap(); @@ -2661,12 +2834,224 @@ mod used_tests { assert_eq!(allocate_evicted_ledger_instance(&instance), None); } + #[test] + fn pressure_observer_bounds_inspection_and_requeues_every_resident() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = [ + RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }, + RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }, + RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }, + ]; + let mut builds = Vec::new(); + let mut recipes = Vec::new(); + for value in &mut native { + let raw = value as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed( + recipe.initial_job(), false, None, Some(recipe.clone()), + )); + let job = build.job.lock().unwrap().take().unwrap(); + complete(&build, job()); + builds.push(build); + recipes.push(recipe); + } + let queue = CandidateQueue::<Build, 4>::new(); + for (build, last_use) in builds.iter().zip([99, 10, 20]) { + build.completed_frame.store(0, Ordering::Relaxed); + note_eviction_candidate_on(build, last_use, &queue); + } + + let config = PressureAdmissionConfig { + enabled: true, + max_sample_age_turns: 1, + max_evictions_per_turn: 2, + ..PressureAdmissionConfig::default() + }; + let limits = EvictionSelectionLimits { + max_scan: 3, max_select: 2, min_unused_frames: 10, min_resident_frames: 0, + }; + let mut observer = PressureObserver::new(config, limits).unwrap(); + let positions = || ( + queue.enqueue.load(Ordering::Relaxed), queue.dequeue.load(Ordering::Relaxed), + ); + + let before = positions(); + let mut disabled = PressureObserver::new(PressureAdmissionConfig::default(), limits).unwrap(); + assert_eq!(disabled.observe_on(&queue, 7, 100, Some(pressure_sample(7, 100))), PressureObservation::default()); + assert_eq!(positions(), before, "a disabled observer touched the candidate journal"); + assert_eq!(observer.observe_on(&queue, 8, 100, None), PressureObservation::default()); + assert_eq!(positions(), before, "a missing sample touched the candidate journal"); + let stale = PressureSample { + observed_turn: 7, + segment: super::super::memory_report::Segment { usage: 95, budget: 100 }, + }; + assert_eq!(observer.observe_on(&queue, 9, 100, Some(stale)), PressureObservation::default()); + assert_eq!(positions(), before, "a stale sample touched the candidate journal"); + + let high = PressureSample { + observed_turn: 9, + segment: super::super::memory_report::Segment { usage: 95, budget: 100 }, + }; + let observed = observer.observe_on(&queue, 10, 100, Some(high)); + assert_eq!(observed, PressureObservation { + mode: PressureMode::Evicting, + scanned: 2, + eligible: 1, + deferred: 1, + discarded: 0, + requeue_saturated: 0, + }); + assert!(builds.iter().all(|build| build.real.load(Ordering::Acquire) != 0)); + assert!(builds.iter().all(|build| build.candidate_queued.load(Ordering::Acquire))); + + let same_turn = PressureSample { + observed_turn: 10, + segment: super::super::memory_report::Segment { usage: 95, budget: 100 }, + }; + assert_eq!(observer.observe_on(&queue, 10, 100, Some(same_turn)), PressureObservation { + mode: PressureMode::Evicting, ..Default::default() + }, "a second sample replenished the same observation turn"); + + // Deterministically model producers consuming every freed slot between drain and requeue. + // The observer must retain exact candidates instead of clearing their queued identity. + let fillers: Vec<_> = (0..3).map(|_| Arc::new(Build::new(Box::new(|| 0), false))).collect(); + let next = PressureSample { + observed_turn: 11, + segment: super::super::memory_report::Segment { usage: 95, budget: 100 }, + }; + let saturated = observer.observe_on_after_drain(&queue, 11, 100, Some(next), || { + for filler in &fillers { + assert!(queue.push(Arc::downgrade(filler)).is_ok()); + } + }); + assert_eq!(saturated, PressureObservation { + mode: PressureMode::Evicting, + scanned: 2, + eligible: 2, + deferred: 0, + discarded: 0, + requeue_saturated: 2, + }); + assert_eq!(observer.held.len(), 2); + assert!(observer.held.iter().all(|candidate| candidate.build.upgrade() + .is_some_and(|build| build.candidate_queued.load(Ordering::Acquire)))); + let blocked = observer.observe_on(&queue, 12, 100, None); + assert_eq!(blocked.requeue_saturated, 2); + assert_eq!(blocked.scanned, 0, "a saturated conservation backlog allowed another drain"); + let crossing = observer.held[0].build.upgrade().unwrap(); + let crossing_recipe = crossing.recipe.as_ref().unwrap().clone(); + assert!(matches!(crossing_recipe.begin_rebuild(), RebuildTurn::Leader)); + let before_crossing_bind = positions(); + note_eviction_candidate_on(&crossing, 100, &queue); + assert_eq!(positions(), before_crossing_bind, "a crossing bind duplicated the held identity"); + + let mut seen = HashSet::new(); + for _ in 0..2 { + let build = queue.pop().unwrap().upgrade().unwrap(); + if builds.iter().any(|expected| Arc::ptr_eq(expected, &build)) { + assert!(seen.insert(Arc::as_ptr(&build) as usize)); + } + } + let recovered = observer.observe_on(&queue, 13, 100, None); + assert_eq!(recovered.requeue_saturated, 0); + assert!(observer.held.is_empty()); + crossing_recipe.finish_rebuild(RebuildResult::Failed); + drop(crossing); + drop(crossing_recipe); + for _ in 0..4 { + let build = queue.pop().unwrap().upgrade().unwrap(); + if builds.iter().any(|expected| Arc::ptr_eq(expected, &build)) { + assert!(seen.insert(Arc::as_ptr(&build) as usize), "observation duplicated a journal record"); + } + } + assert_eq!(seen.len(), 3); + assert!(queue.pop().is_none()); + for build in &builds { + build.candidate_queued.store(false, Ordering::Release); + } + + let finals: Vec<_> = builds.iter().map(|build| build.real.swap(0, Ordering::AcqRel)).collect(); + drop(builds); + drop(recipes); + for raw in finals { + release(raw); + } + assert!(native.iter().all(|value| value.refs.load(Ordering::Relaxed) == 0)); + } + + #[test] + fn saturated_pressure_backlog_does_not_retain_a_released_native_pipeline() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed( + recipe.initial_job(), false, None, Some(recipe.clone()), + )); + let job = build.job.lock().unwrap().take().unwrap(); + complete(&build, job()); + let queue = CandidateQueue::<Build, 2>::new(); + note_eviction_candidate_on(&build, 0, &queue); + let fillers = [Arc::new(Build::new(Box::new(|| 0), false)), + Arc::new(Build::new(Box::new(|| 0), false))]; + let config = PressureAdmissionConfig { + enabled: true, max_evictions_per_turn: 1, ..PressureAdmissionConfig::default() + }; + let mut observer = PressureObserver::new(config, EvictionSelectionLimits { + max_scan: 1, max_select: 1, min_unused_frames: 0, min_resident_frames: 0, + }).unwrap(); + let saturated = observer.observe_on_after_drain(&queue, 1, 1, Some(pressure_sample(1, 100)), || { + for filler in &fillers { + assert!(queue.push(Arc::downgrade(filler)).is_ok()); + } + }); + assert_eq!(saturated.requeue_saturated, 1); + assert_eq!(observer.held.len(), 1); + + build.owners.store(0, Ordering::Release); + release(build.real.swap(0, Ordering::AcqRel)); + drop(build); + drop(recipe); + assert_eq!(native.refs.load(Ordering::Relaxed), 0, "weak backlog retained the native generation"); + assert!(observer.held[0].build.upgrade().is_none()); + let expired = observer.observe_on(&queue, 2, 1, None); + assert_eq!((expired.requeue_saturated, expired.discarded), (0, 1)); + assert!(observer.held.is_empty(), "an expired weak identity remained backlogged"); + } + + #[test] + fn pressure_observer_reports_every_popped_invalid_record() { + let queue = CandidateQueue::<Build, 4>::new(); + let dead = Arc::new(Build::new(Box::new(|| 0), false)); + assert!(queue.push(Arc::downgrade(&dead)).is_ok()); + drop(dead); + let nonresident = Arc::new(Build::new(Box::new(|| 0), false)); nonresident.candidate_queued.store(true, Ordering::Release); + assert!(queue.push(Arc::downgrade(&nonresident)).is_ok()); + let config = PressureAdmissionConfig { + enabled: true, max_evictions_per_turn: 2, ..PressureAdmissionConfig::default() + }; + let mut observer = PressureObserver::new(config, EvictionSelectionLimits { + max_scan: 2, max_select: 2, min_unused_frames: 0, min_resident_frames: 0, + }).unwrap(); + assert_eq!(observer.observe_on(&queue, 1, 1, Some(pressure_sample(1, 100))), PressureObservation { + mode: PressureMode::Evicting, + scanned: 2, + eligible: 0, + deferred: 1, + discarded: 1, + requeue_saturated: 0, + }); + assert!(queue.pop().unwrap().upgrade().is_some()); + } + #[test] fn rebuild_recipe_gate_requires_exact_one() { assert!(recipe_gate_value(Some("1"))); assert!(recipe_gate_value(Some(" 1\t"))); + assert!(pressure_observe_gate_value(Some(" 1\t"))); for value in [None, Some(""), Some("0"), Some("true"), Some("2")] { assert!(!recipe_gate_value(value)); + assert!(!pressure_observe_gate_value(value)); } } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 243873926d..a848b88194 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -59,6 +59,7 @@ pub fn host_main(boot_path: &Path) -> i32 { }; let mut last = snap(); let mut last_looks = crate::hle::d3d12x::sparse::look_counters(); + let mut pressure_turn = 0u64; loop { std::thread::sleep(std::time::Duration::from_secs(2)); let now = snap(); @@ -74,6 +75,10 @@ pub fn host_main(boot_path: &Path) -> i32 { last_looks = looks; // where the memory is: the process's commit, video memory, and XCL's parts of it let owner = crate::hle::d3d12x::memory_report::snapshot(); + pressure_turn = pressure_turn.wrapping_add(1); + if let Some(line) = crate::hle::d3d12x::pso_async::observe_pressure_turn(pressure_turn, owner.local) { + crate::xlog_info!("{line}"); + } let private = owner.commit.unwrap_or(0); let local = owner.local.map_or(0, |s| s.usage); let non_local = owner.non_local.map_or(0, |s| s.usage); From 99c45c49c621d4649dd4f5be5ab82b0cf60f2880 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:49:13 -0800 Subject: [PATCH 234/265] D3D12.X: compose sparse batch submission receipts Bind revocable sparse batch leases to exact staging reservations. Pre-submit failures remain visible for takeover, while every accepted failure poisons both ownership domains and successful submission publishes the staging receipt before the frontier fence. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 391 ++++++++++++++++++++++++++-- 1 file changed, 376 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 16d2d94507..9a82172e9a 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -767,10 +767,11 @@ impl SparseBatchLedger { Ok(self.frontier.next_epoch) } - fn accept(&mut self, token: ClaimFrontierToken) -> Result<(), SparseBatchError> { + fn accept(&mut self, token: ClaimFrontierToken) -> Result<WorkClaimToken, SparseBatchError> { self.check(token.state_generation)?; - self.binding(token, ClaimFrontierState::Pending)?; - self.frontier.accept(token).map_err(SparseBatchError::Frontier) + let work = self.binding(token, ClaimFrontierState::Pending)?; + self.frontier.accept(token).map_err(SparseBatchError::Frontier)?; + Ok(work) } fn receipt(&mut self, token: ClaimFrontierToken, fence: u64) -> Result<(), SparseBatchError> { @@ -806,13 +807,17 @@ impl SparseBatchLedger { Ok(()) } - fn poison(&mut self, token: ClaimFrontierToken) -> Result<(), SparseBatchError> { - self.check(token.state_generation)?; - let work = self.binding(token, ClaimFrontierState::Accepted)?; - if self.work.commit(work) != WorkClaimResolution::Committed { + fn poison_exact( + &mut self, token: ClaimFrontierToken, work: WorkClaimToken, + ) -> Result<(), SparseBatchError> { + if token.state_generation != self.work.state_generation || work.state_generation != token.state_generation { + return Err(SparseBatchError::StaleGeneration); + } + let resolution = self.work.commit(work); + if !matches!(resolution, WorkClaimResolution::Committed | WorkClaimResolution::AlreadyFinished) { return Err(SparseBatchError::Corrupt); } - self.bindings.remove(&token.epoch); + if self.bindings.get(&token.epoch) == Some(&work) { self.bindings.remove(&token.epoch); } self.poisoned = true; Ok(()) } @@ -923,8 +928,8 @@ impl SparseBatchLease { } fn accept(self) -> Result<AcceptedSparseBatch, SparseBatchError> { - self.ledger.lock().unwrap().accept(self.token)?; - Ok(AcceptedSparseBatch { ledger: self.ledger.clone(), token: Some(self.token) }) + let work = self.ledger.lock().unwrap().accept(self.token)?; + Ok(AcceptedSparseBatch { ledger: self.ledger.clone(), token: Some((self.token, work)) }) } fn obsolete(self) -> Result<(), SparseBatchError> { @@ -936,13 +941,13 @@ impl SparseBatchLease { #[allow(dead_code)] struct AcceptedSparseBatch { ledger: Arc<Mutex<SparseBatchLedger>>, - token: Option<ClaimFrontierToken>, + token: Option<(ClaimFrontierToken, WorkClaimToken)>, } #[allow(dead_code)] impl AcceptedSparseBatch { fn receipt(mut self, fence: u64) -> Result<(), SparseBatchError> { - let result = self.ledger.lock().unwrap().receipt(self.token.unwrap(), fence); + let result = self.ledger.lock().unwrap().receipt(self.token.unwrap().0, fence); if result.is_ok() { self.token.take(); } result } @@ -950,8 +955,8 @@ impl AcceptedSparseBatch { impl Drop for AcceptedSparseBatch { fn drop(&mut self) { - if let Some(token) = self.token.take() { - let _ = self.ledger.lock().unwrap().poison(token); + if let Some((token, work)) = self.token.take() { + let _ = self.ledger.lock().unwrap().poison_exact(token, work); } } } @@ -1022,6 +1027,54 @@ struct OwnedUploadStaging { bytes: Box<[u8]>, } +fn build_upload_pages( + claimed: &[(usize, WorkReasons)], mut observe: impl FnMut(usize) -> Option<UploadPageObservation>, +) -> Option<Vec<PlannedUploadPage>> { + let mut pages = Vec::with_capacity(claimed.len()); + for &(page, reasons) in claimed { + let observation = observe(page)?; + if observation.page != page || observation.hole { return None } + let dirty = reasons.0 & (WorkReasons::DIRTY.0 | WorkReasons::RETRY.0) != 0; + let mut dirty_ranges = Vec::new(); + if dirty { + let sent = observation.sent.as_ref().unwrap_or(&ZERO_HASHES); + for (chunk, (&source, &previous)) in observation.source.iter().zip(sent).enumerate() { + if source != previous { push_run(&mut dirty_ranges, page + chunk * CHUNK, CHUNK) } + } + } + pages.push(PlannedUploadPage { + page, + tile: page & !(TILE - 1), + pool: observation.pool, + reasons, + zero: reasons.0 & WorkReasons::ZERO.0 != 0, + dirty, + dirty_ranges, + sent: observation.sent, + source: observation.source, + }); + } + Some(pages) +} + +fn validate_upload_pages( + pages: &[PlannedUploadPage], mut observe: impl FnMut(usize) -> Option<UploadPageObservation>, +) -> Result<(), UploadPlanInvalid> { + for planned in pages { + let current = observe(planned.page).ok_or(UploadPlanInvalid::MissingPage)?; + if current.page != planned.page + || current.page & !(TILE - 1) != planned.tile + || current.pool != planned.pool + || current.hole + { + return Err(UploadPlanInvalid::Mapping); + } + if current.sent != planned.sent { return Err(UploadPlanInvalid::SentHashes) } + if current.source != planned.source { return Err(UploadPlanInvalid::SourceHashes) } + } + Ok(()) +} + /// Inert immutable work between an exact journal claim and a future short serialized commit. /// Dropping an uncommitted plan restores its claim. No command allocator, list or staging range is /// opened or reserved here; those remain responsibilities of the later commit-phase stage. A @@ -1169,6 +1222,92 @@ impl SparseUploadPlan { } } +#[derive(Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum CoordinatedSparseUploadError<C, E, S> { + Invalid(UploadPlanInvalid), + Reserve(UploadReservationError), + Copy(C), + StagingSize, + Prepare(E), + Accept(SparseBatchError), + Signal(S), + PublishReservation(UploadReservationError), + PublishBatch(SparseBatchError), +} + +/// New inert composition path: the plan owns a revocable batch lease rather than an independently +/// restoring work guard. Dropping before acceptance leaves the batch visible for foreground help. +#[allow(dead_code)] +struct CoordinatedSparseUploadPlan { + lease: Option<SparseBatchLease>, + state_generation: u64, + mapping_epoch: u64, + pages: Vec<PlannedUploadPage>, +} + +#[allow(dead_code)] +impl CoordinatedSparseUploadPlan { + fn build( + lease: SparseBatchLease, + state_generation: u64, + mapping_epoch: u64, + observe: impl FnMut(usize) -> Option<UploadPageObservation>, + ) -> Option<Self> { + if lease.token.state_generation != state_generation { return None } + let pages = build_upload_pages(lease.pages(), observe)?; + Some(Self { lease: Some(lease), state_generation, mapping_epoch, pages }) + } + + fn validate( + &self, + state_generation: u64, + mapping_epoch: u64, + observe: impl FnMut(usize) -> Option<UploadPageObservation>, + ) -> Result<(), UploadPlanInvalid> { + if state_generation != self.state_generation { return Err(UploadPlanInvalid::StateGeneration) } + if mapping_epoch != self.mapping_epoch { return Err(UploadPlanInvalid::MappingEpoch) } + validate_upload_pages(&self.pages, observe) + } + + fn commit_reserved<C, E, S>( + mut self, + state_generation: u64, + mapping_epoch: u64, + observe: impl FnMut(usize) -> Option<UploadPageObservation>, + reservations: &UploadReservations, + slot: usize, + bytes: usize, + copy: impl FnOnce(UploadRingRange, &[PlannedUploadPage]) -> Result<Vec<u8>, C>, + prepare: impl FnOnce(&OwnedUploadStaging, &[PlannedUploadPage]) -> Result<(), E>, + execute: impl FnOnce(&OwnedUploadStaging, &[PlannedUploadPage]), + signal: impl FnOnce() -> Result<u64, S>, + ) -> Result<UploadSubmissionReceipt, CoordinatedSparseUploadError<C, E, S>> { + self.validate(state_generation, mapping_epoch, observe) + .map_err(CoordinatedSparseUploadError::Invalid)?; + let reservation = reservations.reserve_for(state_generation, slot, bytes) + .map_err(CoordinatedSparseUploadError::Reserve)?; + let range = reservation.range(); + let copied = copy(range, &self.pages).map_err(CoordinatedSparseUploadError::Copy)?; + if copied.len() != bytes { return Err(CoordinatedSparseUploadError::StagingSize) } + let staging = OwnedUploadStaging { range, bytes: copied.into_boxed_slice() }; + prepare(&staging, &self.pages).map_err(CoordinatedSparseUploadError::Prepare)?; + + let batch = self.lease.take().expect("finished coordinated sparse upload plan").accept() + .map_err(CoordinatedSparseUploadError::Accept)?; + let accepted = AcceptedCoordinatedUpload::new(reservation, batch); + execute(&staging, &self.pages); + let fence = signal().map_err(CoordinatedSparseUploadError::Signal)?; + match accepted.publish(fence) { + Ok(receipt) => Ok(receipt), + Err(CoordinatedPublishError::Reservation(error)) => { + Err(CoordinatedSparseUploadError::PublishReservation(error)) + } + Err(CoordinatedPublishError::Batch(error)) => Err(CoordinatedSparseUploadError::PublishBatch(error)), + } + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[allow(dead_code)] struct UploadReservationToken { @@ -1356,6 +1495,18 @@ impl UploadReservationLedger { Ok(()) } + /// Fail closed even after submission publication: no slot or ring byte in this generation may + /// be reused when the matching batch receipt could not be published. + fn poison_generation(&mut self, token: UploadReservationToken) { + if token.state_generation != self.state_generation { return } + if let Some(record) = self.records.get_mut(&token.serial) { + if matches!(record.state, UploadReservationState::Reserved | UploadReservationState::Submitted { .. }) { + record.state = UploadReservationState::Poisoned; + } + } + self.poisoned = true; + } + fn record_mut( &mut self, token: UploadReservationToken, ) -> Result<&mut UploadReservationRecord, UploadReservationError> { @@ -1400,6 +1551,13 @@ impl UploadReservations { Ok(UploadReservation { ledger: self.0.clone(), token: Some(token), range }) } + fn reserve_for( + &self, state_generation: u64, slot: usize, bytes: usize, + ) -> Result<UploadReservation, UploadReservationError> { + let (token, range) = self.0.lock().unwrap().reserve(state_generation, slot, bytes)?; + Ok(UploadReservation { ledger: self.0.clone(), token: Some(token), range }) + } + fn complete(&self, receipt: UploadSubmissionReceipt) -> Result<u64, UploadReservationError> { self.0.lock().unwrap().complete(receipt) } @@ -1483,6 +1641,56 @@ impl Drop for AcceptedSparseUpload { } } +enum CoordinatedPublishError { + Reservation(UploadReservationError), + Batch(SparseBatchError), +} + +/// Own both accepted ledgers. Any exit before both receipts are published poisons both generation +/// domains, including the narrow boundary after reservation submission but before frontier receipt. +struct AcceptedCoordinatedUpload { + reservation: Option<UploadReservation>, + reservation_token: UploadReservationToken, + reservation_ledger: Arc<Mutex<UploadReservationLedger>>, + batch: Option<AcceptedSparseBatch>, + batch_token: ClaimFrontierToken, + batch_ledger: Arc<Mutex<SparseBatchLedger>>, + armed: bool, +} + +impl AcceptedCoordinatedUpload { + fn new(reservation: UploadReservation, batch: AcceptedSparseBatch) -> Self { + Self { + reservation_token: reservation.token.unwrap(), + reservation_ledger: reservation.ledger.clone(), + batch_token: batch.token.unwrap().0, + batch_ledger: batch.ledger.clone(), + reservation: Some(reservation), + batch: Some(batch), + armed: true, + } + } + + fn publish(mut self, fence: u64) -> Result<UploadSubmissionReceipt, CoordinatedPublishError> { + let receipt = self.reservation.take().unwrap().publish_after_accept(fence) + .map_err(CoordinatedPublishError::Reservation)?; + self.batch.take().unwrap().receipt(fence).map_err(CoordinatedPublishError::Batch)?; + self.armed = false; + Ok(receipt) + } +} + +impl Drop for AcceptedCoordinatedUpload { + fn drop(&mut self) { + if !self.armed { return } + if let Some(reservation) = self.reservation.take() { let _ = reservation.poison(); } + if let Some(batch) = self.batch.take() { drop(batch); } + self.reservation_ledger.lock().unwrap().poison_generation(self.reservation_token); + let mut batches = self.batch_ledger.lock().unwrap(); + if batches.work.state_generation == self.batch_token.state_generation { batches.poisoned = true } + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) enum PreparationOutcome { Ready, @@ -4600,7 +4808,7 @@ mod tests { assert!(batches.add_dirty_pages([0x4_3000])); let accepted = batches.seal(4, 1).unwrap().unwrap().accept().unwrap(); - let accepted_token = accepted.token.unwrap(); + let accepted_token = accepted.token.unwrap().0; assert!(matches!( batches.take_over(accepted_token, 5), Err(SparseBatchError::Frontier(ClaimFrontierError::WrongState)), @@ -4636,6 +4844,159 @@ mod tests { (claims, plan, observation) } + fn coordinated_upload_fixture( + owner: u64, + ) -> (SparseBatches, CoordinatedSparseUploadPlan, UploadPageObservation, ClaimFrontierToken) { + let batches = SparseBatches::new(71); + assert!(batches.add_dirty_pages([0x2_1000])); + let lease = batches.seal(owner, 1).unwrap().unwrap(); + let token = lease.token; + let observation = upload_observation(0x2_1000, (4, 9), 0xA5); + let plan = CoordinatedSparseUploadPlan::build(lease, 71, 7, |_| Some(observation.clone())).unwrap(); + (batches, plan, observation, token) + } + + fn commit_coordinated( + plan: CoordinatedSparseUploadPlan, observation: &UploadPageObservation, + reservations: &UploadReservations, slot: usize, fence: u64, + ) -> Result<UploadSubmissionReceipt, CoordinatedSparseUploadError<(), (), ()>> { + plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), reservations, slot, 64, + |_, _| Ok(vec![0; 64]), |_, _| Ok(()), |_, _| {}, || Ok(fence), + ) + } + + #[test] + fn coordinated_plan_preaccept_failures_stay_visible_and_takeover_revokes() { + for failure in ["validate", "reservation generation", "reserve", "copy", "size", "prepare"] { + let (batches, plan, observation, token) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(if failure == "reservation generation" { 72 } else { 71 }, 1, 256, 64); + let occupied = (failure == "reserve").then(|| reservations.reserve(0, 64).unwrap()); + let result = plan.commit_reserved( + if failure == "validate" { 72 } else { 71 }, 7, |_| Some(observation.clone()), + &reservations, 0, 64, + |_, _| if failure == "copy" { Err("copy") } else { Ok(vec![0; if failure == "size" { 63 } else { 64 }]) }, + |_, _| if failure == "prepare" { Err("prepare") } else { Ok(()) }, + |_, _| {}, || Ok::<_, &'static str>(9), + ); + let expected = match failure { + "validate" => matches!(result, Err(CoordinatedSparseUploadError::Invalid(UploadPlanInvalid::StateGeneration))), + "reservation generation" => matches!(result, Err(CoordinatedSparseUploadError::Reserve(UploadReservationError::StaleGeneration))), + "reserve" => matches!(result, Err(CoordinatedSparseUploadError::Reserve(UploadReservationError::SlotBusy))), + "copy" => matches!(result, Err(CoordinatedSparseUploadError::Copy("copy"))), + "size" => matches!(result, Err(CoordinatedSparseUploadError::StagingSize)), + _ => matches!(result, Err(CoordinatedSparseUploadError::Prepare("prepare"))), + }; + assert!(expected, "wrong {failure} boundary result"); + assert_eq!(batches.observe(1, 9), Ok(ClaimFrontierAction::TakeOver(token))); + assert!(!reservations.0.lock().unwrap().poisoned); + drop(occupied); + } + + let (batches, stale, observation, token) = coordinated_upload_fixture(1); + let replacement = batches.take_over(token, 2).unwrap(); + let result = commit_coordinated(stale, &observation, &UploadReservations::new(71, 1, 256, 64), 0, 9); + assert!(matches!(result, Err(CoordinatedSparseUploadError::Accept( + SparseBatchError::Frontier(ClaimFrontierError::StaleToken) + )))); + assert_eq!(replacement.pages()[0].0, 0x2_1000); + } + + #[test] + fn coordinated_submit_then_panic_poisons_both_generations() { + let (batches, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let submitted = std::cell::Cell::new(false); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), + |_, _| { submitted.set(true); panic!("execute panicked after submit") }, + || Ok::<_, ()>(9), + ); + })); + assert!(result.is_err() && submitted.get()); + assert!(reservations.0.lock().unwrap().poisoned); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + + let (batches, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let result = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, || Err::<u64, _>("signal"), + ); + assert!(matches!(result, Err(CoordinatedSparseUploadError::Signal("signal")))); + assert!(reservations.0.lock().unwrap().poisoned); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + + let (batches, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + assert!(matches!(commit_coordinated(plan, &observation, &reservations, 0, 0), + Err(CoordinatedSparseUploadError::PublishReservation(UploadReservationError::State)))); + assert!(reservations.0.lock().unwrap().poisoned); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + } + + #[test] + fn coordinated_frontier_publication_failure_quarantines_submitted_reservation() { + let (batches, plan, _, _) = coordinated_upload_fixture(1); + let lease = plan.lease.unwrap(); + let batch = lease.accept().unwrap(); + let reservations = UploadReservations::new(71, 1, 256, 64); + let reservation = reservations.reserve(0, 64).unwrap(); + let mut accepted = AcceptedCoordinatedUpload::new(reservation, batch); + let receipt = accepted.reservation.take().unwrap().publish_after_accept(13).unwrap(); + accepted.batch_ledger.lock().unwrap().bindings.remove(&accepted.batch_token.epoch); + assert_eq!(accepted.batch.take().unwrap().receipt(13), Err(SparseBatchError::Corrupt)); + drop(accepted); + let ledger = reservations.0.lock().unwrap(); + assert!(ledger.poisoned); + assert_eq!(ledger.records[&receipt.token.serial].state, UploadReservationState::Poisoned); + drop(ledger); + let ledger = batches.ledger.lock().unwrap(); + assert!(ledger.poisoned && ledger.work.claims.is_empty() && ledger.work.owners.is_empty()); + assert!(ledger.bindings.is_empty()); + } + + #[test] + fn a_prior_poison_does_not_leave_later_accepted_work_owned() { + let batches = SparseBatches::new(71); + assert!(batches.add_dirty_pages([0x3_1000, 0x3_2000])); + let first = batches.seal(1, 1).unwrap().unwrap().accept().unwrap(); + let second = batches.seal(2, 1).unwrap().unwrap().accept().unwrap(); + let reservations = UploadReservations::new(71, 2, 256, 64); + let first = AcceptedCoordinatedUpload::new(reservations.reserve(0, 64).unwrap(), first); + let second = AcceptedCoordinatedUpload::new(reservations.reserve(1, 64).unwrap(), second); + drop(first); + assert!(matches!(second.publish(17), Err(CoordinatedPublishError::Batch(SparseBatchError::Poisoned)))); + let ledger = batches.ledger.lock().unwrap(); + assert!(ledger.poisoned && ledger.work.claims.is_empty() && ledger.work.owners.is_empty()); + assert!(ledger.bindings.is_empty()); + drop(ledger); + let reservations = reservations.0.lock().unwrap(); + assert!(reservations.poisoned && reservations.records.values().all(|r| r.state == UploadReservationState::Poisoned)); + } + + #[test] + fn coordinated_receipts_publish_exact_out_of_order_fence_prefix() { + let batches = SparseBatches::new(71); + assert!(batches.add_dirty_pages([0x2_1000, 0x2_2000])); + let observation = |page| upload_observation(page, (4, 9), 0xA5); + let first_lease = batches.seal(1, 1).unwrap().unwrap(); + let first_token = first_lease.token; + let second_lease = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + let first = CoordinatedSparseUploadPlan::build(first_lease, 71, 7, |page| Some(observation(page))).unwrap(); + let second = CoordinatedSparseUploadPlan::build(second_lease, 71, 7, |page| Some(observation(page))).unwrap(); + let reservations = UploadReservations::new(71, 2, 256, 64); + let second_receipt = commit_coordinated(second, &observation(0x2_2000), &reservations, 1, 11).unwrap(); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::WaitForReceipt(first_token))); + let first_receipt = commit_coordinated(first, &observation(0x2_1000), &reservations, 0, 8).unwrap(); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::Ready { through, required_fence: Some(11) })); + assert_eq!(reservations.complete(first_receipt), Ok(0)); + assert_eq!(reservations.complete(second_receipt), Ok(128)); + } + #[test] fn sparse_upload_plan_preserves_claim_order_intent_and_source_ranges() { let claims = SparseWorkClaims::new(29); From f910a402dc824efdf4c14f14fe7d06ed43cc4cf2 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:50:03 -0800 Subject: [PATCH 235/265] D3D12.X: time native title queue submissions Adapt the opt-in timing from upstream PR #1065 to the exact native chunks emitted by the current submission planner. Keep count and slowest duration/list count as one coherent sample in report.json; ordinary submissions read no clock. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 3 + crates/xcl/src/hle/d3d12x/real.rs | 99 ++++++++++++++++++++++++++++++- 2 files changed, 101 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ab1d4493ed..00c5320281 100644 --- a/README.md +++ b/README.md @@ -320,6 +320,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder barrier, copy and command-list lifecycle recording costs on the title's first observed submitting thread; it also enables the coarse trace. Use it only for a diagnostic run because every recorded call reads the clock and updates counters. + `XCL_GPU_TIMING=1` times each native title `ExecuteCommandLists` chunk on the CPU. The count and + slowest duration/list count are written to `report.json`; chunks taking at least 50 ms are logged + (`XCL_GPU_TIMING_MS` changes that threshold). It does not measure when the GPU finishes. - **Diagnostics for a bug report** (all off by default; set them in the environment of `xcl run`): - `XCL_RUN_SECONDS=n`: the title ends itself after `n` seconds, with the GPU drained and `xcl.log` and `report.json` written, so a run of a fixed length can be attached. A value that diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 46d6426251..7a6be9c158 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -168,6 +168,14 @@ pub struct D3d12Stats { /// DXIL cache and compiler statistics. #[serde(default)] pub dxil_cache: crate::gpu::recomp::dxc::CacheStats, + /// Native title `ExecuteCommandLists` chunks timed while `XCL_GPU_TIMING=1`, plus the CPU + /// duration and list count of the slowest chunk. This is not GPU execution time. + #[serde(default)] + pub submissions: u64, + #[serde(default)] + pub slowest_submission_ms: f64, + #[serde(default)] + pub slowest_submission_lists: usize, } static ADAPTER: Mutex<String> = Mutex::new(String::new()); @@ -178,6 +186,58 @@ static FAILED_PSO: AtomicU64 = AtomicU64::new(0); static FALLBACK_RS: AtomicU64 = AtomicU64::new(0); static TRANSLATED_PSO: AtomicU64 = AtomicU64::new(0); static TRANSLATE_ERRORS: Mutex<Vec<String>> = Mutex::new(Vec::new()); + +#[derive(Clone, Copy, Default)] +struct SubmissionTiming { + submissions: u64, + slowest_us: u64, + slowest_lists: usize, +} + +impl SubmissionTiming { + fn record(&mut self, us: u64, lists: usize) { + self.submissions = self.submissions.saturating_add(1); + if us > self.slowest_us { + self.slowest_us = us; + self.slowest_lists = lists; + } + } +} + +static SUBMISSION_TIMING: Mutex<SubmissionTiming> = Mutex::new(SubmissionTiming { + submissions: 0, + slowest_us: 0, + slowest_lists: 0, +}); + +fn gpu_timing_on_value(value: Option<&str>) -> bool { + value == Some("1") +} + +fn gpu_timing_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| gpu_timing_on_value(std::env::var("XCL_GPU_TIMING").ok().as_deref())) +} + +fn slow_submission_us_value(value: Option<&str>) -> u64 { + value.and_then(|value| value.parse::<u64>().ok()).unwrap_or(50).saturating_mul(1_000) +} + +fn slow_submission_us() -> u64 { + static US: OnceLock<u64> = OnceLock::new(); + *US.get_or_init(|| slow_submission_us_value(std::env::var("XCL_GPU_TIMING_MS").ok().as_deref())) +} + +fn note_submission_timing(elapsed: std::time::Duration, lists: usize, queue: *mut c_void) { + let us = elapsed.as_micros().min(u64::MAX as u128) as u64; + if let Ok(mut timing) = SUBMISSION_TIMING.lock() { + timing.record(us, lists); + } + if us >= slow_submission_us() { + crate::xlog_warn!("ExecuteCommandLists: {us} µs of CPU time for {lists} list(s), queue {queue:p}"); + } +} + /// XCL shader ABI root signature on the primary backend device (raw, kept for the process lifetime) static ABI_RS: AtomicUsize = AtomicUsize::new(0); static ABI_RS_DEV: AtomicUsize = AtomicUsize::new(0); @@ -428,6 +488,7 @@ pub fn stats() -> D3d12Stats { }) .unwrap_or_default(); let (presents, boundaries) = super::present::counters(); + let submission_timing = SUBMISSION_TIMING.lock().map(|timing| *timing).unwrap_or_default(); D3d12Stats { backend: format!("{:?}", super::backend()).to_lowercase(), adapter: ADAPTER.lock().map(|a| a.clone()).unwrap_or_default(), @@ -451,6 +512,9 @@ pub fn stats() -> D3d12Stats { translation_errors: TRANSLATE_ERRORS.lock().map(|e| e.clone()).unwrap_or_default(), background_pipelines: super::pso_async::counts(), dxil_cache: crate::gpu::recomp::dxc::cache_stats(), + submissions: submission_timing.submissions, + slowest_submission_ms: submission_timing.slowest_us as f64 / 1_000.0, + slowest_submission_lists: submission_timing.slowest_lists, } } @@ -9117,7 +9181,13 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis || { let _ = super::alloc_pool::note_resubmits(this, lists); }, - || f(this, lists.len() as u32, lists.as_ptr()), + || { + let started = gpu_timing_on().then(std::time::Instant::now); + f(this, lists.len() as u32, lists.as_ptr()); + if let Some(started) = started { + note_submission_timing(started.elapsed(), lists.len(), this); + } + }, ) { return (false, None); } @@ -9223,6 +9293,33 @@ unsafe fn report_dred_lists(head: *const D3D12_AUTO_BREADCRUMB_NODE, mut report: } } +#[cfg(test)] +mod submission_timing_tests { + use super::*; + + #[test] + fn submission_timing_keeps_one_exact_slowest_sample() { + let mut timing = SubmissionTiming::default(); + timing.record(20, 2); + timing.record(10, 9); + timing.record(30, 4); + assert_eq!((timing.submissions, timing.slowest_us, timing.slowest_lists), (3, 30, 4)); + } + + #[test] + fn submission_warning_threshold_is_bounded_and_defaults() { + assert!(gpu_timing_on_value(Some("1"))); + for value in [None, Some(""), Some("0"), Some("true"), Some(" 1")] { + assert!(!gpu_timing_on_value(value)); + } + assert_eq!(slow_submission_us_value(None), 50_000); + assert_eq!(slow_submission_us_value(Some("bad")), 50_000); + assert_eq!(slow_submission_us_value(Some("0")), 0); + assert_eq!(slow_submission_us_value(Some("17")), 17_000); + assert_eq!(slow_submission_us_value(Some("18446744073709551615")), u64::MAX); + } +} + #[cfg(test)] mod dred_tests { use super::*; From eac1a94116b518d83de139f23ac009b88f65c633 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:48:11 -0800 Subject: [PATCH 236/265] D3D12.X: model exact pipeline rehydration receipts Add an inert bounded registry which separates queue request outcomes from exact asynchronous completion. Accepted guards fail closed on cancellation or panic, and stale attempts cannot publish replacement generations. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 401 ++++++++++++++++++++++++- 1 file changed, 399 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 98c1aa125d..3a82f585f1 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1298,6 +1298,261 @@ pub(crate) fn observe_pressure_turn( ).line()) } +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RehydratePriority { Background, Foreground } + +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RehydrateRequestReceipt { Refused, Queued { priority: RehydratePriority } } + +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RehydrateCompletion { Reserved, Refused, Queued, Cancelled, Panicked, BuildFailed, Released, + Succeeded { replacement: LedgerNativeGeneration } } + +impl RehydrateCompletion { + fn terminal(self) -> bool { !matches!(self, Self::Reserved | Self::Queued) } +} + +#[allow(dead_code)] +#[derive(Clone)] +struct RehydrateAttemptToken { registry_instance: u64, slot: usize, slot_generation: u64, + serial: u64, attempt_generation: u64, evicted: EvictedBuildToken } + +mod rehydrate_success { + use super::*; + pub(super) struct Proof { attempt: RehydrateAttemptToken, build: Weak<Build>, recipe: Recipe, + replacement: NativeGeneration } + impl Proof { + pub(super) fn new(attempt: &RehydrateAttemptToken, build: &Arc<Build>, + replacement: &NativeGeneration) -> Option<Self> { + if !Weak::ptr_eq(&attempt.evicted.build, &Arc::downgrade(build)) { return None } + let recipe = build.recipe.as_ref()?; + let (current, residency) = recipe.pin_with_residency(build.real.load(Ordering::Acquire)); + (residency == Residency::Resident && current.as_ref().is_some_and(|current| current.same(replacement))).then(|| + Self { attempt: attempt.clone(), build: Arc::downgrade(build), recipe: recipe.clone(), replacement: replacement.clone() }) + } + pub(super) fn current(&self, attempt: &RehydrateAttemptToken) -> Option<Arc<Build>> { + if !self.attempt.exact(attempt) { return None } + let build = self.build.upgrade()?; + let recipe = build.recipe.as_ref()?; + (Arc::ptr_eq(&recipe.0, &self.recipe.0) && recipe.0.resident_generation.load(Ordering::Acquire) + == self.replacement.id()).then_some(build) + } + + pub(super) fn replacement(&self) -> LedgerNativeGeneration { self.replacement.ledger_identity() } + } +} + +impl RehydrateAttemptToken { + fn exact(&self, other: &Self) -> bool { + self.registry_instance == other.registry_instance + && self.slot == other.slot + && self.slot_generation == other.slot_generation + && self.serial == other.serial + && self.attempt_generation == other.attempt_generation + && self.evicted.exact(&other.evicted) + } +} + +struct RehydrateReceiptEntry { token: RehydrateAttemptToken, state: RehydrateCompletion, priority: RehydratePriority } +struct RehydrateReceiptSlot { generation: u64, entry: Option<RehydrateReceiptEntry> } +struct RehydrateReceiptInner<const N: usize> { serial: u64, exhausted: bool, slots: [RehydrateReceiptSlot; N] } + +/// Bounded truth about asynchronous rehydration attempts. Queue submission and pipeline building +/// happen outside this lock; accepting a queue request records only Queued, never success. +#[allow(dead_code)] +struct RehydrateReceiptRegistry<const N: usize> { instance: u64, inner: Mutex<RehydrateReceiptInner<N>> } + +#[allow(dead_code)] +#[derive(Clone)] +struct RehydrateReceiptRecord { token: RehydrateAttemptToken, state: RehydrateCompletion, priority: RehydratePriority } + +static NEXT_REHYDRATE_RECEIPT_INSTANCE: AtomicU64 = AtomicU64::new(1); + +#[allow(dead_code)] +impl<const N: usize> RehydrateReceiptRegistry<N> { + fn new() -> Option<Self> { + if N == 0 { return None } + let instance = allocate_evicted_ledger_instance(&NEXT_REHYDRATE_RECEIPT_INSTANCE)?; + Some(Self { instance, inner: Mutex::new(RehydrateReceiptInner { serial: 0, exhausted: false, + slots: std::array::from_fn(|_| RehydrateReceiptSlot { generation: 0, entry: None }) }) }) + } + + fn reserve<'a>(&'a self, evicted: &EvictedBuildToken) -> Option<RehydrateReceiptReservation<'a, N>> { + let mut inner = self.inner.lock().unwrap(); + if inner.exhausted { return None } + let slot = inner.slots.iter().position(|slot| slot.entry.is_none())?; + let Some(serial) = inner.serial.checked_add(1) else { + inner.exhausted = true; + return None; + }; + let Some(slot_generation) = inner.slots[slot].generation.checked_add(1) else { + inner.exhausted = true; + return None; + }; + let token = RehydrateAttemptToken { registry_instance: self.instance, slot, slot_generation, + serial, attempt_generation: serial, evicted: evicted.clone() }; + inner.serial = serial; + inner.slots[slot].generation = slot_generation; + inner.slots[slot].entry = Some(RehydrateReceiptEntry { + token: token.clone(), state: RehydrateCompletion::Reserved, priority: RehydratePriority::Background, + }); + Some(RehydrateReceiptReservation { registry: self, token, submitted: false }) + } + + fn publish(&self, token: &RehydrateAttemptToken, state: RehydrateCompletion) -> bool { + self.publish_checked(token, state) + } + + fn publish_checked(&self, token: &RehydrateAttemptToken, mut state: RehydrateCompletion) -> bool { + if !state.terminal() || matches!(state, RehydrateCompletion::Succeeded { .. }) { return false } + let live_build = token.evicted.build.upgrade(); + if live_build.is_none() { state = RehydrateCompletion::Released } + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + if !entry.token.exact(token) { return false } + let allowed = match state { + RehydrateCompletion::Refused => entry.state == RehydrateCompletion::Reserved, + RehydrateCompletion::Released => matches!(entry.state, RehydrateCompletion::Reserved | RehydrateCompletion::Queued), + RehydrateCompletion::Cancelled | RehydrateCompletion::Panicked + | RehydrateCompletion::BuildFailed => entry.state == RehydrateCompletion::Queued, + RehydrateCompletion::Succeeded { replacement } => entry.state == RehydrateCompletion::Queued + && replacement != entry.token.evicted.native, + _ => false, + }; + if !allowed { return false } + entry.state = state; + true + } + + fn publish_success(&self, token: &RehydrateAttemptToken, proof: &rehydrate_success::Proof) -> bool { + let Some(_live_build) = token.evicted.build.upgrade() else { + return self.publish(token, RehydrateCompletion::Released); + }; + let Some(_build) = proof.current(token) else { return false }; + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + let replacement = proof.replacement(); + if entry.state != RehydrateCompletion::Queued || !entry.token.exact(token) + || replacement == entry.token.evicted.native || proof.current(token).is_none() { return false } + entry.state = RehydrateCompletion::Succeeded { replacement }; true + } + + fn accept(&self, token: &RehydrateAttemptToken, priority: RehydratePriority) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + if entry.state != RehydrateCompletion::Reserved || !entry.token.exact(token) { return false } + entry.state = RehydrateCompletion::Queued; entry.priority = priority; true + } + + fn promote(&self, token: &RehydrateAttemptToken) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + if entry.state != RehydrateCompletion::Queued || !entry.token.exact(token) { return false } + entry.priority = RehydratePriority::Foreground; true + } + + fn records(&self, limit: usize) -> Vec<RehydrateReceiptRecord> { + let mut inner = self.inner.lock().unwrap(); + let mut records = Vec::new(); + for slot in &mut inner.slots { + let Some(entry) = slot.entry.as_mut() else { continue }; + if !entry.state.terminal() && entry.token.evicted.build.strong_count() == 0 { + entry.state = RehydrateCompletion::Released; + } + if records.len() == limit { break } + records.push(RehydrateReceiptRecord { + token: entry.token.clone(), state: entry.state, priority: entry.priority, + }); + } + records + } + + fn retire(&self, token: &RehydrateAttemptToken) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(slot) = inner.slots.get_mut(token.slot) else { return false }; + if slot.entry.as_ref().is_none_or(|entry| !entry.state.terminal() || !entry.token.exact(token)) { + return false; + } + slot.entry = None; + true + } +} + +#[allow(dead_code)] +struct RehydrateReceiptReservation<'a, const N: usize> { registry: &'a RehydrateReceiptRegistry<N>, + token: RehydrateAttemptToken, submitted: bool } + +#[allow(dead_code)] +impl<'a, const N: usize> RehydrateReceiptReservation<'a, N> { + fn refused(mut self) -> Option<(RehydrateRequestReceipt, RehydrateAttemptToken)> { + self.submitted = self.registry.publish(&self.token, RehydrateCompletion::Refused); + self.submitted.then(|| (RehydrateRequestReceipt::Refused, self.token.clone())) + } + + fn accepted(mut self, priority: RehydratePriority) -> Option<(RehydrateRequestReceipt, RehydrateQueuedReceipt<'a, N>)> { + if !self.registry.accept(&self.token, priority) { + return None; + } + self.submitted = true; + let token = self.token.clone(); + Some((RehydrateRequestReceipt::Queued { priority }, RehydrateQueuedReceipt { + registry: self.registry, token, completed: false, + })) + } +} + +impl<const N: usize> Drop for RehydrateReceiptReservation<'_, N> { + fn drop(&mut self) { + if !self.submitted { + let mut inner = self.registry.inner.lock().unwrap(); + if let Some(slot) = inner.slots.get_mut(self.token.slot) { + if slot.entry.as_ref().is_some_and(|entry| { + entry.state == RehydrateCompletion::Reserved && entry.token.exact(&self.token) + }) { + slot.entry = None; + } + } + } + } +} + +#[allow(dead_code)] +struct RehydrateQueuedReceipt<'a, const N: usize> { registry: &'a RehydrateReceiptRegistry<N>, + token: RehydrateAttemptToken, completed: bool } + +#[allow(dead_code)] +impl<const N: usize> RehydrateQueuedReceipt<'_, N> { + fn replacement(&self, build: &Arc<Build>, replacement: &NativeGeneration) -> Option<rehydrate_success::Proof> { + rehydrate_success::Proof::new(&self.token, build, replacement) + } + + fn complete(mut self, completion: RehydrateCompletion) -> bool { + self.completed = self.registry.publish(&self.token, completion); + self.completed + } + + fn complete_success(mut self, proof: rehydrate_success::Proof) -> bool { + self.completed = self.registry.publish_success(&self.token, &proof); + self.completed + } +} + +impl<const N: usize> Drop for RehydrateQueuedReceipt<'_, N> { + fn drop(&mut self) { + if !self.completed { + let completion = if std::thread::panicking() { + RehydrateCompletion::Panicked + } else { + RehydrateCompletion::Cancelled + }; + let _ = self.registry.publish(&self.token, completion); + } + } +} + fn forget_in_flight(build: &Arc<Build>) { let Some(key) = &build.compute_key else { return }; let mut registry = IN_FLIGHT.lock().unwrap(); @@ -1703,6 +1958,7 @@ impl<T> GenerationSlot<T> { struct RecipeInner { build: Box<dyn Fn() -> usize + Send + Sync>, generation: Mutex<GenerationSlot<ID3D12PipelineState>>, + resident_generation: AtomicU64, rebuild: Mutex<RebuildState>, rebuild_done: Condvar, } @@ -1840,6 +2096,7 @@ impl Recipe { Self(Arc::new(RecipeInner { build: Box::new(build), generation: Mutex::new(GenerationSlot::default()), + resident_generation: AtomicU64::new(0), rebuild: Mutex::new(RebuildState::default()), rebuild_done: Condvar::new(), })) @@ -1854,7 +2111,10 @@ impl Recipe { fn publish(&self, raw: usize) -> (NativeGeneration, Option<NativeGeneration>) { let p = raw as *mut std::ffi::c_void; let owner = unsafe { ID3D12PipelineState::from_raw_borrowed(&p) }.expect("non-null pipeline result").clone(); - let (generation, replaced) = self.0.generation.lock().unwrap().publish(raw, owner); + let mut slot = self.0.generation.lock().unwrap(); + let (generation, replaced) = slot.publish(raw, owner); + self.0.resident_generation.store(generation.id, Ordering::Release); + drop(slot); (NativeGeneration(generation), replaced.map(NativeGeneration)) } @@ -1867,11 +2127,16 @@ impl Recipe { let mut generation = self.0.generation.lock().unwrap(); if generation.resident.is_none() { generation.residency = Residency::Failed; + self.0.resident_generation.store(0, Ordering::Release); } } fn detach_current(&self, raw: usize) -> Option<NativeGeneration> { - self.0.generation.lock().unwrap().detach(raw).map(NativeGeneration) + let mut slot = self.0.generation.lock().unwrap(); + let detached = slot.detach(raw).map(NativeGeneration); + if detached.is_some() { self.0.resident_generation.store(0, Ordering::Release) } + drop(slot); + detached } fn initial_job(&self) -> Job { @@ -2834,6 +3099,138 @@ mod used_tests { assert_eq!(allocate_evicted_ledger_instance(&instance), None); } + fn receipt_evicted(build: &Arc<Build>, id: u64) -> EvictedBuildToken { + EvictedBuildLedger::<1>::new(id + 100).unwrap() + .reserve(build, ledger_native(id)).unwrap().arm_detach().unwrap() + } + + #[test] + fn rehydrate_receipts_separate_request_from_completion() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 20); + let registry = RehydrateReceiptRegistry::<3>::new().unwrap(); + let (request, refused) = registry.reserve(&evicted).unwrap().refused().unwrap(); + assert_eq!(request, RehydrateRequestReceipt::Refused); + assert_eq!(registry.records(3)[0].state, RehydrateCompletion::Refused); assert!(registry.retire(&refused)); + let (request, queued) = registry.reserve(&evicted).unwrap() + .accepted(RehydratePriority::Background).unwrap(); + assert_eq!(request, RehydrateRequestReceipt::Queued { priority: RehydratePriority::Background }); + let queued_token = queued.token.clone(); + assert_eq!(registry.records(3)[0].state, RehydrateCompletion::Queued, + "queue acceptance was treated as successful completion"); + assert!(registry.promote(&queued_token)); + assert_eq!(registry.records(3)[0].priority, RehydratePriority::Foreground); + drop(queued); + assert_eq!(registry.records(3)[0].state, RehydrateCompletion::Cancelled); + } + + #[test] + fn rehydrate_receipts_report_panic_failure_and_release() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 21); + let registry = RehydrateReceiptRegistry::<4>::new().unwrap(); + let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let (_, _queued) = registry.reserve(&evicted).unwrap() + .accepted(RehydratePriority::Foreground).unwrap(); + panic!("queued build panic"); + })); + assert!(panic_result.is_err()); assert_eq!(registry.records(4)[0].state, RehydrateCompletion::Panicked); + let (_, failed) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + assert!(failed.complete(RehydrateCompletion::BuildFailed)); + let (_, released) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + assert!(released.complete(RehydrateCompletion::Released)); + } + + #[test] + fn rehydrate_receipts_reject_duplicate_stale_and_release_races() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 23); + let registry = RehydrateReceiptRegistry::<1>::new().unwrap(); + let reservation = registry.reserve(&evicted).unwrap(); + assert!(!registry.publish(&reservation.token, RehydrateCompletion::BuildFailed), + "a completion published before queue acceptance"); + let (_, success) = reservation.accepted(RehydratePriority::Background).unwrap(); + let old = success.token.clone(); + assert!(!registry.publish(&old, RehydrateCompletion::Succeeded { replacement: evicted.native }), + "the evicted native generation was reported as its own replacement"); + assert!(success.complete(RehydrateCompletion::BuildFailed)); + assert!(!registry.publish(&old, RehydrateCompletion::BuildFailed), "a duplicate completion mutated state"); + assert!(registry.retire(&old)); + let (_, racing) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + let current = racing.token.clone(); + assert_ne!(old.attempt_generation, current.attempt_generation); + assert!(!registry.publish(&old, RehydrateCompletion::Panicked), "a stale attempt mutated its replacement"); + let replacement_build = ledger_build(); + let mut reused = current.clone(); + reused.evicted.build = Arc::downgrade(&replacement_build); + assert!(!registry.publish(&reused, RehydrateCompletion::BuildFailed), + "a different build allocation completed the current attempt"); + assert!(registry.publish(¤t, RehydrateCompletion::Released)); + assert!(!racing.complete(RehydrateCompletion::Succeeded { replacement: ledger_native(25) }), + "success won after release completed the attempt"); + assert_eq!(registry.records(1)[0].state, RehydrateCompletion::Released); + } + + #[test] + fn rehydrate_success_requires_exact_current_build_generation_and_liveness() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let job = build.job.lock().unwrap().take().unwrap(); complete(&build, job()); + let replacement = recipe.pin_with_residency(raw).0.unwrap(); let evicted = receipt_evicted(&build, 27); + let registry = RehydrateReceiptRegistry::<1>::new().unwrap(); + let (_, success) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + assert!(success.replacement(&ledger_build(), &replacement).is_none(), "another build proved replacement"); + assert!(!registry.publish(&success.token, RehydrateCompletion::Succeeded { replacement: ledger_native(99) }), + "a forged native identity bypassed replacement proof"); + let proof = success.replacement(&build, &replacement).unwrap(); let token = success.token.clone(); + let mut newer_native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let newer_raw = &mut newer_native as *mut RebuildFakePso as usize; + let (newer, replaced) = recipe.publish(newer_raw); let old_raw = build.real.swap(newer_raw, Ordering::AcqRel); + release(old_raw); drop(replaced); + assert!(!success.complete_success(proof), "generation A completed after B became current"); + assert_eq!(registry.records(1)[0].state, RehydrateCompletion::Cancelled); assert!(registry.retire(&token)); + let (_, success) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + let proof = success.replacement(&build, &newer).unwrap(); let token = success.token.clone(); + assert!(success.complete_success(proof)); + assert_eq!(registry.records(1)[0].state, + RehydrateCompletion::Succeeded { replacement: newer.ledger_identity() }); + assert!(registry.retire(&token)); + let (_, expired) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + let proof = expired.replacement(&build, &newer).unwrap(); + let raw_owner = build.real.swap(0, Ordering::AcqRel); + drop(build); release(raw_owner); + assert!(expired.complete_success(proof)); + assert_eq!(registry.records(1)[0].state, RehydrateCompletion::Released); + drop(replacement); drop(newer); drop(recipe); assert_eq!(native.refs.load(Ordering::Relaxed), 0); + assert_eq!(newer_native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn rehydrate_guard_drop_resolves_expired_build_as_released() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 28); + let registry = RehydrateReceiptRegistry::<1>::new().unwrap(); + let (_, queued) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + drop(build); + drop(queued); + assert_eq!(registry.records(1)[0].state, RehydrateCompletion::Released); + } + + #[test] + fn rehydrate_receipt_capacity_and_counters_fail_before_queue() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 26); + let registry = RehydrateReceiptRegistry::<1>::new().unwrap(); + let reservation = registry.reserve(&evicted).unwrap(); + assert!(registry.reserve(&evicted).is_none()); + drop(reservation); assert!(registry.records(1).is_empty()); + registry.inner.lock().unwrap().serial = u64::MAX; + assert!(registry.reserve(&evicted).is_none()); + assert!(registry.inner.lock().unwrap().exhausted); + let generation = RehydrateReceiptRegistry::<1>::new().unwrap(); + generation.inner.lock().unwrap().slots[0].generation = u64::MAX; + assert!(generation.reserve(&evicted).is_none()); + assert!(generation.inner.lock().unwrap().exhausted); + } + #[test] fn pressure_observer_bounds_inspection_and_requeues_every_resident() { let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; From 10da931f4074c1abf6c40f85f0a8a78aae42c33b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:59:18 -0800 Subject: [PATCH 237/265] Tests: add a dependency-free benchmark harness Provide warmup, sampled timing, throughput reporting, substring filtering, batched inputs, and a fast --test smoke mode using only std. This avoids introducing a dependency graph with licences incompatible with GPL-2.0-only. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/benches/support/mod.rs | 265 ++++++++++++++++++++++++++++++ 1 file changed, 265 insertions(+) create mode 100644 crates/xcl/benches/support/mod.rs diff --git a/crates/xcl/benches/support/mod.rs b/crates/xcl/benches/support/mod.rs new file mode 100644 index 0000000000..74c6d6fee7 --- /dev/null +++ b/crates/xcl/benches/support/mod.rs @@ -0,0 +1,265 @@ +#![allow(dead_code)] + +use std::fmt::Display; +use std::hint::black_box; +use std::time::{Duration, Instant}; + +#[derive(Clone)] +struct Config { + test: bool, + filter: Option<String>, +} + +pub struct Criterion { + config: Config, + ran: usize, +} + +pub struct BenchmarkGroup<'a> { + criterion: &'a mut Criterion, + name: String, + throughput: Option<Throughput>, + sample_size: usize, + measurement_time: Duration, +} + +pub struct Bencher { + name: String, + test: bool, + throughput: Option<Throughput>, + sample_size: usize, + measurement_time: Duration, +} + +#[derive(Clone, Copy)] +pub enum Throughput { + Bytes(u64), + Elements(u64), +} + +pub enum BatchSize { + SmallInput, +} + +pub struct BenchmarkId(String); + +fn median(sorted: &[f64]) -> f64 { + let middle = sorted.len() / 2; + if sorted.len() % 2 == 0 { + (sorted[middle - 1] + sorted[middle]) / 2.0 + } else { + sorted[middle] + } +} + +fn test_helpers() { + assert_eq!(median(&[1.0, 3.0]), 2.0); + assert_eq!(median(&[1.0, 4.0, 9.0]), 4.0); +} + +impl BenchmarkId { + pub fn new(name: impl Display, parameter: impl Display) -> Self { + Self(format!("{name}/{parameter}")) + } + + pub fn from_parameter(parameter: impl Display) -> Self { + Self(parameter.to_string()) + } +} + +impl Display for BenchmarkId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} + +impl Criterion { + fn from_args() -> Self { + let mut test = false; + let mut filter = None; + for argument in std::env::args().skip(1) { + if argument == "--test" { + test = true; + } else if !argument.starts_with('-') && filter.is_none() { + filter = Some(argument); + } + } + Self { config: Config { test, filter }, ran: 0 } + } + + pub fn benchmark_group<'a>(&'a mut self, name: &str) -> BenchmarkGroup<'a> { + BenchmarkGroup { + criterion: self, + name: name.to_owned(), + throughput: None, + sample_size: 30, + measurement_time: Duration::from_secs(2), + } + } + + pub fn bench_function(&mut self, name: &str, routine: impl FnMut(&mut Bencher)) { + self.run_one(name.to_owned(), None, 30, Duration::from_secs(2), routine); + } + + fn run_one( + &mut self, + name: String, + throughput: Option<Throughput>, + sample_size: usize, + measurement_time: Duration, + mut routine: impl FnMut(&mut Bencher), + ) { + if self.config.filter.as_ref().is_some_and(|filter| !name.contains(filter)) { + return; + } + self.ran += 1; + routine(&mut Bencher { + name, + test: self.config.test, + throughput, + sample_size: sample_size.max(3), + measurement_time, + }); + } +} + +impl BenchmarkGroup<'_> { + pub fn throughput(&mut self, throughput: Throughput) { + self.throughput = Some(throughput); + } + + pub fn sample_size(&mut self, sample_size: usize) { + self.sample_size = sample_size; + } + + pub fn measurement_time(&mut self, measurement_time: Duration) { + self.measurement_time = measurement_time; + } + + pub fn bench_function(&mut self, name: &str, routine: impl FnMut(&mut Bencher)) { + let name = format!("{}/{}", self.name, name); + self.criterion.run_one( + name, self.throughput, self.sample_size, self.measurement_time, routine, + ); + } + + pub fn bench_with_input<T: ?Sized>( + &mut self, + id: BenchmarkId, + input: &T, + mut routine: impl FnMut(&mut Bencher, &T), + ) { + let name = format!("{}/{}", self.name, id); + self.criterion.run_one( + name, + self.throughput, + self.sample_size, + self.measurement_time, + |bencher| routine(bencher, input), + ); + } + + pub fn finish(self) {} +} + +impl Bencher { + pub fn iter<R>(&mut self, mut routine: impl FnMut() -> R) { + if self.test { + let _ = black_box(routine()); + println!("test {} ... ok", self.name); + return; + } + self.measure_iterations(|iterations| { + let started = Instant::now(); + for _ in 0..iterations { + let _ = black_box(routine()); + } + started.elapsed() + }); + } + + pub fn iter_batched<I, R>( + &mut self, + mut setup: impl FnMut() -> I, + mut routine: impl FnMut(I) -> R, + _batch_size: BatchSize, + ) { + if self.test { + let input = setup(); + let _ = black_box(routine(input)); + println!("test {} ... ok", self.name); + return; + } + self.measure_iterations(|iterations| { + let mut elapsed = Duration::ZERO; + let mut remaining = iterations; + while remaining != 0 { + let batch = remaining.min(1_024) as usize; + let inputs: Vec<_> = (0..batch).map(|_| setup()).collect(); + let started = Instant::now(); + for input in inputs { + let _ = black_box(routine(input)); + } + elapsed += started.elapsed(); + remaining -= batch as u64; + } + elapsed + }); + } + + fn measure_iterations(&self, mut run: impl FnMut(u64) -> Duration) { + let warmup = self.measurement_time.div_f64(10.0).min(Duration::from_millis(100)); + let mut iterations = 1u64; + let elapsed = loop { + let elapsed = run(iterations); + if elapsed >= warmup || iterations >= 1 << 40 { + break elapsed; + } + let scale = (warmup.as_secs_f64() / elapsed.as_secs_f64().max(1e-9)).ceil() as u64; + iterations = iterations.saturating_mul(scale.clamp(2, 10)).min(1 << 40); + }; + + let seconds_per_iteration = elapsed.as_secs_f64() / iterations as f64; + let target_sample = self.measurement_time.as_secs_f64() / self.sample_size as f64; + let sample_iterations = (target_sample / seconds_per_iteration.max(1e-12)) + .ceil() + .clamp(1.0, (1u64 << 40) as f64) as u64; + let mut samples = Vec::with_capacity(self.sample_size); + for _ in 0..self.sample_size { + samples.push(run(sample_iterations).as_secs_f64() / sample_iterations as f64); + } + samples.sort_unstable_by(f64::total_cmp); + let median = median(&samples); + let mean = samples.iter().sum::<f64>() / samples.len() as f64; + let minimum = samples[0]; + print!( + "bench {}: median {:.1} ns/iter, mean {:.1}, min {:.1}", + self.name, + median * 1e9, + mean * 1e9, + minimum * 1e9, + ); + if let Some(throughput) = self.throughput { + let (amount, unit) = match throughput { + Throughput::Bytes(amount) => (amount, "B/s"), + Throughput::Elements(amount) => (amount, "elem/s"), + }; + print!(", {:.1} {unit}", amount as f64 / median.max(1e-12)); + } + println!(); + } +} + +pub fn run(groups: &[fn(&mut Criterion)]) { + let mut criterion = Criterion::from_args(); + if criterion.config.test { + test_helpers(); + } + for group in groups { + group(&mut criterion); + } + if criterion.ran == 0 { + eprintln!("no benchmark matched the requested filter"); + std::process::exit(2); + } +} From 895b6e3efc47c6ef80ea363c7a93604e134c236a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 04:59:51 -0800 Subject: [PATCH 238/265] Tests: add synthetic benchmark foundation Adapt the generated inputs and benchmark IDs from upstream PR #1148 to the dependency-free harness. Cover RDNA2 decode, descriptors, parsers, shader-pack scans, and PE parsing without game data. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 7 ++ crates/xcl/Cargo.toml | 8 ++ crates/xcl/benches/core.rs | 36 +++++++ crates/xcl/benches/formats.rs | 182 ++++++++++++++++++++++++++++++++++ 4 files changed, 233 insertions(+) create mode 100644 crates/xcl/benches/core.rs create mode 100644 crates/xcl/benches/formats.rs diff --git a/README.md b/README.md index 00c5320281..556a644068 100644 --- a/README.md +++ b/README.md @@ -412,8 +412,15 @@ labelled as missing; it does not infer significance or percentages. .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace .\scripts\perf-run.tests.ps1 # cold/warm runner fixture (no game is run) .\scripts\perf-compare.tests.ps1 # comparison fixture (synthetic artifacts) +cargo bench -p xcl # synthetic performance benchmarks +cargo bench -p xcl --bench core # run one benchmark target ``` +Benchmarks use generated inputs and public XCL APIs; they do not require game files or a title +executable. The dependency-free harness prints median, mean and minimum time plus throughput; a +positional substring selects benchmarks, and `cargo bench -p xcl -- --test` runs every closure once +as a fast smoke check. + Unit tests, an end-to-end test with our own "console title" (`tests/testtitle`) and GPU tests (D3D12, SM 6.6; skipped without a GPU / DXC; `XCL_ADAPTER=1` or `XCL_ADAPTER=radeon` picks another adapter than the first high-performance one, for titles too). A GPU test that cannot run on diff --git a/crates/xcl/Cargo.toml b/crates/xcl/Cargo.toml index c3b23a1b8b..5b668f1645 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -68,3 +68,11 @@ features = [ "Win32_UI_Controls_Dialogs", "Win32_UI_WindowsAndMessaging", ] + +[[bench]] +name = "core" +harness = false + +[[bench]] +name = "formats" +harness = false diff --git a/crates/xcl/benches/core.rs b/crates/xcl/benches/core.rs new file mode 100644 index 0000000000..1de00df098 --- /dev/null +++ b/crates/xcl/benches/core.rs @@ -0,0 +1,36 @@ +mod support; + +use std::hint::black_box; +use support::Criterion; + +fn core_benches(c: &mut Criterion) { + let encoded = xcl::gpu::rdna2::encode( + "V_ADD_F32", + "ENC_VOP2", + &[("VDST", 1), ("SRC0", 258), ("VSRC1", 3)], + None, + ) + .expect("the built-in instruction table must encode V_ADD_F32"); + + c.bench_function("rdna2/decode_vop2", |b| { + b.iter(|| { + black_box( + xcl::gpu::rdna2::decode(black_box(&encoded), 0) + .expect("benchmark instruction must decode"), + ); + }); + }); + + c.bench_function("descriptor/component_mapping", |b| { + b.iter(|| { + black_box(xcl::gpu::desc::component_mapping( + black_box([4, 5, 6, 7]), + black_box([0, 1, 2, 3]), + )); + }); + }); +} + +fn main() { + support::run(&[core_benches]); +} diff --git a/crates/xcl/benches/formats.rs b/crates/xcl/benches/formats.rs new file mode 100644 index 0000000000..a6c1730c91 --- /dev/null +++ b/crates/xcl/benches/formats.rs @@ -0,0 +1,182 @@ +mod support; + +use std::hint::black_box; +use std::time::Duration; +use support::{BenchmarkId, Criterion, Throughput}; +use xcl::gpu::{desc, pack, rdna2}; +use xcl::pe::{Layout, Pe}; + +fn instruction() -> Vec<u8> { + rdna2::encode( + "V_ADD_F32", + "ENC_VOP2", + &[("VDST", 1), ("SRC0", 128), ("VSRC1", 2)], + None, + ) + .expect("benchmark instruction must encode") +} + +fn rdna2_benches(c: &mut Criterion) { + let inst = instruction(); + let mut group = c.benchmark_group("rdna2_instruction"); + group.throughput(Throughput::Elements(1)); + group.bench_function("encode", |b| { + b.iter(|| { + rdna2::encode( + black_box("V_ADD_F32"), + black_box("ENC_VOP2"), + black_box(&[("VDST", 1), ("SRC0", 128), ("VSRC1", 2)]), + None, + ) + .unwrap() + }) + }); + group.bench_function("decode", |b| { + b.iter(|| rdna2::decode(black_box(&inst), black_box(0x1_0000)).unwrap()) + }); + let decoded = rdna2::decode(&inst, 0x1_0000).unwrap(); + group.bench_function("format", |b| b.iter(|| rdna2::format(black_box(&decoded)))); + group.bench_function("register_uses", |b| { + b.iter(|| { + ( + rdna2::sgpr_uses(black_box(&decoded)), + rdna2::vgpr_uses(black_box(&decoded)), + ) + }) + }); + group.finish(); + + let mut group = c.benchmark_group("rdna2_stream"); + for instructions in [64usize, 1024, 16_384] { + let code = inst.repeat(instructions); + group.throughput(Throughput::Bytes(code.len() as u64)); + group.bench_with_input( + BenchmarkId::new("disassemble", instructions), + &code, + |b, code| b.iter(|| rdna2::disassemble(black_box(code), 0, false)), + ); + } + group.finish(); + + let mut group = c.benchmark_group("rdna2_program_scan"); + for bytes in [4 * 1024usize, 256 * 1024, 4 * 1024 * 1024] { + let mut blob = vec![0x5au8; bytes]; + // s_endpgm is enough to exercise the scanner's candidate handling without title data. + for at in (0..bytes.saturating_sub(4)).step_by(256) { + blob[at..at + 4].copy_from_slice(&0xbf81_0000u32.to_le_bytes()); + } + group.throughput(Throughput::Bytes(bytes as u64)); + group.bench_with_input(BenchmarkId::from_parameter(bytes), &blob, |b, blob| { + b.iter(|| rdna2::find_programs(black_box(blob))) + }); + } + group.finish(); +} + +fn descriptor_benches(c: &mut Criterion) { + let buffer = desc::buffer_words(0x1_2345_6780, 16, 65_536, 32); + let image = desc::xcl_image_for_view(17, 10, desc::ImageType::D2, 1920, 1080, 1, 11); + let sampler = [0x0000_1000, 0x0000_0000, 0x0000_0000, 0x0000_0000]; + let mut group = c.benchmark_group("gpu_descriptors"); + group.throughput(Throughput::Elements(1)); + group.bench_function("decode_buffer", |b| { + b.iter(|| desc::buffer(black_box(&buffer))) + }); + group.bench_function("decode_image", |b| { + b.iter(|| desc::image(black_box(&image))) + }); + group.bench_function("image_to_d3d12", |b| { + let decoded = desc::image(&image).unwrap(); + b.iter(|| desc::image_d3d12(black_box(&decoded))) + }); + group.bench_function("sampler_to_d3d12", |b| { + b.iter(|| desc::sampler_d3d12(black_box(&sampler), black_box(false))) + }); + group.finish(); +} + +fn manifest_and_config_benches(c: &mut Criterion) { + let languages = (0..64) + .map(|i| format!(r#"<Resource Language="lang-{i}"/>"#)) + .collect::<String>(); + let xml = format!( + r#"<Game configVersion="1"><PersistentLocalStorage><SizeMB>4096</SizeMB></PersistentLocalStorage><VirtualMachine><XboxLockhartTitleMemory>Standard</XboxLockhartTitleMemory><XboxAnacondaTitleMemory>Advanced</XboxAnacondaTitleMemory></VirtualMachine><TitleId>12345678</TitleId><Resources>{languages}</Resources></Game>"# + ); + let config = toml::to_string(&xcl::config::Config::default()).unwrap(); + let mut group = c.benchmark_group("text_formats"); + group.throughput(Throughput::Bytes(xml.len() as u64)); + group.bench_function("manifest_xml", |b| { + b.iter(|| xcl::manifest::parse(black_box(&xml))) + }); + group.throughput(Throughput::Bytes(config.len() as u64)); + group.bench_function("config_toml", |b| { + b.iter(|| toml::from_str::<xcl::config::Config>(black_box(&config)).unwrap()) + }); + group.finish(); +} + +fn record(name: &str, payload: &[u8]) -> Vec<u8> { + let compressed = miniz_oxide::deflate::compress_to_vec(payload, 6); + let mut out = vec![(name.len() + 1) as u8]; + out.extend_from_slice(name.as_bytes()); + out.push(0); + out.push(50); + for value in [ + compressed.len() as u32, + 0, + compressed.len() as u32, + payload.len() as u32, + ] { + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&compressed); + out +} + +fn pack_benches(c: &mut Criterion) { + let payload = (0..16 * 1024).map(|i| (i % 251) as u8).collect::<Vec<_>>(); + let one = record("CS_SyntheticBenchmark", &payload); + let mut archive = b"9FPR".to_vec(); + archive.resize(4096, 0xa5); + for i in 0..256 { + archive.extend_from_slice(&record(&format!("CS_Synthetic_{i:04}"), &payload)); + archive.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); + } + archive.extend_from_slice(&[0; 40]); + let records = pack::scan(&one, 0); + assert_eq!(records.len(), 1); + + let mut group = c.benchmark_group("rpf_records"); + group.sample_size(20); + group.measurement_time(Duration::from_secs(4)); + group.throughput(Throughput::Bytes(archive.len() as u64)); + group.bench_function("scan_256_records", |b| { + b.iter(|| pack::scan(black_box(&archive), 0)) + }); + group.throughput(Throughput::Bytes(payload.len() as u64)); + group.bench_function("inflate_16k", |b| { + b.iter(|| pack::inflate(black_box(&one), black_box(&records[0])).unwrap()) + }); + group.finish(); +} + +fn pe_benches(c: &mut Criterion) { + let exe = std::env::current_exe().expect("benchmark executable path"); + let bytes = std::fs::read(exe).expect("benchmark executable bytes"); + let mut group = c.benchmark_group("pe"); + group.throughput(Throughput::Bytes(bytes.len() as u64)); + group.bench_function("parse_benchmark_executable", |b| { + b.iter(|| Pe::parse(black_box(&bytes), Layout::File).unwrap()) + }); + group.finish(); +} + +fn main() { + support::run(&[ + rdna2_benches, + descriptor_benches, + manifest_and_config_benches, + pack_benches, + pe_benches, + ]); +} From f6577375b9460228627fb284fc65a8577777da8d Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:00:19 -0800 Subject: [PATCH 239/265] Tests: benchmark runtime and shader hot paths Adapt upstream PR #1152 to the dependency-free harness for shader decoding and translation, mesh-wave analysis, descriptor conversion, configuration, utility, and VFS paths. Count terminal S_ENDPGM instructions in throughput. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/Cargo.toml | 8 ++ crates/xcl/benches/gpu_cpu.rs | 173 ++++++++++++++++++++++++++++ crates/xcl/benches/runtime.rs | 205 ++++++++++++++++++++++++++++++++++ 3 files changed, 386 insertions(+) create mode 100644 crates/xcl/benches/gpu_cpu.rs create mode 100644 crates/xcl/benches/runtime.rs diff --git a/crates/xcl/Cargo.toml b/crates/xcl/Cargo.toml index 5b668f1645..42aa7a365b 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -76,3 +76,11 @@ harness = false [[bench]] name = "formats" harness = false + +[[bench]] +name = "gpu_cpu" +harness = false + +[[bench]] +name = "runtime" +harness = false diff --git a/crates/xcl/benches/gpu_cpu.rs b/crates/xcl/benches/gpu_cpu.rs new file mode 100644 index 0000000000..7bdf2079df --- /dev/null +++ b/crates/xcl/benches/gpu_cpu.rs @@ -0,0 +1,173 @@ +mod support; + +use std::hint::black_box; +use support::{BenchmarkId, Criterion, Throughput}; +use xcl::gpu::{desc, rdna2, recomp, shader, xbox}; + +const VGPR0: u64 = 256; + +fn instruction(name: &str, encoding: &str, fields: &[(&str, u64)]) -> Vec<u8> { + rdna2::encode(name, encoding, fields, None).unwrap() +} + +fn arithmetic_program(instructions: usize) -> Vec<u8> { + let add = instruction( + "V_ADD_NC_U32", + "ENC_VOP2", + &[("VDST", 1), ("SRC0", VGPR0 + 2), ("VSRC1", 3)], + ); + let xor = instruction( + "V_XOR_B32", + "ENC_VOP2", + &[("VDST", 4), ("SRC0", VGPR0 + 1), ("VSRC1", 5)], + ); + let mut code = Vec::with_capacity(instructions * 4 + 4); + for i in 0..instructions { + code.extend(if i & 1 == 0 { &add } else { &xor }); + } + code.extend(instruction("S_ENDPGM", "ENC_SOPP", &[])); + code +} + +fn branch_program(blocks: usize) -> Vec<u8> { + let mov = instruction("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)]); + let branch = instruction("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 1)]); + let add = instruction( + "V_ADD_NC_U32", + "ENC_VOP2", + &[("VDST", 1), ("SRC0", VGPR0 + 2), ("VSRC1", 3)], + ); + let mut code = Vec::with_capacity(blocks * 12 + 4); + for _ in 0..blocks { + code.extend(&mov); + code.extend(&branch); + code.extend(&add); + } + code.extend(instruction("S_ENDPGM", "ENC_SOPP", &[])); + code +} + +fn rdna2_frontend(c: &mut Criterion) { + let code = arithmetic_program(1024); + let mesh_control_flow = branch_program(256); + let mut group = c.benchmark_group("rdna2_frontend"); + group.throughput(Throughput::Bytes(code.len() as u64)); + group.bench_function("decode_stream", |b| { + b.iter(|| { + let mut offset = 0; + while offset < code.len() { + let decoded = rdna2::decode(black_box(&code[offset..]), offset as u64).unwrap(); + offset += black_box(decoded.len); + } + black_box(offset) + }) + }); + group.bench_function("disassemble", |b| { + b.iter(|| black_box(rdna2::disassemble(black_box(&code), 0, false))) + }); + group.bench_function("wave_hazard_scan", |b| { + b.iter(|| black_box(recomp::wave_hazards(black_box(&code)))) + }); + group.bench_function("geometry_wave32_hazard_scan", |b| { + b.iter(|| black_box(recomp::geometry_wave32_hazards(black_box(&code)))) + }); + group.throughput(Throughput::Bytes(mesh_control_flow.len() as u64)); + group.bench_function("mesh_wave_analysis", |b| { + b.iter(|| black_box(recomp::mesh_wave::analyze(black_box(&mesh_control_flow)))) + }); + group.finish(); +} + +fn translate(c: &mut Criterion) { + let mut group = c.benchmark_group("recompiler_translate"); + group.sample_size(20); + for size in [16usize, 64, 256] { + let code = arithmetic_program(size); + group.throughput(Throughput::Elements((size + 1) as u64)); + group.bench_with_input(BenchmarkId::new("linear", size), &code, |b, code| { + b.iter(|| { + let translated = + recomp::translate(black_box(code), black_box(&recomp::Options::default())) + .unwrap(); + black_box(( + translated.hlsl.len(), + translated.instructions, + translated.blocks, + )) + }) + }); + } + for blocks in [8usize, 32] { + let code = branch_program(blocks); + group.throughput(Throughput::Elements((blocks * 3 + 1) as u64)); + group.bench_with_input( + BenchmarkId::new("control_flow", blocks), + &code, + |b, code| { + b.iter(|| { + let translated = + recomp::translate(black_box(code), black_box(&recomp::Options::default())) + .unwrap(); + black_box(( + translated.hlsl.len(), + translated.instructions, + translated.blocks, + )) + }) + }, + ); + } + group.finish(); +} + +fn descriptors(c: &mut Criterion) { + let image = desc::xcl_image_for_view(7, 10, desc::ImageType::D2, 1920, 1080, 1, 11); + let buffer = desc::buffer_words(0x1_2345_6000, 16, 65_536, 74); + let sampler = [0x0000_0002, 0x0000_0101, 0x3f80_0000, 0x0000_0000]; + let mut group = c.benchmark_group("descriptor_conversion"); + group.bench_function("decode_image", |b| { + b.iter(|| black_box(desc::image(black_box(&image)))) + }); + group.bench_function("image_to_d3d12", |b| { + let decoded = desc::image(&image).unwrap(); + b.iter(|| black_box(desc::image_d3d12(black_box(&decoded)))) + }); + group.bench_function("decode_buffer", |b| { + b.iter(|| black_box(desc::buffer(black_box(&buffer)))) + }); + group.bench_function("sampler_to_d3d12", |b| { + b.iter(|| black_box(desc::sampler_d3d12(black_box(&sampler), false))) + }); + group.finish(); +} + +fn shader_scans(c: &mut Criterion) { + let program = arithmetic_program(1024); + let mut blob = vec![0u8; 4096]; + for _ in 0..16 { + blob.extend_from_slice(&program); + blob.extend_from_slice(&[0u8; 64]); + } + let mut group = c.benchmark_group("shader_scans"); + group.throughput(Throughput::Bytes(blob.len() as u64)); + group.bench_function("find_rdna2_programs", |b| { + b.iter(|| black_box(rdna2::find_programs(black_box(&blob)))) + }); + group.throughput(Throughput::Bytes(program.len() as u64)); + group.bench_function("classify_raw_rdna2", |b| { + b.iter(|| black_box(shader::classify(black_box(&program)))) + }); + group.throughput(Throughput::Bytes(blob.len() as u64)); + group.bench_function("fnv64", |b| { + b.iter(|| black_box(shader::fnv64(black_box(&blob)))) + }); + group.throughput(Throughput::Bytes(program.len() as u64)); + group.bench_function("split_segments", |b| { + b.iter(|| black_box(xbox::split_segments(black_box(&program)))) + }); + group.finish(); +} + +fn main() { + support::run(&[rdna2_frontend, translate, descriptors, shader_scans]); +} diff --git a/crates/xcl/benches/runtime.rs b/crates/xcl/benches/runtime.rs new file mode 100644 index 0000000000..3ff4a99f4a --- /dev/null +++ b/crates/xcl/benches/runtime.rs @@ -0,0 +1,205 @@ +mod support; + +use std::collections::BTreeMap; +use std::hint::black_box; +use std::path::Path; +use support::{BatchSize, BenchmarkId, Criterion, Throughput}; +use xcl::config::Config; +use xcl::manifest; +use xcl::util; +use xcl::vfs::Vfs; + +const MANIFEST: &str = r#"<Game configVersion="1"> + <Identity Name="Synthetic.Benchmark" Publisher="CN=Benchmark" Version="1.0.0.0" /> + <PersistentLocalStorage><SizeMB>4096</SizeMB></PersistentLocalStorage> + <VirtualMachine> + <XboxAnacondaTitleMemory>Advanced</XboxAnacondaTitleMemory> + <XboxLockhartTitleMemory>Standard</XboxLockhartTitleMemory> + </VirtualMachine> + <TitleId>12345678</TitleId> + <Resources> + <Resource Language="en-US"/><Resource Language="fr-FR"/> + <Resource Language="de-DE"/><Resource Language="ja-JP"/> + </Resources> +</Game>"#; + +const CONFIG: &str = r#" +device_type = "anaconda" +gamertag = "Player" +user_id = 281474976710655 +title_memory = "auto" +pls_mb = 0 +uma_mb = 0 +log_level = "info" +graphics = "d3d12" +d3d12_adapter = "auto" +present = "auto" +raytracing = "auto" +window_width = 1280 +window_height = 720 +keyboard_mouse = true +mouse_sensitivity = 1.0 + +[mounts] +"GAME:" = "{game}" +"G:" = "{game}" +"S:" = "{data}\\pls" + +[aliases] +"api-ms-win-*" = "@system" +"kernelx.dll" = "kernelx.dll" + +[stub_returns] +"example.dll!Example" = "S_OK" +"#; + +fn utility_benches(c: &mut Criterion) { + let mut group = c.benchmark_group("runtime/util"); + for (name, pattern, value) in [ + ("glob_exact", "kernelx.dll", "kernelx.dll"), + ( + "glob_prefix", + "api-ms-win-*", + "api-ms-win-core-file-l2-1-0.dll", + ), + ("glob_bounded", "xgame*.dll", "xgameruntime.dll"), + ] { + group.bench_function(name, |b| { + b.iter(|| util::glob_match(black_box(pattern), black_box(value))) + }); + } + for value in [ + "kernelx", + "D:\\Game\\D3D12_XS.DLL", + "api-ms-win-core-file-l2-1-0", + ] { + group.bench_with_input( + BenchmarkId::new("dll_key", value.len()), + value, + |b, value| { + b.iter(|| util::dll_key(black_box(value))); + }, + ); + } + for value in ["S_OK", "E_NOTIMPL", "0x80004005", "42"] { + group.bench_with_input( + BenchmarkId::new("parse_return", value), + value, + |b, value| { + b.iter(|| util::parse_ret(black_box(value))); + }, + ); + } + for value in [ + "short", + "D:\\Synthetic Game\\Content\\localization\\en-US\\strings.bin", + ] { + group.throughput(Throughput::Bytes(value.len() as u64)); + group.bench_with_input(BenchmarkId::new("utf16", value.len()), value, |b, value| { + b.iter(|| util::wide(black_box(value))); + }); + } + group.finish(); +} + +fn manifest_and_config_benches(c: &mut Criterion) { + let mut group = c.benchmark_group("runtime/config"); + group.throughput(Throughput::Bytes(MANIFEST.len() as u64)); + group.bench_function("manifest_parse", |b| { + b.iter(|| manifest::parse(black_box(MANIFEST))) + }); + + group.throughput(Throughput::Bytes(CONFIG.len() as u64)); + group.bench_function("toml_parse", |b| { + b.iter(|| toml::from_str::<Config>(black_box(CONFIG)).unwrap()); + }); + + let parsed_manifest = manifest::parse(MANIFEST); + group.throughput(Throughput::Elements(1)); + group.bench_function("resolve_defaults", |b| { + b.iter_batched( + Config::default, + |mut config| black_box(config.resolve(black_box(Some(&parsed_manifest)))), + BatchSize::SmallInput, + ); + }); + + let mut mounts = BTreeMap::new(); + mounts.insert("GAME:".to_owned(), "{game}".to_owned()); + mounts.insert("S:".to_owned(), "{data}\\pls".to_owned()); + let mut resolved = Config { + mounts, + ..Config::default() + }; + resolved.resolve(Some(&parsed_manifest)); + group.throughput(Throughput::Elements(1)); + group.bench_function("resolved_memory_queries", |b| { + b.iter(|| { + black_box(resolved.title_memory_budget_mb()); + black_box(resolved.pls_drive()); + black_box(resolved.raytracing_tier_override()); + }); + }); + group.finish(); +} + +fn vfs_benches(c: &mut Criterion) { + let vfs = Vfs::new( + Path::new(r"C:\bench\game"), + Path::new(r"C:\bench\data"), + vec![ + ("GAME:".to_owned(), r"C:\bench\game".to_owned()), + ("G:".to_owned(), r"C:\bench\game".to_owned()), + ("S:".to_owned(), r"C:\bench\data\pls".to_owned()), + ], + ); + let full = |path: &str| Some(path.replace('/', "\\")); + let cases = [ + ("mounted_game", r"GAME:\data\textures.bin"), + ("mounted_drive", r"G:\data\textures.bin"), + ("embedded_mount", r"C:\cwd\GAME:\data\textures.bin"), + ("direct_game", r"C:\bench\game\data\textures.bin"), + ("host_path", r"C:\Windows\System32\kernel32.dll"), + ("unc", r"\\server\share\file.bin"), + ]; + + let mut group = c.benchmark_group("runtime/vfs"); + for (name, path) in cases { + group.throughput(Throughput::Bytes(path.len() as u64)); + group.bench_with_input(BenchmarkId::new("classify", name), path, |b, path| { + b.iter(|| vfs.classify_with(black_box(path), black_box(full))); + }); + } + group.throughput(Throughput::Bytes( + cases.iter().map(|(_, path)| path.len() as u64).sum(), + )); + group.bench_function("classify_mixed_batch", |b| { + b.iter(|| { + for (_, path) in black_box(&cases) { + black_box(vfs.classify_with(path, full)); + } + }); + }); + for rel in ["", "data", r"data\textures\terrain.bin"] { + group.throughput(Throughput::Elements(1)); + group.bench_with_input( + BenchmarkId::new("overlay_path", rel.len()), + rel, + |b, rel| { + b.iter(|| vfs.overlay_path(black_box(rel))); + }, + ); + group.bench_with_input( + BenchmarkId::new("original_path", rel.len()), + rel, + |b, rel| { + b.iter(|| vfs.original_path(black_box(rel))); + }, + ); + } + group.finish(); +} + +fn main() { + support::run(&[utility_benches, manifest_and_config_benches, vfs_benches]); +} From aedde19cc8cb10f2e54b112339839f410b4b2601 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:11:20 -0800 Subject: [PATCH 240/265] D3D12.X: coordinate exact pipeline restoration state Compose the inert eviction ledger and rehydration receipts without nested policy locks. Exact terminal receipts now map to retry, release, poison, or restored state, while foreground demand promotes one existing attempt. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 334 +++++++++++++++++++++++++ 1 file changed, 334 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 3a82f585f1..7458d5dc23 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1070,6 +1070,16 @@ impl<const N: usize> EvictedBuildLedger<N> { self.set_state(token, EvictedBuildState::Evicted, EvictedBuildState::RehydrateQueued) } + fn rehydrate_retry(&self, token: &EvictedBuildToken) -> bool { + self.set_state(token, EvictedBuildState::RehydrateQueued, EvictedBuildState::Evicted) + } + + fn state(&self, token: &EvictedBuildToken) -> Option<EvictedBuildState> { + let inner = self.inner.lock().unwrap(); + let entry = inner.slots.get(token.slot)?.entry.as_ref()?; + entry.token.exact(token).then_some(entry.state) + } + fn finish(&self, token: &EvictedBuildToken, terminal: EvictedBuildState) -> bool { let mut inner = self.inner.lock().unwrap(); let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; @@ -1382,6 +1392,26 @@ impl<const N: usize> RehydrateReceiptRegistry<N> { fn reserve<'a>(&'a self, evicted: &EvictedBuildToken) -> Option<RehydrateReceiptReservation<'a, N>> { let mut inner = self.inner.lock().unwrap(); + self.reserve_locked(&mut inner, evicted) + } + + fn reserve_unique<'a>( + &'a self, evicted: &EvictedBuildToken, allow_new: bool, + ) -> Result<Option<RehydrateReceiptReservation<'a, N>>, RehydrateReceiptRecord> { + let mut inner = self.inner.lock().unwrap(); + if let Some(entry) = inner.slots.iter().filter_map(|slot| slot.entry.as_ref()) + .find(|entry| entry.token.evicted.exact(evicted)) { + return Err(RehydrateReceiptRecord { + token: entry.token.clone(), state: entry.state, priority: entry.priority, + }); + } + if !allow_new { return Ok(None) } + Ok(self.reserve_locked(&mut inner, evicted)) + } + + fn reserve_locked<'a>( + &'a self, inner: &mut RehydrateReceiptInner<N>, evicted: &EvictedBuildToken, + ) -> Option<RehydrateReceiptReservation<'a, N>> { if inner.exhausted { return None } let slot = inner.slots.iter().position(|slot| slot.entry.is_none())?; let Some(serial) = inner.serial.checked_add(1) else { @@ -1553,6 +1583,117 @@ impl<const N: usize> Drop for RehydrateQueuedReceipt<'_, N> { } } +#[allow(dead_code)] +#[derive(Clone)] +struct RestorationRetry { token: EvictedBuildToken } + +#[allow(dead_code)] +/// State composition only: it retains no JobHandle or post-success native pin and never starts, +/// runs, or promotes live queue work. Foreground here is admission metadata, not live readiness. +struct RestorationCoordinator<const E: usize, const R: usize> { + evicted: EvictedBuildLedger<E>, + receipts: RehydrateReceiptRegistry<R>, +} + +#[allow(dead_code)] +enum RestorationQueue<'a, const E: usize, const R: usize> { + Queued(RestorationQueued<'a, E, R>), + Existing, + Promoted, +} + +#[allow(dead_code)] +struct RestorationQueued<'a, const E: usize, const R: usize> { + coordinator: &'a RestorationCoordinator<E, R>, + receipt: RehydrateQueuedReceipt<'a, R>, +} + +#[allow(dead_code)] +impl<const E: usize, const R: usize> RestorationCoordinator<E, R> { + fn new(generation: u64) -> Option<Self> { + Some(Self { evicted: EvictedBuildLedger::new(generation)?, receipts: RehydrateReceiptRegistry::new()? }) + } + + fn reserve_eviction<'a>( + &'a self, build: &Arc<Build>, native: LedgerNativeGeneration, + ) -> Option<EvictedBuildReservation<'a, E>> { + self.evicted.reserve(build, native) + } + + fn refuse_rehydrate(&self, evicted: &EvictedBuildToken) -> bool { + match self.receipts.reserve_unique(evicted, true) { + Ok(Some(reservation)) => reservation.refused().is_some(), + Ok(None) | Err(_) => false, + } + } + + fn queue_rehydrate( + &self, evicted: &EvictedBuildToken, priority: RehydratePriority, background_ready: bool, + ) -> Option<RestorationQueue<'_, E, R>> { + let allow_new = priority == RehydratePriority::Foreground || background_ready; + let reservation = match self.receipts.reserve_unique(evicted, allow_new) { + Err(record) => { + if !record.state.terminal() && priority == RehydratePriority::Foreground + && record.priority != RehydratePriority::Foreground { + return self.receipts.promote(&record.token).then_some(RestorationQueue::Promoted); + } + return Some(RestorationQueue::Existing); + } + Ok(Some(reservation)) => reservation, + Ok(None) => return None, + }; + let (_, receipt) = reservation.accepted(priority)?; + if !self.evicted.rehydrate_queued(evicted) { + drop(receipt); + return None; + } + Some(RestorationQueue::Queued(RestorationQueued { coordinator: self, receipt })) + } + + /// Snapshot receipt state first, then mutate the exact eviction record, then retire the + /// receipt. No two policy locks overlap, and a stale token can never touch a reused slot. + fn reconcile(&self, limit: usize) -> usize { + let records = self.receipts.records(limit); + let mut reconciled = 0; + for record in records.into_iter().filter(|record| record.state.terminal()) { + let token = &record.token.evicted; + let ok = match record.state { + RehydrateCompletion::Refused => self.evicted.state(token) == Some(EvictedBuildState::Evicted), + RehydrateCompletion::Cancelled | RehydrateCompletion::Panicked | RehydrateCompletion::BuildFailed => { + self.evicted.rehydrate_retry(token) || self.evicted.state(token) == Some(EvictedBuildState::Evicted) + } + RehydrateCompletion::Released => self.evicted.finish(token, EvictedBuildState::Released) + || self.evicted.state(token) == Some(EvictedBuildState::Released), + RehydrateCompletion::Succeeded { .. } => self.evicted.finish(token, EvictedBuildState::Restored) + || self.evicted.state(token) == Some(EvictedBuildState::Restored), + _ => false, + }; + if !ok && self.evicted.state(token).is_some_and(|state| !state.terminal()) { + let _ = self.evicted.finish(token, EvictedBuildState::Poisoned); + } + if self.receipts.retire(&record.token) { reconciled += 1 } + } + reconciled + } + + fn retries(&self, limit: usize) -> Vec<RestorationRetry> { + self.evicted.records(limit).into_iter().filter_map(|record| { + (record.state == EvictedBuildState::Evicted).then_some(RestorationRetry { token: record.token }) + }).collect() + } +} + +#[allow(dead_code)] +impl<const E: usize, const R: usize> RestorationQueued<'_, E, R> { + fn token(&self) -> &RehydrateAttemptToken { &self.receipt.token } + fn replacement(&self, build: &Arc<Build>, replacement: &NativeGeneration) -> Option<rehydrate_success::Proof> { + self.receipt.replacement(build, replacement) + } + fn promote(&self) -> bool { self.coordinator.receipts.promote(&self.receipt.token) } + fn complete(self, completion: RehydrateCompletion) -> bool { self.receipt.complete(completion) } + fn complete_success(self, proof: rehydrate_success::Proof) -> bool { self.receipt.complete_success(proof) } +} + fn forget_in_flight(build: &Arc<Build>) { let Some(key) = &build.compute_key else { return }; let mut registry = IN_FLIGHT.lock().unwrap(); @@ -3104,6 +3245,12 @@ mod used_tests { .reserve(build, ledger_native(id)).unwrap().arm_detach().unwrap() } + fn coordinated_evicted<const E: usize, const R: usize>( + coordinator: &RestorationCoordinator<E, R>, build: &Arc<Build>, id: u64, + ) -> EvictedBuildToken { + coordinator.reserve_eviction(build, ledger_native(id)).unwrap().arm_detach().unwrap() + } + #[test] fn rehydrate_receipts_separate_request_from_completion() { let build = ledger_build(); let evicted = receipt_evicted(&build, 20); @@ -3231,6 +3378,193 @@ mod used_tests { assert!(generation.inner.lock().unwrap().exhausted); } + #[test] + fn restoration_coordinator_refusal_and_full_ledger_retry() { + let coordinator = RestorationCoordinator::<1, 2>::new(301).unwrap(); + let build = ledger_build(); + let reserved = coordinator.reserve_eviction(&build, ledger_native(40)).unwrap(); + assert!(coordinator.reserve_eviction(&ledger_build(), ledger_native(41)).is_none()); + drop(reserved); + let evicted = coordinated_evicted(&coordinator, &build, 40); + assert!(coordinator.refuse_rehydrate(&evicted)); + assert_eq!(coordinator.reconcile(2), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Evicted)); + assert!(coordinator.retries(1)[0].token.exact(&evicted)); + } + + #[test] + fn rehydrate_registry_atomically_returns_existing_before_readiness() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 49); + let registry = RehydrateReceiptRegistry::<2>::new().unwrap(); + let reservation = match registry.reserve_unique(&evicted, true) { + Ok(Some(reservation)) => reservation, _ => panic!("initial unique reservation failed"), + }; + let existing = match registry.reserve_unique(&evicted, true) { + Err(existing) => existing, _ => panic!("duplicate reservation was admitted"), + }; + assert!(existing.token.evicted.exact(&evicted)); + assert!(matches!(registry.reserve_unique(&evicted, false), Err(existing) + if existing.token.evicted.exact(&evicted))); + drop(reservation); + assert!(matches!(registry.reserve_unique(&evicted, false), Ok(None))); + } + + #[test] + fn restoration_coordinator_maps_failures_and_foreground_deduplicates() { + let coordinator = RestorationCoordinator::<1, 2>::new(302).unwrap(); + let build = ledger_build(); let evicted = coordinated_evicted(&coordinator, &build, 42); + let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => panic!("first request was not queued"), + }; + assert!(matches!(coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, false), + Some(RestorationQueue::Existing)), "backoff hid an already-live attempt"); + assert!(matches!(coordinator.queue_rehydrate(&evicted, RehydratePriority::Foreground, false), + Some(RestorationQueue::Promoted))); + assert!(matches!(coordinator.queue_rehydrate(&evicted, RehydratePriority::Foreground, false), + Some(RestorationQueue::Existing))); + assert_eq!(coordinator.receipts.records(2).len(), 1); + assert_eq!(coordinator.receipts.records(2)[0].priority, RehydratePriority::Foreground); + drop(queued); assert_eq!(coordinator.reconcile(2), 1); + assert!(coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, false).is_none()); + for completion in [RehydrateCompletion::Panicked, RehydrateCompletion::BuildFailed] { + let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + assert!(queued.complete(completion)); assert_eq!(coordinator.reconcile(2), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Evicted)); + } + let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Foreground, false).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + panic!("restoration worker panic"); + })); + assert!(panic_result.is_err()); assert_eq!(coordinator.reconcile(2), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Evicted)); + } + + #[test] + fn restoration_coordinator_atomically_deduplicates_concurrent_queues() { + let coordinator = RestorationCoordinator::<1, 2>::new(306).unwrap(); + let build = ledger_build(); let evicted = coordinated_evicted(&coordinator, &build, 47); + let barrier = std::sync::Barrier::new(3); + let queued = AtomicUsize::new(0); + let existing = AtomicUsize::new(0); + std::thread::scope(|scope| { + for _ in 0..2 { + scope.spawn(|| { + barrier.wait(); + match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(receipt) => { + queued.fetch_add(1, Ordering::Relaxed); + assert!(receipt.complete(RehydrateCompletion::BuildFailed)); + } + RestorationQueue::Existing => { existing.fetch_add(1, Ordering::Relaxed); } + RestorationQueue::Promoted => panic!("background request promoted"), + } + }); + } + barrier.wait(); + }); + assert_eq!((queued.load(Ordering::Relaxed), existing.load(Ordering::Relaxed)), (1, 1)); + assert_eq!(coordinator.receipts.records(2).len(), 1); + assert_eq!(coordinator.reconcile(2), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Evicted)); + } + + #[test] + fn restoration_coordinator_atomically_orders_queue_against_refusal() { + let coordinator = RestorationCoordinator::<1, 2>::new(307).unwrap(); + let build = ledger_build(); let evicted = coordinated_evicted(&coordinator, &build, 48); + let barrier = std::sync::Barrier::new(3); + let admitted = AtomicUsize::new(0); + std::thread::scope(|scope| { + scope.spawn(|| { + barrier.wait(); + match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(receipt) => { + admitted.fetch_add(1, Ordering::Relaxed); + assert!(receipt.complete(RehydrateCompletion::BuildFailed)); + } + RestorationQueue::Existing => {} + RestorationQueue::Promoted => unreachable!(), + } + }); + scope.spawn(|| { + barrier.wait(); + if coordinator.refuse_rehydrate(&evicted) { + admitted.fetch_add(1, Ordering::Relaxed); + } + }); + barrier.wait(); + }); + assert_eq!(admitted.load(Ordering::Relaxed), 1); + assert_eq!(coordinator.receipts.records(2).len(), 1); + assert_eq!(coordinator.reconcile(2), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Evicted)); + } + + #[test] + fn restoration_coordinator_release_race_is_terminal_and_idempotent() { + let coordinator = RestorationCoordinator::<1, 1>::new(303).unwrap(); + let build = ledger_build(); let evicted = coordinated_evicted(&coordinator, &build, 43); + let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + drop(build); drop(queued); + assert_eq!(coordinator.reconcile(1), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Released)); + assert_eq!(coordinator.reconcile(1), 0); + assert!(coordinator.retries(1).is_empty()); + } + + #[test] + fn restoration_coordinator_poisons_mismatch_without_touching_reused_slot() { + let coordinator = RestorationCoordinator::<1, 1>::new(305).unwrap(); + let first_build = ledger_build(); + let first = coordinated_evicted(&coordinator, &first_build, 45); + assert!(coordinator.refuse_rehydrate(&first)); + assert!(coordinator.evicted.rehydrate_queued(&first)); + assert_eq!(coordinator.reconcile(1), 1); + assert_eq!(coordinator.evicted.state(&first), Some(EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&first)); + + let second_build = ledger_build(); + let second = coordinated_evicted(&coordinator, &second_build, 46); + assert_eq!(first.slot, second.slot); + assert_ne!(first.slot_generation, second.slot_generation); + assert!(coordinator.receipts.reserve(&first).unwrap().refused().is_some()); + assert_eq!(coordinator.reconcile(1), 1); + assert_eq!(coordinator.evicted.state(&second), Some(EvictedBuildState::Evicted), + "a stale receipt poisoned a reused eviction slot"); + assert_eq!(coordinator.reconcile(1), 0); + } + + #[test] + fn restoration_coordinator_exact_success_restores_after_receipt() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let job = build.job.lock().unwrap().take().unwrap(); complete(&build, job()); + let replacement = recipe.pin_with_residency(raw).0.unwrap(); + let coordinator = RestorationCoordinator::<1, 1>::new(304).unwrap(); + let evicted = coordinated_evicted(&coordinator, &build, 44); + let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Foreground, false).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + let proof = queued.replacement(&build, &replacement).unwrap(); + assert!(queued.complete_success(proof)); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::RehydrateQueued)); + assert_eq!(coordinator.reconcile(1), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Restored)); + assert_eq!(coordinator.reconcile(1), 0); + let raw_owner = build.real.swap(0, Ordering::AcqRel); + drop(build); release(raw_owner); drop(replacement); drop(recipe); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + #[test] fn pressure_observer_bounds_inspection_and_requeues_every_resident() { let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; From 2c5c33d4c85acf64a489204e40b8efb990bfa6e2 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:13:13 -0800 Subject: [PATCH 241/265] D3D12.X: model exact foreground sparse waits Bind frontier-ready receipts to exact sparse fence and title-queue generations. Reservation guards separate rollback-safe preparation from accepted waits, while unpublished acceptance remains fail-closed. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 399 +++++++++++++++++++++++++++- 1 file changed, 397 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 9a82172e9a..51696941d6 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -676,6 +676,7 @@ impl ClaimFrontier { #[allow(dead_code)] enum SparseBatchError { StaleGeneration, + Fence, Poisoned, Unsealed, Exhausted, @@ -690,6 +691,7 @@ enum SparseBatchError { struct SparseBatchLedger { work: WorkClaimLedger, frontier: ClaimFrontier, + fence: Option<SparseFenceIdentity>, bindings: BTreeMap<u64, WorkClaimToken>, poisoned: bool, } @@ -700,6 +702,7 @@ impl SparseBatchLedger { Self { work: WorkClaimLedger::new(state_generation), frontier: ClaimFrontier::new(state_generation), + fence: None, bindings: BTreeMap::new(), poisoned: false, } @@ -830,7 +833,9 @@ impl SparseBatchLedger { self.work.claims.contains_key(&work.serial).then_some(work).ok_or(SparseBatchError::Corrupt) } - fn replace_generation(&mut self, current: u64, replacement: u64) -> Result<(), SparseBatchError> { + fn replace_generation( + &mut self, current: u64, replacement: u64, fence_allocation: Option<u64>, + ) -> Result<(), SparseBatchError> { if current != self.work.state_generation { return Err(SparseBatchError::StaleGeneration); } @@ -838,6 +843,13 @@ impl SparseBatchLedger { if replacement <= current { return Err(SparseBatchError::StaleGeneration); } + self.fence = match (self.fence, fence_allocation) { + (None, None) => None, + (Some(fence), Some(allocation)) if allocation > fence.allocation => { + Some(SparseFenceIdentity { state_generation: replacement, allocation }) + } + _ => return Err(SparseBatchError::Fence), + }; self.work.replace_generation(replacement); self.frontier = ClaimFrontier::new(replacement); self.bindings.clear(); @@ -859,6 +871,13 @@ impl SparseBatches { Self { ledger: Arc::new(Mutex::new(SparseBatchLedger::new(state_generation))), state_generation } } + fn with_fence(state_generation: u64, fence_allocation: u64) -> Option<Self> { + if state_generation == 0 || fence_allocation == 0 { return None } + let batches = Self::new(state_generation); + batches.ledger.lock().unwrap().fence = Some(SparseFenceIdentity { state_generation, allocation: fence_allocation }); + Some(batches) + } + fn add_pages(&self, pages: impl IntoIterator<Item = usize>, reason: WorkReasons) -> bool { // Iterator code is caller code: finish it before taking the non-reentrant ledger mutex. let mut pages: Vec<_> = pages.into_iter().map(|page| page & !(PAGE - 1)).collect(); @@ -894,6 +913,17 @@ impl SparseBatches { self.ledger.lock().unwrap().observe(self.state_generation, through, requester) } + fn ready_receipt(&self, through: u64, requester: u64) -> Result<SparseReadyReceipt, ForegroundWaitError> { + let ledger = self.ledger.lock().unwrap(); + let fence = ledger.fence.ok_or(ForegroundWaitError::Fence)?; + match ledger.observe(self.state_generation, through, requester).map_err(ForegroundWaitError::Batch)? { + ClaimFrontierAction::Ready { through, required_fence } => Ok(SparseReadyReceipt { + state_generation: self.state_generation, fence, through, required_fence, + }), + _ => Err(ForegroundWaitError::NotReady), + } + } + fn through(&self) -> Result<u64, SparseBatchError> { self.ledger.lock().unwrap().through(self.state_generation) } @@ -906,7 +936,16 @@ impl SparseBatches { } fn replace_generation(&self, replacement: u64) -> Result<Self, SparseBatchError> { - self.ledger.lock().unwrap().replace_generation(self.state_generation, replacement)?; + self.ledger.lock().unwrap().replace_generation(self.state_generation, replacement, None)?; + Ok(Self { ledger: self.ledger.clone(), state_generation: replacement }) + } + + fn replace_generation_with_fence( + &self, replacement: u64, fence_allocation: u64, + ) -> Result<Self, SparseBatchError> { + self.ledger.lock().unwrap().replace_generation( + self.state_generation, replacement, Some(fence_allocation), + )?; Ok(Self { ledger: self.ledger.clone(), state_generation: replacement }) } } @@ -961,6 +1000,257 @@ impl Drop for AcceptedSparseBatch { } } +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +#[allow(dead_code)] +struct SparseFenceIdentity { + state_generation: u64, allocation: u64, +} + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +#[allow(dead_code)] +struct TitleQueueIdentity { + raw: usize, generation: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct SparseReadyReceipt { + state_generation: u64, fence: SparseFenceIdentity, through: u64, required_fence: Option<u64>, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct ForegroundWaitToken { + state_generation: u64, fence: SparseFenceIdentity, queue: TitleQueueIdentity, serial: u64, value: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ForegroundWaitState { Reserved, Accepted } + +struct ForegroundWaitRecord { + fence: SparseFenceIdentity, installed: u64, + pending: Option<(ForegroundWaitToken, ForegroundWaitState)>, uncertain: bool, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum ForegroundWaitError { + StaleGeneration, Fence, Queue, NotReady, Pending(ForegroundWaitToken), + Uncertain, StaleToken, Exhausted, + Batch(SparseBatchError), +} + +#[allow(dead_code)] +enum ForegroundWaitDecision { + NoWait { through: u64 }, Installed { through: u64, value: u64 }, + Reserve(ForegroundWaitReservation), +} + +#[allow(dead_code)] +struct ForegroundWaitLedger { + state_generation: u64, fence: SparseFenceIdentity, + next_queue_generation: u64, next_serial: u64, + queues: BTreeMap<usize, u64>, + waits: BTreeMap<TitleQueueIdentity, ForegroundWaitRecord>, +} + +#[allow(dead_code)] +impl ForegroundWaitLedger { + fn new(state_generation: u64, fence_allocation: u64) -> Option<Self> { + if state_generation == 0 || fence_allocation == 0 { return None } + Some(Self { + state_generation, + fence: SparseFenceIdentity { state_generation, allocation: fence_allocation }, + next_queue_generation: 0, + next_serial: 0, + queues: BTreeMap::new(), + waits: BTreeMap::new(), + }) + } + + fn register_queue(&mut self, raw: usize) -> Result<TitleQueueIdentity, ForegroundWaitError> { + if raw == 0 { return Err(ForegroundWaitError::Queue) } + if let Some(&generation) = self.queues.get(&raw) { + return Ok(TitleQueueIdentity { raw, generation }); + } + let generation = self.next_queue_generation.checked_add(1).ok_or(ForegroundWaitError::Exhausted)?; + self.next_queue_generation = generation; + self.queues.insert(raw, generation); + Ok(TitleQueueIdentity { raw, generation }) + } + + fn retire_queue(&mut self, queue: TitleQueueIdentity) -> Result<(), ForegroundWaitError> { + if self.queues.get(&queue.raw) != Some(&queue.generation) { return Err(ForegroundWaitError::Queue) } + self.queues.remove(&queue.raw); + self.waits.remove(&queue); + Ok(()) + } + + fn reserve( + &mut self, queue: TitleQueueIdentity, ready: SparseReadyReceipt, + ) -> Result<ForegroundWaitDecision, ForegroundWaitError> { + if ready.state_generation != self.state_generation { return Err(ForegroundWaitError::StaleGeneration) } + if ready.fence != self.fence { return Err(ForegroundWaitError::Fence) } + if self.queues.get(&queue.raw) != Some(&queue.generation) { return Err(ForegroundWaitError::Queue) } + if let Some(record) = self.waits.get(&queue) { + if record.fence != ready.fence { return Err(ForegroundWaitError::Fence) } + if record.uncertain { return Err(ForegroundWaitError::Uncertain) } + if let Some((token, _)) = record.pending { return Err(ForegroundWaitError::Pending(token)) } + } + let Some(value) = ready.required_fence else { return Ok(ForegroundWaitDecision::NoWait { through: ready.through }) }; + if value == 0 { return Err(ForegroundWaitError::Fence) } + let record = self.waits.entry(queue).or_insert(ForegroundWaitRecord { + fence: ready.fence, + installed: 0, + pending: None, + uncertain: false, + }); + if record.installed >= value { return Ok(ForegroundWaitDecision::Installed { through: ready.through, value }) } + let serial = self.next_serial.checked_add(1).ok_or(ForegroundWaitError::Exhausted)?; + self.next_serial = serial; + let token = ForegroundWaitToken { state_generation: self.state_generation, fence: ready.fence, queue, serial, value }; + record.pending = Some((token, ForegroundWaitState::Reserved)); + Ok(ForegroundWaitDecision::Reserve(ForegroundWaitReservation { + ledger: None, + token: Some(token), + through: ready.through, + })) + } + + fn transition( + &mut self, token: ForegroundWaitToken, expected: ForegroundWaitState, + replacement: Option<ForegroundWaitState>, + ) -> Result<(), ForegroundWaitError> { + if token.state_generation != self.state_generation { return Err(ForegroundWaitError::StaleGeneration) } + if token.fence != self.fence { return Err(ForegroundWaitError::Fence) } + if self.queues.get(&token.queue.raw) != Some(&token.queue.generation) { + return Err(ForegroundWaitError::Queue); + } + let record = self.waits.get_mut(&token.queue).ok_or(ForegroundWaitError::StaleToken)?; + if record.pending != Some((token, expected)) { return Err(ForegroundWaitError::StaleToken) } + record.pending = replacement.map(|state| (token, state)); + Ok(()) + } + + fn publish(&mut self, token: ForegroundWaitToken) -> Result<(), ForegroundWaitError> { + self.transition(token, ForegroundWaitState::Accepted, None)?; + self.waits.get_mut(&token.queue).unwrap().installed = token.value; + Ok(()) + } + + fn uncertain(&mut self, token: ForegroundWaitToken) { + if self.transition(token, ForegroundWaitState::Accepted, None).is_ok() { + self.waits.get_mut(&token.queue).unwrap().uncertain = true; + } + } + + fn replace_generation( + &mut self, current: u64, replacement: u64, fence_allocation: u64, + ) -> Result<(), ForegroundWaitError> { + if current != self.state_generation || replacement <= current { + return Err(ForegroundWaitError::StaleGeneration); + } + if fence_allocation <= self.fence.allocation { return Err(ForegroundWaitError::Fence) } + self.state_generation = replacement; + self.fence = SparseFenceIdentity { state_generation: replacement, allocation: fence_allocation }; + self.waits.clear(); + Ok(()) + } +} + +#[derive(Clone)] +#[allow(dead_code)] +struct ForegroundWaits(Arc<Mutex<ForegroundWaitLedger>>); + +#[allow(dead_code)] +impl ForegroundWaits { + fn new(state_generation: u64, fence_allocation: u64) -> Option<Self> { + Some(Self(Arc::new(Mutex::new(ForegroundWaitLedger::new(state_generation, fence_allocation)?)))) + } + + fn register_queue(&self, raw: usize) -> Result<TitleQueueIdentity, ForegroundWaitError> { + self.0.lock().unwrap().register_queue(raw) + } + + fn fence(&self) -> SparseFenceIdentity { self.0.lock().unwrap().fence } + + fn retire_queue(&self, queue: TitleQueueIdentity) -> Result<(), ForegroundWaitError> { + self.0.lock().unwrap().retire_queue(queue) + } + + fn replace_generation( + &self, current: u64, replacement: u64, fence_allocation: u64, + ) -> Result<(), ForegroundWaitError> { + self.0.lock().unwrap().replace_generation(current, replacement, fence_allocation) + } + + fn reserve( + &self, queue: TitleQueueIdentity, ready: SparseReadyReceipt, + ) -> Result<ForegroundWaitDecision, ForegroundWaitError> { + let result = self.0.lock().unwrap().reserve(queue, ready)?; + Ok(match result { + ForegroundWaitDecision::Reserve(mut reservation) => { + reservation.ledger = Some(self.0.clone()); + ForegroundWaitDecision::Reserve(reservation) + } + ready => ready, + }) + } +} + +#[allow(dead_code)] +struct ForegroundWaitReservation { + ledger: Option<Arc<Mutex<ForegroundWaitLedger>>>, token: Option<ForegroundWaitToken>, through: u64, +} + +#[allow(dead_code)] +impl ForegroundWaitReservation { + fn arm(mut self) -> Result<AcceptedForegroundWait, ForegroundWaitError> { + let token = self.token.unwrap(); + self.ledger.as_ref().unwrap().lock().unwrap().transition( + token, ForegroundWaitState::Reserved, Some(ForegroundWaitState::Accepted), + )?; + self.token.take(); + Ok(AcceptedForegroundWait { ledger: self.ledger.take().unwrap(), token: Some(token), through: self.through }) + } +} + +impl Drop for ForegroundWaitReservation { + fn drop(&mut self) { + if let (Some(ledger), Some(token)) = (&self.ledger, self.token.take()) { + let _ = ledger.lock().unwrap().transition(token, ForegroundWaitState::Reserved, None); + } + } +} + +#[allow(dead_code)] +struct AcceptedForegroundWait { + ledger: Arc<Mutex<ForegroundWaitLedger>>, token: Option<ForegroundWaitToken>, through: u64, +} + +#[allow(dead_code)] +impl AcceptedForegroundWait { + fn publish(mut self) -> Result<(u64, u64), ForegroundWaitError> { + let token = self.token.unwrap(); + self.ledger.lock().unwrap().publish(token)?; + self.token.take(); + Ok((self.through, token.value)) + } + + fn rollback(mut self) -> Result<(), ForegroundWaitError> { + let token = self.token.unwrap(); + self.ledger.lock().unwrap().transition(token, ForegroundWaitState::Accepted, None)?; + self.token.take(); + Ok(()) + } +} + +impl Drop for AcceptedForegroundWait { + fn drop(&mut self) { + if let Some(token) = self.token.take() { self.ledger.lock().unwrap().uncertain(token) } + } +} + /// Point-in-time identities needed to prove that planning and a later serialized upload commit /// still refer to the same sparse page. `source` names the observed CPU page by chunk hash rather /// than retaining a raw pointer across the unlocked interval. Title writes are outside sparse @@ -4828,6 +5118,111 @@ mod tests { assert!(matches!(SparseBatches::new(u64::MAX).replace_generation(0), Err(SparseBatchError::StaleGeneration))); } + fn wait_ready(fence: SparseFenceIdentity, through: u64, value: Option<u64>) -> SparseReadyReceipt { + SparseReadyReceipt { state_generation: fence.state_generation, fence, through, required_fence: value } + } + + fn wait_reservation(decision: ForegroundWaitDecision) -> ForegroundWaitReservation { + match decision { ForegroundWaitDecision::Reserve(reservation) => reservation, _ => panic!("wait not reserved") } + } + + #[test] + fn foreground_wait_pairs_out_of_order_frontier_with_exact_fence() { + let batches = SparseBatches::with_fence(101, 501).unwrap(); + assert!(batches.add_dirty_pages([0x6_1000, 0x6_2000])); + let first = batches.seal(1, 1).unwrap().unwrap(); + let first_token = first.token; + let second = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + let first = first.accept().unwrap(); + second.accept().unwrap().receipt(11).unwrap(); + let waits = ForegroundWaits::new(101, 501).unwrap(); + let queue = waits.register_queue(0xA).unwrap(); + assert_eq!(waits.register_queue(0xA), Ok(queue)); + assert_eq!(batches.ready_receipt(through, 3), Err(ForegroundWaitError::NotReady)); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::WaitForReceipt(first_token))); + first.receipt(8).unwrap(); + + let ready = batches.ready_receipt(through, 3).unwrap(); + let wrong = SparseReadyReceipt { fence: SparseFenceIdentity { allocation: 502, ..ready.fence }, ..ready }; + assert!(matches!(waits.reserve(queue, wrong), Err(ForegroundWaitError::Fence))); + let reservation = wait_reservation(waits.reserve(queue, ready).unwrap()); + assert_eq!(reservation.arm().unwrap().publish(), Ok((through, 11))); + assert!(matches!(waits.reserve(queue, ready), Ok(ForegroundWaitDecision::Installed { through: t, value: 11 }) if t == through)); + assert!(matches!(waits.reserve(queue, wait_ready(waits.fence(), through + 1, None)), + Ok(ForegroundWaitDecision::NoWait { through: t }) if t == through + 1)); + + let other = SparseBatches::with_fence(101, 502).unwrap(); + let other_waits = ForegroundWaits::new(101, 502).unwrap(); + let other_queue = other_waits.register_queue(0xE).unwrap(); + assert!(matches!(other.ready_receipt(through, 3), Err(ForegroundWaitError::Batch(_)))); + assert!(matches!(other_waits.reserve(other_queue, ready), Err(ForegroundWaitError::Fence))); + + assert!(matches!(batches.replace_generation_with_fence(102, 501), Err(SparseBatchError::Fence))); + let stale = batches.clone(); + let batches = batches.replace_generation_with_fence(102, 503).unwrap(); + assert_eq!(batches.ledger.lock().unwrap().fence.unwrap().allocation, 503); + assert_eq!(stale.ready_receipt(through, 3), Err(ForegroundWaitError::Batch(SparseBatchError::StaleGeneration))) + } + + #[test] + fn foreground_wait_rollbacks_are_exact_and_queue_reuse_is_stale() { + let waits = ForegroundWaits::new(103, 601).unwrap(); + let fence = waits.fence(); + let queue = waits.register_queue(0xB).unwrap(); + let ready = wait_ready(fence, 1, Some(5)); + let abandoned = wait_reservation(waits.reserve(queue, ready).unwrap()); + let stale = abandoned.token.unwrap(); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Pending(token)) if token == stale)); + assert!(matches!(waits.reserve(queue, wait_ready(fence, 0, None)), Err(ForegroundWaitError::Pending(_)))); + drop(abandoned); + + let accepted = wait_reservation(waits.reserve(queue, wait_ready(fence, 2, Some(6))).unwrap()).arm().unwrap(); + let accepted_token = accepted.token.unwrap(); + accepted.rollback().unwrap(); + let newer = wait_reservation(waits.reserve(queue, wait_ready(fence, 3, Some(7))).unwrap()); + assert_eq!(waits.0.lock().unwrap().transition(accepted_token, ForegroundWaitState::Accepted, None), + Err(ForegroundWaitError::StaleToken)); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Pending(token)) if token == newer.token.unwrap())); + drop(newer); + waits.retire_queue(queue).unwrap(); + let replacement = waits.register_queue(0xB).unwrap(); + assert!(replacement.generation > queue.generation); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Queue))); + assert!(matches!(waits.reserve(replacement, ready), Ok(ForegroundWaitDecision::Reserve(_)))); + } + + #[test] + fn foreground_wait_unpublished_acceptance_fails_closed() { + let waits = ForegroundWaits::new(107, 701).unwrap(); + let queue = waits.register_queue(0xC).unwrap(); + let ready = wait_ready(waits.fence(), 1, Some(9)); + let accepted = wait_reservation(waits.reserve(queue, ready).unwrap()).arm().unwrap(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _accepted = accepted; + panic!("after native wait acceptance"); + })); + assert!(result.is_err()); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Uncertain))); + assert!(matches!(waits.reserve(queue, wait_ready(waits.fence(), 0, None)), Err(ForegroundWaitError::Uncertain))); + } + + #[test] + fn foreground_wait_generation_replacement_rejects_old_guards_and_fences() { + let waits = ForegroundWaits::new(109, 801).unwrap(); + let queue = waits.register_queue(0xD).unwrap(); + let old_fence = waits.fence(); + let old_ready = wait_ready(old_fence, 1, Some(3)); + let old = wait_reservation(waits.reserve(queue, old_ready).unwrap()); + waits.replace_generation(109, 110, 802).unwrap(); + drop(old); + assert!(matches!(waits.reserve(queue, old_ready), Err(ForegroundWaitError::StaleGeneration))); + assert_eq!(waits.replace_generation(110, 109, 803), Err(ForegroundWaitError::StaleGeneration)); + assert_eq!(waits.replace_generation(110, 111, 801), Err(ForegroundWaitError::Fence)); + let current = wait_ready(waits.fence(), 1, Some(4)); + assert!(matches!(waits.reserve(queue, current), Ok(ForegroundWaitDecision::Reserve(_)))); + } + fn upload_observation(page: usize, pool: (u32, u32), source_word: u64) -> UploadPageObservation { let mut source = ZERO_HASHES; source[1] = source_word; From bd64a1dbb2546eb69860a3d6522ccbe20ea65100 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:26:24 -0800 Subject: [PATCH 242/265] D3D12.X: remove superseded sparse commit model The coordinated batch transaction now owns acceptance, poisoning, and publication semantics. Preserve unwind, callback-order, and staging-ownership coverage on that implementation before removing the duplicate test-only protocol. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 300 +++++----------------------- 1 file changed, 55 insertions(+), 245 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 51696941d6..bba081ded8 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1297,18 +1297,6 @@ enum UploadPlanCommitError<E> { Commit(E), } -#[derive(Debug, Eq, PartialEq)] -#[allow(dead_code)] -enum SparseUploadCommitError<C, E, S> { - Invalid(UploadPlanInvalid), - Reserve(UploadReservationError), - Copy(C), - StagingSize, - Prepare(E), - Signal(S), - Publish(UploadReservationError), -} - /// Private owned stand-in for a future mapped staging allocation. Keeping the copied bytes here /// makes it impossible for the record/execute callback to retain a borrowed title-memory view. #[allow(dead_code)] @@ -1474,42 +1462,6 @@ impl SparseUploadPlan { Ok((result, claim.commit())) } - /// Inert model of the future short serialized commit phase. Callers must hold the sparse - /// commit exclusion and make `copy` produce the bytes whose identities `observe` validated. - /// No live allocator, command list, queue, or staging allocation is touched by this model. - fn commit_reserved<C, E, S>( - mut self, - state_generation: u64, - mapping_epoch: u64, - observe: impl FnMut(usize) -> Option<UploadPageObservation>, - reservations: &UploadReservations, - slot: usize, - bytes: usize, - copy: impl FnOnce(UploadRingRange, &[PlannedUploadPage]) -> Result<Vec<u8>, C>, - prepare: impl FnOnce(&OwnedUploadStaging, &[PlannedUploadPage]) -> Result<(), E>, - execute: impl FnOnce(&OwnedUploadStaging, &[PlannedUploadPage]), - signal: impl FnOnce() -> Result<u64, S>, - ) -> Result<(UploadSubmissionReceipt, WorkClaimResolution), SparseUploadCommitError<C, E, S>> { - self.validate(state_generation, mapping_epoch, observe).map_err(SparseUploadCommitError::Invalid)?; - let reservation = reservations.reserve(slot, bytes).map_err(SparseUploadCommitError::Reserve)?; - let range = reservation.range(); - let copied = copy(range, &self.pages).map_err(SparseUploadCommitError::Copy)?; - if copied.len() != bytes { - return Err(SparseUploadCommitError::StagingSize); - } - let staging = OwnedUploadStaging { range, bytes: copied.into_boxed_slice() }; - prepare(&staging, &self.pages).map_err(SparseUploadCommitError::Prepare)?; - - // Arm fail-closed ownership before crossing the void execution boundary: execution may - // have accepted work even if the callback unwinds before it can report anything. - let accepted = AcceptedSparseUpload { - reservation: Some(reservation), - claim: self.claim.take(), - }; - execute(&staging, &self.pages); - let fence = signal().map_err(SparseUploadCommitError::Signal)?; - accepted.publish(fence).map_err(SparseUploadCommitError::Publish) - } } #[derive(Debug, Eq, PartialEq)] @@ -1905,32 +1857,6 @@ impl Drop for UploadReservation { } } -/// Owns both exact ledgers once execute has accepted work. Dropping it is deliberately not a -/// rollback: an untracked execution must quarantine its slot/ring and must not be retried. -struct AcceptedSparseUpload { - reservation: Option<UploadReservation>, - claim: Option<SparseWorkClaim>, -} - -impl AcceptedSparseUpload { - fn publish(mut self, fence: u64) -> Result<(UploadSubmissionReceipt, WorkClaimResolution), UploadReservationError> { - let result = self.reservation.take().unwrap().publish_after_accept(fence); - let resolution = self.claim.take().unwrap().commit(); - result.map(|receipt| (receipt, resolution)) - } -} - -impl Drop for AcceptedSparseUpload { - fn drop(&mut self) { - if let Some(reservation) = self.reservation.take() { - let _ = reservation.poison(); - } - if let Some(claim) = self.claim.take() { - let _ = claim.commit(); - } - } -} - enum CoordinatedPublishError { Reservation(UploadReservationError), Batch(SparseBatchError), @@ -5261,6 +5187,61 @@ mod tests { ) } + #[test] + fn coordinated_preaccept_unwind_cancels_reservation_and_leaves_batch_visible() { + for panic_at in ["copy", "prepare"] { + let (batches, plan, observation, token) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| -> Result<Vec<u8>, ()> { + if panic_at == "copy" { panic!("copy panicked") } + Ok(vec![0; 64]) + }, + |_, _| -> Result<(), ()> { + if panic_at == "prepare" { panic!("prepare panicked") } + Ok(()) + }, + |_, _| {}, || Ok::<_, ()>(9), + ); + })); + assert!(result.is_err()); + assert_eq!(batches.observe(1, 9), Ok(ClaimFrontierAction::TakeOver(token))); + let ledger = reservations.0.lock().unwrap(); + assert!(!ledger.poisoned && ledger.records.is_empty()); + assert!(ledger.slots.iter().all(Option::is_none)); + } + } + + #[test] + fn coordinated_commit_orders_callbacks_and_owns_copied_staging() { + let (_, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let calls = std::cell::RefCell::new(Vec::new()); + let receipt = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 4, + |range, pages| { + calls.borrow_mut().push("copy"); + assert_eq!(range, UploadRingRange { start: 0, end: 4 }); + assert_eq!(pages[0].page, observation.page); + Ok::<_, ()>(vec![1, 2, 3, 4]) + }, + |staging, _| { + calls.borrow_mut().push("prepare"); + assert_eq!(&*staging.bytes, &[1, 2, 3, 4]); + Ok::<_, ()>(()) + }, + |staging, _| { + calls.borrow_mut().push("execute"); + assert_eq!(&*staging.bytes, &[1, 2, 3, 4]); + }, + || { calls.borrow_mut().push("signal"); Ok::<_, ()>(9) }, + ).unwrap(); + assert_eq!(&*calls.borrow(), &["copy", "prepare", "execute", "signal"]); + assert_eq!(reservations.complete(receipt), Ok(4)); + } + #[test] fn coordinated_plan_preaccept_failures_stay_visible_and_takeover_revokes() { for failure in ["validate", "reservation generation", "reserve", "copy", "size", "prepare"] { @@ -5521,177 +5502,6 @@ mod tests { assert_eq!(claims.claim(2).unwrap().pages().len(), 2); } - #[test] - fn sparse_commit_protocol_orders_owned_copy_execute_publish_and_consume() { - let (claims, plan, observation) = one_page_upload_plan(); - let reservations = UploadReservations::new(31, 1, 256, 64); - let events = std::cell::RefCell::new(Vec::new()); - let result = plan.commit_reserved( - 31, - 7, - |_| { - events.borrow_mut().push("validate"); - Some(observation.clone()) - }, - &reservations, - 0, - 64, - |range, pages| { - assert!(reservations.0.lock().unwrap().slots[0].is_some(), "copy preceded reservation"); - assert_eq!(pages.len(), 1); - assert_eq!(range, UploadRingRange { start: 0, end: 64 }); - events.borrow_mut().push("copy"); - Ok::<_, ()>(vec![0xA5; 64]) - }, - |staging, pages| { - assert_eq!(staging.range, UploadRingRange { start: 0, end: 64 }); - assert_eq!(&*staging.bytes, &[0xA5; 64]); - assert_eq!(pages[0].page, 0x2_1000); - events.borrow_mut().push("prepare"); - Ok::<_, ()>(()) - }, - |staging, _| { - assert_eq!(&*staging.bytes, &[0xA5; 64]); - events.borrow_mut().push("execute"); - }, - || { - events.borrow_mut().push("signal"); - Ok::<_, ()>(9) - }, - ); - let (receipt, resolution) = result.unwrap(); - assert_eq!(&*events.borrow(), &["validate", "copy", "prepare", "execute", "signal"]); - assert_eq!(resolution, WorkClaimResolution::Committed); - assert!(claims.claim(1).is_none(), "accepted submission restored its work"); - assert_eq!(reservations.complete(receipt), Ok(64)); - } - - #[test] - fn sparse_commit_protocol_restores_every_pre_execute_failure() { - let reservations = UploadReservations::new(31, 1, 256, 64); - let (claims, plan, observation) = one_page_upload_plan(); - let result = plan.commit_reserved( - 32, 7, |_| Some(observation.clone()), &reservations, 0, 64, - |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, || Ok::<_, ()>(1), - ); - assert_eq!(result, Err(SparseUploadCommitError::Invalid(UploadPlanInvalid::StateGeneration))); - assert!(claims.claim(1).is_some(), "validation failure consumed work"); - - let occupied = reservations.reserve(0, 64).unwrap(); - let (claims, plan, observation) = one_page_upload_plan(); - let result = plan.commit_reserved( - 31, 7, |_| Some(observation.clone()), &reservations, 0, 64, - |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, || Ok::<_, ()>(1), - ); - assert_eq!(result, Err(SparseUploadCommitError::Reserve(UploadReservationError::SlotBusy))); - assert!(claims.claim(1).is_some(), "reservation refusal consumed work"); - drop(occupied); - - for failure in ["copy", "size", "prepare"] { - let reservations = UploadReservations::new(31, 1, 256, 64); - let (claims, plan, observation) = one_page_upload_plan(); - let result = plan.commit_reserved( - 31, - 7, - |_| Some(observation.clone()), - &reservations, - 0, - 64, - |_, _| match failure { - "copy" => Err("copy"), - "size" => Ok(vec![0; 63]), - _ => Ok(vec![0; 64]), - }, - |_, _| if failure == "prepare" { Err("prepare") } else { Ok(()) }, - |_, _| {}, - || Ok::<_, &'static str>(1), - ); - match failure { - "copy" => assert_eq!(result, Err(SparseUploadCommitError::Copy("copy"))), - "size" => assert_eq!(result, Err(SparseUploadCommitError::StagingSize)), - _ => assert_eq!(result, Err(SparseUploadCommitError::Prepare("prepare"))), - } - assert!(claims.claim(1).is_some(), "{failure} failure consumed work"); - let ledger = reservations.0.lock().unwrap(); - assert!(!ledger.poisoned); - assert!(ledger.slots[0].is_none(), "{failure} failure retained its slot"); - } - } - - #[test] - fn sparse_commit_protocol_unwind_changes_from_rollback_to_poison_after_accept() { - let reservations = UploadReservations::new(31, 1, 256, 64); - let (claims, plan, observation) = one_page_upload_plan(); - let before = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let _ = plan.commit_reserved( - 31, 7, |_| Some(observation.clone()), &reservations, 0, 64, - |_, _| -> Result<Vec<u8>, ()> { panic!("copy panicked") }, - |_, _| Ok::<_, ()>(()), |_, _| {}, || Ok::<_, ()>(1), - ); - })); - assert!(before.is_err()); - assert!(claims.claim(1).is_some(), "pre-execute unwind consumed work"); - assert!(!reservations.0.lock().unwrap().poisoned); - - let reservations = UploadReservations::new(31, 1, 256, 64); - let (claims, plan, observation) = one_page_upload_plan(); - let submitted = std::cell::Cell::new(false); - let after = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let _ = plan.commit_reserved( - 31, 7, |_| Some(observation.clone()), &reservations, 0, 64, - |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), - |_, _| { - submitted.set(true); // Model the void ExecuteCommandLists side effect. - panic!("execute panicked after submit") - }, - || Ok::<_, ()>(1), - ); - })); - assert!(after.is_err()); - assert!(submitted.get()); - assert!(claims.claim(1).is_none(), "accepted execution was made retryable"); - let ledger = reservations.0.lock().unwrap(); - assert!(ledger.poisoned); - assert!(matches!(ledger.records[&1].state, UploadReservationState::Poisoned)); - } - - #[test] - fn sparse_commit_protocol_signal_failure_poison_and_receipts_retire_in_order() { - let reservations = UploadReservations::new(31, 2, 256, 64); - let (failed_claims, failed, observation) = one_page_upload_plan(); - let result = failed.commit_reserved( - 31, 7, |_| Some(observation.clone()), &reservations, 0, 64, - |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, - || Err::<u64, _>("signal"), - ); - assert_eq!(result, Err(SparseUploadCommitError::Signal("signal"))); - assert!(failed_claims.claim(1).is_none()); - assert!(reservations.0.lock().unwrap().poisoned); - - let reservations = UploadReservations::new(31, 1, 256, 64); - let (failed_claims, failed, observation) = one_page_upload_plan(); - let result = failed.commit_reserved( - 31, 7, |_| Some(observation.clone()), &reservations, 0, 64, - |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, || Ok::<_, ()>(0), - ); - assert_eq!(result, Err(SparseUploadCommitError::Publish(UploadReservationError::State))); - assert!(failed_claims.claim(1).is_none(), "accepted work was restored after failed publication"); - assert!(reservations.0.lock().unwrap().poisoned); - - let reservations = UploadReservations::new(31, 2, 256, 64); - let mut receipts = Vec::new(); - for (slot, fence) in [(0, 3), (1, 4)] { - let (_, plan, observation) = one_page_upload_plan(); - receipts.push(plan.commit_reserved( - 31, 7, |_| Some(observation.clone()), &reservations, slot, 64, - |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, - || Ok::<_, ()>(fence), - ).unwrap().0); - } - assert_eq!(reservations.complete(receipts[1]), Ok(0), "newer receipt reclaimed older work"); - assert_eq!(reservations.complete(receipts[0]), Ok(128)); - } - #[test] fn upload_reservations_reclaim_only_a_contiguous_retired_prefix() { let reservations = UploadReservations::new(41, 2, 256, 64); From 0ab510a29345d24a9ebc286724b2e151d515f6fa Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:27:34 -0800 Subject: [PATCH 243/265] D3D12.X: remove superseded sparse upload plan The coordinated upload plan uses the shared page construction and validation primitives directly. Preserve intent, range, incomplete-build, and identity-validation coverage on those paths before removing the older claim-owning plan. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 305 +++++----------------------- 1 file changed, 48 insertions(+), 257 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index bba081ded8..340dc50197 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1289,14 +1289,6 @@ enum UploadPlanInvalid { SentHashes, SourceHashes, } - -#[derive(Debug, Eq, PartialEq)] -#[allow(dead_code)] -enum UploadPlanCommitError<E> { - Invalid(UploadPlanInvalid), - Commit(E), -} - /// Private owned stand-in for a future mapped staging allocation. Keeping the copied bytes here /// makes it impossible for the record/execute callback to retain a borrowed title-memory view. #[allow(dead_code)] @@ -1353,117 +1345,6 @@ fn validate_upload_pages( Ok(()) } -/// Inert immutable work between an exact journal claim and a future short serialized commit. -/// Dropping an uncommitted plan restores its claim. No command allocator, list or staging range is -/// opened or reserved here; those remain responsibilities of the later commit-phase stage. A -/// future caller must run `commit_if_valid` under the serialized sparse-state commit exclusion so -/// validation and publication cannot be separated by a remap. That exclusion does not stop title -/// CPU writes: the fallible closure must own or revalidate source bytes before it returns success. -#[allow(dead_code)] -struct SparseUploadPlan { - claim: Option<SparseWorkClaim>, - state_generation: u64, - mapping_epoch: u64, - pages: Vec<PlannedUploadPage>, -} - -#[allow(dead_code)] -impl SparseUploadPlan { - fn build( - claim: SparseWorkClaim, - state_generation: u64, - mapping_epoch: u64, - mut observe: impl FnMut(usize) -> Option<UploadPageObservation>, - ) -> Option<Self> { - let claimed = claim.claimed.as_ref()?; - if claimed.token.state_generation != state_generation { - return None; - } - let mut pages = Vec::with_capacity(claimed.pages.len()); - for &(page, reasons) in &claimed.pages { - let observation = observe(page)?; - if observation.page != page || observation.hole { - return None; - } - let dirty = reasons.0 & (WorkReasons::DIRTY.0 | WorkReasons::RETRY.0) != 0; - let mut dirty_ranges = Vec::new(); - if dirty { - let sent = observation.sent.as_ref().unwrap_or(&ZERO_HASHES); - for (chunk, (&source, &previous)) in observation.source.iter().zip(sent).enumerate() { - if source != previous { - push_run(&mut dirty_ranges, page + chunk * CHUNK, CHUNK); - } - } - } - pages.push(PlannedUploadPage { - page, - tile: page & !(TILE - 1), - pool: observation.pool, - reasons, - zero: reasons.0 & WorkReasons::ZERO.0 != 0, - dirty, - dirty_ranges, - sent: observation.sent, - source: observation.source, - }); - } - Some(Self { claim: Some(claim), state_generation, mapping_epoch, pages }) - } - - fn pages(&self) -> &[PlannedUploadPage] { - &self.pages - } - - fn validate( - &self, - state_generation: u64, - mapping_epoch: u64, - mut observe: impl FnMut(usize) -> Option<UploadPageObservation>, - ) -> Result<(), UploadPlanInvalid> { - if state_generation != self.state_generation { - return Err(UploadPlanInvalid::StateGeneration); - } - if mapping_epoch != self.mapping_epoch { - return Err(UploadPlanInvalid::MappingEpoch); - } - for planned in &self.pages { - let current = observe(planned.page).ok_or(UploadPlanInvalid::MissingPage)?; - if current.page != planned.page - || current.page & !(TILE - 1) != planned.tile - || current.pool != planned.pool - || current.hole - { - return Err(UploadPlanInvalid::Mapping); - } - if current.sent != planned.sent { - return Err(UploadPlanInvalid::SentHashes); - } - if current.source != planned.source { - return Err(UploadPlanInvalid::SourceHashes); - } - } - Ok(()) - } - - /// Keep the exact work claim armed through the future serialized commit. Only a successful - /// closure consumes it; validation failure, commit refusal, or unwind restores it through the - /// claim guard. The closure must return success only after submission has accepted the work - /// and any source bytes it names can no longer change underneath that submission. - fn commit_if_valid<T, E>( - mut self, - state_generation: u64, - mapping_epoch: u64, - observe: impl FnMut(usize) -> Option<UploadPageObservation>, - commit: impl FnOnce(&[PlannedUploadPage]) -> Result<T, E>, - ) -> Result<(T, WorkClaimResolution), UploadPlanCommitError<E>> { - self.validate(state_generation, mapping_epoch, observe).map_err(UploadPlanCommitError::Invalid)?; - let result = commit(&self.pages).map_err(UploadPlanCommitError::Commit)?; - let claim = self.claim.take().expect("finished sparse upload plan"); - Ok((result, claim.commit())) - } - -} - #[derive(Debug, Eq, PartialEq)] #[allow(dead_code)] enum CoordinatedSparseUploadError<C, E, S> { @@ -5156,15 +5037,6 @@ mod tests { UploadPageObservation { page, pool, hole: false, sent: Some(ZERO_HASHES), source } } - fn one_page_upload_plan() -> (SparseWorkClaims, SparseUploadPlan, UploadPageObservation) { - let claims = SparseWorkClaims::new(31); - assert!(claims.add_dirty_pages([0x2_1000])); - let claim = claims.claim(1).unwrap(); - let observation = upload_observation(0x2_1000, (4, 9), 0xA5); - let plan = SparseUploadPlan::build(claim, 31, 7, |_| Some(observation.clone())).unwrap(); - (claims, plan, observation) - } - fn coordinated_upload_fixture( owner: u64, ) -> (SparseBatches, CoordinatedSparseUploadPlan, UploadPageObservation, ClaimFrontierToken) { @@ -5187,6 +5059,54 @@ mod tests { ) } + #[test] + fn shared_upload_page_builder_preserves_intent_order_and_dirty_ranges() { + let claimed = [ + (0x1_1000, WorkReasons(WorkReasons::ZERO.0 | WorkReasons::DIRTY.0)), + (0x1_2000, WorkReasons::RETRY), + ]; + let first = upload_observation(0x1_1000, (2, 3), 0x91); + let second = upload_observation(0x1_2000, (2, 3), ZERO_HASH); + let pages = build_upload_pages(&claimed, |page| match page { + 0x1_1000 => Some(first.clone()), + 0x1_2000 => Some(second.clone()), + _ => None, + }).unwrap(); + + assert_eq!(pages.iter().map(|page| page.page).collect::<Vec<_>>(), [0x1_1000, 0x1_2000]); + assert!(pages[0].zero && pages[0].dirty); + assert_eq!(pages[0].dirty_ranges, [(0x1_1000 + CHUNK, 2 * CHUNK)]); + assert!(!pages[1].zero && pages[1].dirty); + assert!(pages[1].dirty_ranges.is_empty(), "retry intent was lost when no chunks changed"); + assert!(build_upload_pages(&claimed, |page| { + (page == 0x1_1000).then(|| first.clone()) + }).is_none()); + } + + #[test] + fn coordinated_plan_revalidates_every_sparse_page_identity() { + let (_, plan, observation, _) = coordinated_upload_fixture(1); + assert_eq!(plan.validate(72, 7, |_| Some(observation.clone())), Err(UploadPlanInvalid::StateGeneration)); + assert_eq!(plan.validate(71, 8, |_| Some(observation.clone())), Err(UploadPlanInvalid::MappingEpoch)); + assert_eq!(plan.validate(71, 7, |_| None), Err(UploadPlanInvalid::MissingPage)); + + let mut remapped = observation.clone(); + remapped.page += TILE; + assert_eq!(plan.validate(71, 7, |_| Some(remapped.clone())), Err(UploadPlanInvalid::Mapping)); + let mut repooled = observation.clone(); + repooled.pool.1 += 1; + assert_eq!(plan.validate(71, 7, |_| Some(repooled.clone())), Err(UploadPlanInvalid::Mapping)); + let mut hole = observation.clone(); + hole.hole = true; + assert_eq!(plan.validate(71, 7, |_| Some(hole.clone())), Err(UploadPlanInvalid::Mapping)); + let mut resent = observation.clone(); + resent.sent.as_mut().unwrap()[3] ^= 1; + assert_eq!(plan.validate(71, 7, |_| Some(resent.clone())), Err(UploadPlanInvalid::SentHashes)); + let mut rewritten = observation.clone(); + rewritten.source[3] ^= 1; + assert_eq!(plan.validate(71, 7, |_| Some(rewritten.clone())), Err(UploadPlanInvalid::SourceHashes)); + } + #[test] fn coordinated_preaccept_unwind_cancels_reservation_and_leaves_batch_visible() { for panic_at in ["copy", "prepare"] { @@ -5373,135 +5293,6 @@ mod tests { assert_eq!(reservations.complete(second_receipt), Ok(128)); } - #[test] - fn sparse_upload_plan_preserves_claim_order_intent_and_source_ranges() { - let claims = SparseWorkClaims::new(29); - assert!(claims.add_zero_ranges(&[(0x1_1000, PAGE)])); - assert!(claims.add_dirty_pages([0x1_1000])); - assert!(claims.add_retry_pages([0x1_2000])); - let claim = claims.claim(2).unwrap(); - let first = upload_observation(0x1_1000, (2, 3), 0x91); - let second = upload_observation(0x1_2000, (2, 3), ZERO_HASH); - let plan = SparseUploadPlan::build(claim, 29, 5, |page| match page { - 0x1_1000 => Some(first.clone()), - 0x1_2000 => Some(second.clone()), - _ => None, - }).unwrap(); - - assert_eq!(plan.pages().iter().map(|page| page.page).collect::<Vec<_>>(), [0x1_1000, 0x1_2000]); - assert!(plan.pages()[0].zero); - assert!(plan.pages()[0].dirty); - assert_eq!(plan.pages()[0].dirty_ranges, [(0x1_1000 + CHUNK, 2 * CHUNK)]); - assert!(!plan.pages()[1].zero); - assert!(plan.pages()[1].dirty, "retry work lost its dirty intent when no chunks changed"); - assert!(plan.pages()[1].dirty_ranges.is_empty()); - assert_eq!( - plan.commit_if_valid( - 29, - 5, - |page| match page { - 0x1_1000 => Some(first.clone()), - 0x1_2000 => Some(second.clone()), - _ => None, - }, - |_| Ok::<_, ()>(17), - ), - Ok((17, WorkClaimResolution::Committed)), - ); - assert!(claims.claim(1).is_none(), "committed plan restored its claim"); - } - - #[test] - fn sparse_upload_plan_generation_and_epoch_failures_restore_the_claim() { - let (claims, plan, observation) = one_page_upload_plan(); - assert_eq!( - plan.commit_if_valid(32, 7, |_| Some(observation.clone()), |_| Ok::<_, ()>(())), - Err(UploadPlanCommitError::Invalid(UploadPlanInvalid::StateGeneration)), - ); - let restored = claims.claim(1).expect("generation failure restored work"); - assert_eq!(restored.cancel(), WorkClaimResolution::Restored); - - let claim = claims.claim(1).unwrap(); - let plan = SparseUploadPlan::build(claim, 31, 7, |_| Some(observation.clone())).unwrap(); - assert_eq!( - plan.commit_if_valid(31, 8, |_| Some(observation.clone()), |_| Ok::<_, ()>(())), - Err(UploadPlanCommitError::Invalid(UploadPlanInvalid::MappingEpoch)), - ); - assert!(claims.claim(1).is_some(), "epoch failure did not restore work"); - } - - #[test] - fn sparse_upload_plan_revalidates_mapping_sent_and_source_identities() { - for expected in [ - UploadPlanInvalid::MissingPage, - UploadPlanInvalid::Mapping, - UploadPlanInvalid::SentHashes, - UploadPlanInvalid::SourceHashes, - ] { - let (claims, plan, observation) = one_page_upload_plan(); - let result = plan.commit_if_valid( - 31, - 7, - |_| { - let mut changed = observation.clone(); - match expected { - UploadPlanInvalid::MissingPage => return None, - UploadPlanInvalid::Mapping => changed.pool.1 += 1, - UploadPlanInvalid::SentHashes => changed.sent.as_mut().unwrap()[3] ^= 1, - UploadPlanInvalid::SourceHashes => changed.source[3] ^= 1, - _ => unreachable!(), - } - Some(changed) - }, - |_| Ok::<_, ()>(()), - ); - assert_eq!(result, Err(UploadPlanCommitError::Invalid(expected))); - assert!(claims.claim(1).is_some(), "{expected:?} did not restore work"); - } - } - - #[test] - fn sparse_upload_plan_commit_failure_restores_the_validated_claim() { - let (claims, plan, observation) = one_page_upload_plan(); - let result = plan.commit_if_valid( - 31, - 7, - |_| Some(observation.clone()), - |pages| { - assert_eq!(pages.len(), 1, "validated commit lost its planned page"); - Err::<(), _>("queue refused upload") - }, - ); - assert_eq!(result, Err(UploadPlanCommitError::Commit("queue refused upload"))); - assert!(claims.claim(1).is_some(), "failed commit consumed its exact work claim"); - } - - #[test] - fn sparse_upload_plan_commit_unwind_restores_the_validated_claim() { - let (claims, plan, observation) = one_page_upload_plan(); - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let _ = plan.commit_if_valid( - 31, - 7, - |_| Some(observation.clone()), - |_| -> Result<(), ()> { panic!("driver submission panicked") }, - ); - })); - assert!(result.is_err()); - assert!(claims.claim(1).is_some(), "panicked commit consumed its exact work claim"); - } - - #[test] - fn incomplete_sparse_upload_plan_construction_restores_its_claim() { - let claims = SparseWorkClaims::new(37); - assert!(claims.add_dirty_pages([0x3_0000, 0x3_1000])); - let claim = claims.claim(2).unwrap(); - assert!(SparseUploadPlan::build(claim, 37, 1, |page| { - (page == 0x3_0000).then(|| upload_observation(page, (5, 1), 7)) - }).is_none()); - assert_eq!(claims.claim(2).unwrap().pages().len(), 2); - } - #[test] fn upload_reservations_reclaim_only_a_contiguous_retired_prefix() { let reservations = UploadReservations::new(41, 2, 256, 64); From 2116d1076e51306ad75d4a0e46a4091a41d0ec12 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:28:43 -0800 Subject: [PATCH 244/265] D3D12.X: remove superseded sparse claim wrappers SparseBatches now owns the guarded claim lifecycle used by coordinated uploads. Preserve ordering, reason merging, exact restoration, and stale-producer coverage on the shared ledger and batch model before removing the older guards. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 219 ++++++---------------------- 1 file changed, 45 insertions(+), 174 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 340dc50197..1772d490ed 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -388,102 +388,6 @@ impl WorkClaimLedger { } } -/// Shared owner used by future planners. A dropped guard restores only its exact still-current -/// claim, so unwind is safe and an old guard cannot cancel work reserved after it finished. -#[derive(Clone)] -#[allow(dead_code)] -struct SparseWorkClaims { - ledger: Arc<Mutex<WorkClaimLedger>>, - state_generation: u64, -} - -#[allow(dead_code)] -impl SparseWorkClaims { - fn new(state_generation: u64) -> Self { - Self { ledger: Arc::new(Mutex::new(WorkClaimLedger::new(state_generation))), state_generation } - } - - fn add_zero_ranges(&self, ranges: &[(usize, usize)]) -> bool { - let mut ledger = self.ledger.lock().unwrap(); - if ledger.state_generation != self.state_generation { - return false; - } - ledger.add_zero_ranges(ranges); - true - } - - fn add_retry_pages(&self, pages: impl IntoIterator<Item = usize>) -> bool { - let mut ledger = self.ledger.lock().unwrap(); - if ledger.state_generation != self.state_generation { - return false; - } - ledger.add_retry_pages(pages); - true - } - - fn add_dirty_pages(&self, pages: impl IntoIterator<Item = usize>) -> bool { - let mut ledger = self.ledger.lock().unwrap(); - if ledger.state_generation != self.state_generation { - return false; - } - ledger.add_dirty_pages(pages); - true - } - - fn claim(&self, limit: usize) -> Option<SparseWorkClaim> { - let claimed = { - let mut ledger = self.ledger.lock().unwrap(); - if ledger.state_generation != self.state_generation { - return None; - } - ledger.claim(limit)? - }; - Some(SparseWorkClaim { ledger: self.ledger.clone(), claimed: Some(claimed) }) - } - - /// Replace only the exact generation this handle names. The returned handle names the new - /// generation; this handle and every clone of it become permanently stale. - fn replace_generation(&self, state_generation: u64) -> Option<Self> { - let mut ledger = self.ledger.lock().unwrap(); - if ledger.state_generation != self.state_generation || state_generation == self.state_generation { - return None; - } - ledger.replace_generation(state_generation); - Some(Self { ledger: self.ledger.clone(), state_generation }) - } -} - -#[allow(dead_code)] -struct SparseWorkClaim { - ledger: Arc<Mutex<WorkClaimLedger>>, - claimed: Option<ClaimedWork>, -} - -#[allow(dead_code)] -impl SparseWorkClaim { - fn pages(&self) -> &[(usize, WorkReasons)] { - self.claimed.as_ref().map_or(&[], |claim| claim.pages.as_slice()) - } - - fn commit(mut self) -> WorkClaimResolution { - let claim = self.claimed.take().expect("finished sparse work claim"); - self.ledger.lock().unwrap().commit(claim.token) - } - - fn cancel(mut self) -> WorkClaimResolution { - let claim = self.claimed.take().expect("finished sparse work claim"); - self.ledger.lock().unwrap().cancel(claim.token) - } -} - -impl Drop for SparseWorkClaim { - fn drop(&mut self) { - if let Some(claim) = self.claimed.take() { - let _ = self.ledger.lock().unwrap().restore(claim.token); - } - } -} - /// Identity of one future sparse batch while it crosses planning and queue acceptance. `lease` /// changes on takeover, so an old owner cannot publish or discard the new owner's batch. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -4621,43 +4525,6 @@ mod tests { assert_eq!(retry_journal(PreparationOutcome::ExecutedUntracked, vec![0x3000], &runs), [0x1000, 0x2000, 0x3000]); } - #[test] - fn sparse_work_claims_merge_sources_and_reserve_pages_in_order() { - let claims = SparseWorkClaims::new(7); - claims.add_zero_ranges(&[(0x3000, 2 * PAGE)]); - claims.add_retry_pages([0x3001, 0x1000, 0x1000]); - claims.add_dirty_pages([0x4000, 0x6001, 0x6000]); - - let first = claims.claim(2).unwrap(); - assert_eq!(first.pages().iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ - (0x1000, WorkReasons::RETRY.0), - (0x3000, WorkReasons::ZERO.0 | WorkReasons::RETRY.0), - ]); - let second = claims.claim(8).unwrap(); - assert_eq!(second.pages().iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ - (0x4000, WorkReasons::ZERO.0 | WorkReasons::DIRTY.0), - (0x6000, WorkReasons::DIRTY.0), - ]); - assert!(second.claimed.as_ref().unwrap().token.serial > first.claimed.as_ref().unwrap().token.serial); - - // Work observed after the first snapshot stays journalled, but cannot be claimed until - // the exact older owner finishes. - claims.add_dirty_pages([0x1000]); - assert!(claims.claim(1).is_none()); - assert_eq!(second.cancel(), WorkClaimResolution::Restored); - let out_of_order = claims.claim(1).unwrap(); - assert_eq!(out_of_order.pages()[0].0, 0x4000, "a newer cancellation disturbed the older owner"); - assert_eq!(first.commit(), WorkClaimResolution::Committed); - let later = claims.claim(1).unwrap(); - assert_eq!(later.pages().iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ - (0x1000, WorkReasons::DIRTY.0), - ]); - assert_eq!(later.commit(), WorkClaimResolution::Committed); - assert_eq!(out_of_order.cancel(), WorkClaimResolution::Restored); - let restored = claims.claim(8).unwrap(); - assert_eq!(restored.pages().iter().map(|(page, _)| *page).collect::<Vec<_>>(), [0x4000, 0x6000]); - } - #[test] fn late_claim_completion_cannot_change_a_newer_owner() { let mut ledger = WorkClaimLedger::new(11); @@ -4673,47 +4540,6 @@ mod tests { assert!(ledger.available.is_empty()); } - #[test] - fn dropped_sparse_work_claim_restores_after_unwind() { - let claims = SparseWorkClaims::new(13); - claims.add_dirty_pages([0xA000, 0x9000]); - let result = std::panic::catch_unwind({ - let claims = claims.clone(); - move || { - let claim = claims.claim(1).unwrap(); - assert_eq!(claim.pages()[0].0, 0x9000); - panic!("planned upload failed"); - } - }); - assert!(result.is_err()); - let restored = claims.claim(2).unwrap(); - assert_eq!(restored.pages().iter().map(|(page, _)| *page).collect::<Vec<_>>(), [0x9000, 0xA000]); - } - - #[test] - fn replaced_sparse_generation_rejects_old_claims_and_producer_clones() { - let claims = SparseWorkClaims::new(17); - let stale_clone = claims.clone(); - assert!(claims.add_zero_ranges(&[(0xB000, PAGE)])); - let old = claims.claim(1).unwrap(); - let old_token = old.claimed.as_ref().unwrap().token; - let current = claims.replace_generation(18).unwrap(); - assert!(!claims.add_dirty_pages([0xC000]), "replaced handle added current work"); - assert!(!stale_clone.add_retry_pages([0xD000]), "stale clone added current work"); - assert!(claims.claim(1).is_none(), "replaced handle claimed current work"); - assert!(stale_clone.replace_generation(19).is_none(), "stale clone replaced current generation"); - assert!(current.add_dirty_pages([0xB000])); - assert_eq!(current.ledger.lock().unwrap().restore(old_token), WorkClaimResolution::StaleGeneration); - drop(old); - - let claim = current.claim(1).unwrap(); - assert_eq!(claim.pages().iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ - (0xB000, WorkReasons::DIRTY.0), - ]); - assert_eq!(claim.commit(), WorkClaimResolution::Committed); - assert!(current.claim(1).is_none(), "stale producers polluted the current journal"); - } - #[test] fn foreground_queue_cannot_pass_or_steal_an_unreceipted_claim() { let mut frontier = ClaimFrontier::new(23); @@ -4810,6 +4636,51 @@ mod tests { assert_eq!(takeover.observe(43, token.epoch, 1), Ok(ClaimFrontierAction::Progress(token))); } + #[test] + fn work_claim_ledger_merges_orders_and_restores_exact_out_of_order_work() { + let mut ledger = WorkClaimLedger::new(7); + ledger.add_zero_ranges(&[(0x3000, 2 * PAGE)]); + ledger.add_retry_pages([0x3001, 0x1000, 0x1000]); + ledger.add_dirty_pages([0x4000, 0x6001, 0x6000]); + + let first = ledger.claim(2).unwrap(); + assert_eq!(first.pages.iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ + (0x1000, WorkReasons::RETRY.0), + (0x3000, WorkReasons::ZERO.0 | WorkReasons::RETRY.0), + ]); + let second = ledger.claim(8).unwrap(); + assert_eq!(second.pages.iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ + (0x4000, WorkReasons::ZERO.0 | WorkReasons::DIRTY.0), + (0x6000, WorkReasons::DIRTY.0), + ]); + + ledger.add_dirty_pages([0x1000]); + assert!(ledger.claim(1).is_none(), "new work escaped an older owner of the same page"); + assert_eq!(ledger.cancel(second.token), WorkClaimResolution::Restored); + let out_of_order = ledger.claim(1).unwrap(); + assert_eq!(out_of_order.pages[0].0, 0x4000); + assert_eq!(ledger.commit(first.token), WorkClaimResolution::Committed); + let later = ledger.claim(1).unwrap(); + assert_eq!(later.pages, [(0x1000, WorkReasons::DIRTY)]); + assert_eq!(ledger.commit(later.token), WorkClaimResolution::Committed); + assert_eq!(ledger.cancel(out_of_order.token), WorkClaimResolution::Restored); + let restored = ledger.claim(8).unwrap(); + assert_eq!(restored.pages.iter().map(|(page, _)| *page).collect::<Vec<_>>(), [0x4000, 0x6000]); + } + + #[test] + fn replaced_sparse_batch_handles_reject_stale_additions() { + let batches = SparseBatches::new(17); + let stale_clone = batches.clone(); + let current = batches.replace_generation(18).unwrap(); + assert!(!batches.add_dirty_pages([0xC000])); + assert!(!stale_clone.add_retry_pages([0xD000])); + assert!(matches!(batches.seal(1, 1), Err(SparseBatchError::StaleGeneration))); + assert!(matches!(stale_clone.replace_generation(19), Err(SparseBatchError::StaleGeneration))); + assert!(current.add_dirty_pages([0xB000])); + assert_eq!(current.seal(1, 1).unwrap().unwrap().pages()[0].0, 0xB000); + } + #[test] fn sparse_batch_takeover_revokes_without_restoring_or_duplicating_work() { let batches = SparseBatches::new(47); From c9a26c5e45468033111fa8e739be3fa623a1bd74 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:42:28 -0800 Subject: [PATCH 245/265] D3D12.X: retain exact foreground restoration attempts Keep one exact queue handle per restoration attempt so foreground demand can promote existing speculative work without compiling on the caller. Transfer an opaque recipe-bound published generation through the exact ticket, and report queue and build terminal states without substituting another attempt. The private coordinator remains default-off and unwired. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/build_queue.rs | 1 + crates/xcl/src/hle/d3d12x/pso_async.rs | 326 +++++++++++++++++++---- 2 files changed, 282 insertions(+), 45 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/build_queue.rs b/crates/xcl/src/hle/d3d12x/build_queue.rs index c445bb7817..eb83a51efb 100644 --- a/crates/xcl/src/hle/d3d12x/build_queue.rs +++ b/crates/xcl/src/hle/d3d12x/build_queue.rs @@ -107,6 +107,7 @@ impl Completion { } } +#[derive(Clone)] pub(super) struct JobHandle { id: JobId, queue: Weak<Inner>, diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 7458d5dc23..fc9fbbca58 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -14,7 +14,7 @@ use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock, Weak}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::ID3D12PipelineState; -use super::build_queue::{BuildQueue, JobHandle, Priority}; +use super::build_queue::{BuildQueue, JobHandle, JobStatus, Priority}; const QUEUE_IDLE: u8 = 0; const QUEUE_ACTIVE: u8 = 1; @@ -1332,8 +1332,9 @@ struct RehydrateAttemptToken { registry_instance: u64, slot: usize, slot_generat mod rehydrate_success { use super::*; + enum Authority { Current, Published } pub(super) struct Proof { attempt: RehydrateAttemptToken, build: Weak<Build>, recipe: Recipe, - replacement: NativeGeneration } + replacement: NativeGeneration, authority: Authority } impl Proof { pub(super) fn new(attempt: &RehydrateAttemptToken, build: &Arc<Build>, replacement: &NativeGeneration) -> Option<Self> { @@ -1341,17 +1342,31 @@ mod rehydrate_success { let recipe = build.recipe.as_ref()?; let (current, residency) = recipe.pin_with_residency(build.real.load(Ordering::Acquire)); (residency == Residency::Resident && current.as_ref().is_some_and(|current| current.same(replacement))).then(|| - Self { attempt: attempt.clone(), build: Arc::downgrade(build), recipe: recipe.clone(), replacement: replacement.clone() }) + Self { attempt: attempt.clone(), build: Arc::downgrade(build), recipe: recipe.clone(), + replacement: replacement.clone(), authority: Authority::Current }) } - pub(super) fn current(&self, attempt: &RehydrateAttemptToken) -> Option<Arc<Build>> { - if !self.attempt.exact(attempt) { return None } - let build = self.build.upgrade()?; - let recipe = build.recipe.as_ref()?; - (Arc::ptr_eq(&recipe.0, &self.recipe.0) && recipe.0.resident_generation.load(Ordering::Acquire) - == self.replacement.id()).then_some(build) + pub(super) fn published(attempt: &RehydrateAttemptToken, build: &Build, recipe: &Recipe, + replacement: &NativeGeneration) -> Option<Self> { + if attempt.evicted.build.as_ptr() != build as *const Build + || !Weak::ptr_eq(&replacement.recipe, &Arc::downgrade(&recipe.0)) + || build.recipe.as_ref().is_none_or(|owned| !Arc::ptr_eq(&owned.0, &recipe.0)) { return None } + let (current, residency) = recipe.pin_with_residency(replacement.raw()); + if residency != Residency::Resident || current.as_ref().is_none_or(|current| !current.same(replacement)) { return None } + Some(Self { attempt: attempt.clone(), build: attempt.evicted.build.clone(), recipe: recipe.clone(), + replacement: replacement.clone(), authority: Authority::Published }) + } + pub(super) fn valid_locked(&self, attempt: &RehydrateAttemptToken, build: &Arc<Build>) -> bool { + if !self.attempt.exact(attempt) { return false } + if !Weak::ptr_eq(&self.build, &Arc::downgrade(build)) { return false } + let Some(recipe) = build.recipe.as_ref() else { return false }; + Arc::ptr_eq(&recipe.0, &self.recipe.0) && match self.authority { + Authority::Current => recipe.0.resident_generation.load(Ordering::Acquire) == self.replacement.id(), + Authority::Published => Weak::ptr_eq(&self.replacement.recipe, &Arc::downgrade(&recipe.0)), + } } pub(super) fn replacement(&self) -> LedgerNativeGeneration { self.replacement.ledger_identity() } + pub(super) fn pin(&self) -> NativeGeneration { self.replacement.clone() } } } @@ -1444,7 +1459,7 @@ impl<const N: usize> RehydrateReceiptRegistry<N> { let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; if !entry.token.exact(token) { return false } let allowed = match state { - RehydrateCompletion::Refused => entry.state == RehydrateCompletion::Reserved, + RehydrateCompletion::Refused => matches!(entry.state, RehydrateCompletion::Reserved | RehydrateCompletion::Queued), RehydrateCompletion::Released => matches!(entry.state, RehydrateCompletion::Reserved | RehydrateCompletion::Queued), RehydrateCompletion::Cancelled | RehydrateCompletion::Panicked | RehydrateCompletion::BuildFailed => entry.state == RehydrateCompletion::Queued, @@ -1458,15 +1473,22 @@ impl<const N: usize> RehydrateReceiptRegistry<N> { } fn publish_success(&self, token: &RehydrateAttemptToken, proof: &rehydrate_success::Proof) -> bool { - let Some(_live_build) = token.evicted.build.upgrade() else { + let Some(build) = token.evicted.build.upgrade() else { return self.publish(token, RehydrateCompletion::Released); }; - let Some(_build) = proof.current(token) else { return false }; + let done = build.done.lock().unwrap(); + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + drop(done); + return self.publish(token, RehydrateCompletion::Released); + } + if !proof.valid_locked(token, &build) { + return false; + } let mut inner = self.inner.lock().unwrap(); let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; let replacement = proof.replacement(); if entry.state != RehydrateCompletion::Queued || !entry.token.exact(token) - || replacement == entry.token.evicted.native || proof.current(token).is_none() { return false } + || replacement == entry.token.evicted.native { return false } entry.state = RehydrateCompletion::Succeeded { replacement }; true } @@ -1532,6 +1554,12 @@ impl<'a, const N: usize> RehydrateReceiptReservation<'a, N> { registry: self.registry, token, completed: false, })) } + + fn accepted_token(mut self, priority: RehydratePriority) -> Option<RehydrateAttemptToken> { + if !self.registry.accept(&self.token, priority) { return None } + self.submitted = true; + Some(self.token.clone()) + } } impl<const N: usize> Drop for RehydrateReceiptReservation<'_, N> { @@ -1588,11 +1616,35 @@ impl<const N: usize> Drop for RehydrateQueuedReceipt<'_, N> { struct RestorationRetry { token: EvictedBuildToken } #[allow(dead_code)] -/// State composition only: it retains no JobHandle or post-success native pin and never starts, -/// runs, or promotes live queue work. Foreground here is admission metadata, not live readiness. +/// Private and unwired: composes exact eviction identity with one queue job and its strong result. struct RestorationCoordinator<const E: usize, const R: usize> { evicted: EvictedBuildLedger<E>, - receipts: RehydrateReceiptRegistry<R>, + receipts: Arc<RehydrateReceiptRegistry<R>>, + admission: Mutex<()>, + attempts: Mutex<Vec<Arc<RestorationAttempt>>>, + #[cfg(test)] + captured: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>, +} + +struct RestorationAttempt { + token: RehydrateAttemptToken, + job: Mutex<Option<JobHandle>>, + submitted: Condvar, + foreground: AtomicBool, + outcome: Mutex<Option<RestorationOutcome>>, +} + +#[allow(dead_code)] +enum RestorationOutcome { + Failed(RehydrateCompletion), + Succeeded(NativeGeneration), +} + +#[derive(Clone)] +#[allow(dead_code)] +struct RestorationTicket<const R: usize> { + receipts: Arc<RehydrateReceiptRegistry<R>>, + attempt: Arc<RestorationAttempt>, } #[allow(dead_code)] @@ -1611,7 +1663,14 @@ struct RestorationQueued<'a, const E: usize, const R: usize> { #[allow(dead_code)] impl<const E: usize, const R: usize> RestorationCoordinator<E, R> { fn new(generation: u64) -> Option<Self> { - Some(Self { evicted: EvictedBuildLedger::new(generation)?, receipts: RehydrateReceiptRegistry::new()? }) + Some(Self { + evicted: EvictedBuildLedger::new(generation)?, + receipts: Arc::new(RehydrateReceiptRegistry::new()?), + admission: Mutex::new(()), + attempts: Mutex::new(Vec::new()), + #[cfg(test)] + captured: Arc::new(Mutex::new(None)), + }) } fn reserve_eviction<'a>( @@ -1653,12 +1712,26 @@ impl<const E: usize, const R: usize> RestorationCoordinator<E, R> { /// Snapshot receipt state first, then mutate the exact eviction record, then retire the /// receipt. No two policy locks overlap, and a stale token can never touch a reused slot. fn reconcile(&self, limit: usize) -> usize { + let attempts = self.attempts.lock().unwrap().clone(); + for attempt in &attempts { + if attempt.outcome.lock().unwrap().is_some() { continue } + let status = attempt.job.lock().unwrap().as_ref().map(JobHandle::status); + let completion = match status { + Some(JobStatus::Cancelled) => Some(RehydrateCompletion::Cancelled), + Some(JobStatus::Panicked) => Some(RehydrateCompletion::Panicked), + _ => None, + }; + if let Some(completion) = completion { + let _ = self.receipts.publish(&attempt.token, completion); + } + } let records = self.receipts.records(limit); let mut reconciled = 0; for record in records.into_iter().filter(|record| record.state.terminal()) { let token = &record.token.evicted; let ok = match record.state { - RehydrateCompletion::Refused => self.evicted.state(token) == Some(EvictedBuildState::Evicted), + RehydrateCompletion::Refused => self.evicted.rehydrate_retry(token) + || self.evicted.state(token) == Some(EvictedBuildState::Evicted), RehydrateCompletion::Cancelled | RehydrateCompletion::Panicked | RehydrateCompletion::BuildFailed => { self.evicted.rehydrate_retry(token) || self.evicted.state(token) == Some(EvictedBuildState::Evicted) } @@ -1673,6 +1746,18 @@ impl<const E: usize, const R: usize> RestorationCoordinator<E, R> { } if self.receipts.retire(&record.token) { reconciled += 1 } } + let removed = { + let mut attempts = self.attempts.lock().unwrap(); + let (active, removed) = std::mem::take(&mut *attempts).into_iter().partition(|attempt| { + attempt.outcome.lock().unwrap().is_none() + && attempt.job.lock().unwrap().as_ref().is_none_or(|job| { + matches!(job.status(), JobStatus::Queued | JobStatus::Running) + }) + }); + *attempts = active; + removed + }; + drop(removed); // NativeGeneration/COM destruction can re-enter pipeline bookkeeping. reconciled } @@ -1681,6 +1766,141 @@ impl<const E: usize, const R: usize> RestorationCoordinator<E, R> { (record.state == EvictedBuildState::Evicted).then_some(RestorationRetry { token: record.token }) }).collect() } + + /// Private queue seam for a later bind integration. Submission never invokes the work inline; + /// foreground demand uses the normal worker band, while an exact queued background attempt is + /// promoted through its retained `JobHandle`. + fn request_exact_on( + &self, evicted: &EvictedBuildToken, priority: RehydratePriority, q: &BuildQueue, + ) -> Option<RestorationTicket<R>> { + let build = evicted.build.upgrade()?; + let admission = self.admission.lock().unwrap(); + if let Some(attempt) = self.attempts.lock().unwrap().iter() + .find(|attempt| attempt.token.evicted.exact(evicted)).cloned() { + drop(admission); + if priority == RehydratePriority::Foreground { + attempt.foreground.store(true, Ordering::Release); + if let Some(job) = attempt.job.lock().unwrap().as_ref() { + let _ = job.promote(Priority::Foreground); + } + let _ = self.receipts.promote(&attempt.token); + } + return Some(RestorationTicket { receipts: self.receipts.clone(), attempt }); + } + let receipt = match self.receipts.reserve_unique(evicted, true) { + Ok(Some(receipt)) => receipt, + Err(_) => return None, + Ok(None) => return None, + }; + let token = receipt.accepted_token(priority)?; + let attempt = Arc::new(RestorationAttempt { + token: token.clone(), job: Mutex::new(None), submitted: Condvar::new(), + foreground: AtomicBool::new(priority == RehydratePriority::Foreground), outcome: Mutex::new(None), + }); + self.attempts.lock().unwrap().push(attempt.clone()); + drop(admission); + if !self.evicted.rehydrate_queued(evicted) { + let _ = self.receipts.publish(&token, RehydrateCompletion::Cancelled); + *attempt.outcome.lock().unwrap() = Some(RestorationOutcome::Failed(RehydrateCompletion::Cancelled)); + attempt.submitted.notify_all(); + return Some(RestorationTicket { receipts: self.receipts.clone(), attempt }); + } + let reservation = match reserve_rehydrate_on(&build) { + Ok(reservation) => reservation, + Err(result) => { + let completion = if result == RehydrateRequest::Abandoned { + RehydrateCompletion::Released + } else { + RehydrateCompletion::Cancelled + }; + let _ = self.receipts.publish(&token, completion); + *attempt.outcome.lock().unwrap() = Some(RestorationOutcome::Failed(completion)); + attempt.submitted.notify_all(); + return Some(RestorationTicket { receipts: self.receipts.clone(), attempt }); + } + }; + let worker_attempt = attempt.clone(); + let receipts = self.receipts.clone(); + let queued_build = build.clone(); + #[cfg(test)] + let captured = self.captured.clone(); + let queue_priority = if attempt.foreground.load(Ordering::Acquire) { + Priority::Foreground + } else { + Priority::Speculative + }; + let job = q.submit(queue_priority, Box::new(move || { + let recipe = reservation.recipe.clone(); + let (result, proof) = rebuild_reserved_pinned(&queued_build, &recipe, Some(&token)); + drop(reservation); + #[cfg(test)] + if let Some(captured) = captured.lock().unwrap().take() { captured() } + let outcome = match (result, proof) { + (RebuildResult::Published { .. }, Some(proof)) => { + let pin = proof.pin(); + if receipts.publish_success(&token, &proof) { RestorationOutcome::Succeeded(pin) } + else { RestorationOutcome::Failed(RehydrateCompletion::Released) } + } + (RebuildResult::Published { .. }, None) => RestorationOutcome::Failed(RehydrateCompletion::BuildFailed), + (RebuildResult::Failed, _) => RestorationOutcome::Failed(RehydrateCompletion::BuildFailed), + (RebuildResult::Abandoned, _) => RestorationOutcome::Failed(RehydrateCompletion::Released), + (RebuildResult::NotReady, _) => RestorationOutcome::Failed(RehydrateCompletion::Cancelled), + }; + if let RestorationOutcome::Failed(completion) = &outcome { + let _ = receipts.publish(&token, *completion); + } + *worker_attempt.outcome.lock().unwrap() = Some(outcome); + })); + match job { + Some(job) => { + *attempt.job.lock().unwrap() = Some(job.clone()); + if attempt.foreground.load(Ordering::Acquire) { let _ = job.promote(Priority::Foreground); } + attempt.submitted.notify_all(); + } + None => { + let _ = self.receipts.publish(&attempt.token, RehydrateCompletion::Refused); + *attempt.outcome.lock().unwrap() = Some(RestorationOutcome::Failed(RehydrateCompletion::Refused)); + attempt.submitted.notify_all(); + } + } + Some(RestorationTicket { receipts: self.receipts.clone(), attempt }) + } + + fn request_foreground(&self, evicted: &EvictedBuildToken) -> Option<RestorationTicket<R>> { + if !start_normal_workers() { return None } + self.request_exact_on(evicted, RehydratePriority::Foreground, queue()) + } +} + +#[allow(dead_code)] +impl<const R: usize> RestorationTicket<R> { + fn token(&self) -> &RehydrateAttemptToken { &self.attempt.token } + + /// Waits only on this queue job, with no Build, recipe, ledger, list, or coordinator lock. + fn wait_and_take_pin(&self) -> Result<NativeGeneration, RehydrateCompletion> { + let mut job = self.attempt.job.lock().unwrap(); + while job.is_none() && self.attempt.outcome.lock().unwrap().is_none() { + job = self.attempt.submitted.wait(job).unwrap(); + } + let queued = job.clone(); + drop(job); + let status = queued.map(|job| job.wait()); + let outcome = self.attempt.outcome.lock().unwrap(); + match outcome.as_ref() { + Some(RestorationOutcome::Succeeded(pin)) => Ok(pin.clone()), + Some(RestorationOutcome::Failed(completion)) => Err(*completion), + None => { + let completion = match status { + Some(JobStatus::Panicked) => RehydrateCompletion::Panicked, + Some(JobStatus::Cancelled) => RehydrateCompletion::Cancelled, + _ => RehydrateCompletion::Cancelled, + }; + drop(outcome); + let _ = self.receipts.publish(&self.attempt.token, completion); + Err(completion) + } + } + } } #[allow(dead_code)] @@ -1839,6 +2059,14 @@ fn rebuild_once(build: &Build) -> Option<RebuildResult> { /// Run an attempt which already owns the recipe's rebuild turn. fn rebuild_reserved(build: &Build, recipe: &Recipe) -> RebuildResult { + rebuild_reserved_pinned(build, recipe, None).0 +} + +/// The exact published generation is retained before `Build.done` is released, so a later +/// eviction cannot invalidate a successful foreground restoration before its waiter pins it. +fn rebuild_reserved_pinned( + build: &Build, recipe: &Recipe, attempt: Option<&RehydrateAttemptToken>, +) -> (RebuildResult, Option<rehydrate_success::Proof>) { // A queued request can lose its last title-visible owner before a worker starts it. The queued // Arc keeps this state alive only so the attempt can retire; it must not revive the pipeline. { @@ -1846,7 +2074,7 @@ fn rebuild_reserved(build: &Build, recipe: &Recipe) -> RebuildResult { if !*done || build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { drop(done); recipe.finish_rebuild(RebuildResult::Abandoned); - return RebuildResult::Abandoned; + return (RebuildResult::Abandoned, None); } } @@ -1855,6 +2083,7 @@ fn rebuild_reserved(build: &Build, recipe: &Recipe) -> RebuildResult { let raw = run_job(recipe.initial_job()); let mut replaced_generation = None; let mut replaced_raw = 0; + let mut published = None; let result = if raw == 0 { RebuildResult::Failed } else { @@ -1863,6 +2092,7 @@ fn rebuild_reserved(build: &Build, recipe: &Recipe) -> RebuildResult { RebuildResult::Abandoned } else { let (generation, replaced) = recipe.publish(raw); + published = attempt.and_then(|attempt| rehydrate_success::Proof::published(attempt, build, recipe, &generation)); replaced_generation = replaced; replaced_raw = build.real.swap(raw, Ordering::AcqRel); build.completed_frame.store(super::present::presents(), Ordering::Relaxed); @@ -1879,7 +2109,7 @@ fn rebuild_reserved(build: &Build, recipe: &Recipe) -> RebuildResult { } else if raw != 0 { release(raw); } - result + (result, published) } static BUILT: AtomicUsize = AtomicUsize::new(0); static FAILED: AtomicUsize = AtomicUsize::new(0); @@ -2122,16 +2352,19 @@ enum RebuildTurn { /// One immutable native pipeline generation. Its strong owner keeps the exact object alive even /// after the title releases its stand-in or a later rebuild publishes the same raw address. #[derive(Clone)] -pub(super) struct NativeGeneration(Arc<Generation<ID3D12PipelineState>>); +pub(super) struct NativeGeneration { + generation: Arc<Generation<ID3D12PipelineState>>, + recipe: Weak<RecipeInner>, +} impl NativeGeneration { #[allow(dead_code)] // consumed by the later retirement diagnostics stage - pub(super) fn id(&self) -> u64 { self.0.id } + pub(super) fn id(&self) -> u64 { self.generation.id } #[allow(dead_code)] // exposed to focused generation-capture tests - pub(super) fn raw(&self) -> usize { self.0.raw } - pub(super) fn same(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } + pub(super) fn raw(&self) -> usize { self.generation.raw } + pub(super) fn same(&self, other: &Self) -> bool { Arc::ptr_eq(&self.generation, &other.generation) } // The owner allocation, rather than `raw`, distinguishes ABA reuse by a later generation. - fn identity(&self) -> usize { Arc::as_ptr(&self.0) as usize } + fn identity(&self) -> usize { Arc::as_ptr(&self.generation) as usize } #[allow(dead_code)] fn ledger_identity(&self) -> LedgerNativeGeneration { LedgerNativeGeneration { id: self.id(), identity: self.identity() } @@ -2256,12 +2489,15 @@ impl Recipe { let (generation, replaced) = slot.publish(raw, owner); self.0.resident_generation.store(generation.id, Ordering::Release); drop(slot); - (NativeGeneration(generation), replaced.map(NativeGeneration)) + let wrap = |generation| NativeGeneration { generation, recipe: Arc::downgrade(&self.0) }; + (wrap(generation), replaced.map(wrap)) } fn pin_with_residency(&self, raw: usize) -> (Option<NativeGeneration>, Residency) { let generation = self.0.generation.lock().unwrap(); - (generation.pin(raw).map(NativeGeneration), generation.residency) + (generation.pin(raw).map(|generation| NativeGeneration { + generation, recipe: Arc::downgrade(&self.0), + }), generation.residency) } fn mark_failed(&self) { @@ -2274,7 +2510,9 @@ impl Recipe { fn detach_current(&self, raw: usize) -> Option<NativeGeneration> { let mut slot = self.0.generation.lock().unwrap(); - let detached = slot.detach(raw).map(NativeGeneration); + let detached = slot.detach(raw).map(|generation| NativeGeneration { + generation, recipe: Arc::downgrade(&self.0), + }); if detached.is_some() { self.0.resident_generation.store(0, Ordering::Release) } drop(slot); detached @@ -2545,6 +2783,18 @@ fn run_reserved_rehydrate(build: Arc<Build>, reservation: RehydrateReservation) drop(reservation); } +fn reserve_rehydrate_on(build: &Arc<Build>) -> Result<RehydrateReservation, RehydrateRequest> { + let done = build.done.lock().unwrap(); + if !*done { return Err(RehydrateRequest::NotReady) } + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + return Err(RehydrateRequest::Abandoned); + } + if build.real.load(Ordering::Acquire) != 0 { return Err(RehydrateRequest::Resident) } + let Some(recipe) = build.recipe.clone() else { return Err(RehydrateRequest::Unavailable) }; + let turn = recipe.reserve_rehydrate()?; + Ok(RehydrateReservation { recipe, turn }) +} + fn request_rebuild_on(build: Arc<Build>, q: &BuildQueue) -> RebuildRequest { let recipe = { let done = build.done.lock().unwrap(); @@ -2569,23 +2819,9 @@ fn request_rebuild_on(build: Arc<Build>, q: &BuildQueue) -> RebuildRequest { } fn request_rehydrate_on(build: Arc<Build>, q: &BuildQueue) -> RehydrateRequest { - let reservation = { - let done = build.done.lock().unwrap(); - if !*done { - return RehydrateRequest::NotReady; - } - if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { - return RehydrateRequest::Abandoned; - } - if build.real.load(Ordering::Acquire) != 0 { - return RehydrateRequest::Resident; - } - let Some(recipe) = build.recipe.clone() else { return RehydrateRequest::Unavailable }; - let turn = match recipe.reserve_rehydrate() { - Ok(turn) => turn, - Err(result) => return result, - }; - RehydrateReservation { recipe, turn } + let reservation = match reserve_rehydrate_on(&build) { + Ok(reservation) => reservation, + Err(result) => return result, }; if q.submit(Priority::Speculative, Box::new(move || run_reserved_rehydrate(build, reservation))).is_none() { // The refused work is dropped by `submit`, restoring Evicted/Failed before it returns. From ff6be930f09d75cef85762e47ad6d3c6bd46b498 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:42:57 -0800 Subject: [PATCH 246/265] Tests: cover exact pipeline restoration attempts Exercise foreground promotion, coalescing, queue refusal and cancellation, build failure, worker panic, release, and exact attempt-token replacement. Deterministically evict after publication capture and verify the ticket keeps the recipe-bound generation, while final COM destruction occurs outside the coordinator lock. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 122 +++++++++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index fc9fbbca58..82934d9f54 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1624,6 +1624,8 @@ struct RestorationCoordinator<const E: usize, const R: usize> { attempts: Mutex<Vec<Arc<RestorationAttempt>>>, #[cfg(test)] captured: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>, + #[cfg(test)] + before_rebuild: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>, } struct RestorationAttempt { @@ -1670,6 +1672,8 @@ impl<const E: usize, const R: usize> RestorationCoordinator<E, R> { attempts: Mutex::new(Vec::new()), #[cfg(test)] captured: Arc::new(Mutex::new(None)), + #[cfg(test)] + before_rebuild: Arc::new(Mutex::new(None)), }) } @@ -1824,12 +1828,16 @@ impl<const E: usize, const R: usize> RestorationCoordinator<E, R> { let queued_build = build.clone(); #[cfg(test)] let captured = self.captured.clone(); + #[cfg(test)] + let before_rebuild = self.before_rebuild.clone(); let queue_priority = if attempt.foreground.load(Ordering::Acquire) { Priority::Foreground } else { Priority::Speculative }; let job = q.submit(queue_priority, Box::new(move || { + #[cfg(test)] + if let Some(before_rebuild) = before_rebuild.lock().unwrap().take() { before_rebuild() } let recipe = reservation.recipe.clone(); let (result, proof) = rebuild_reserved_pinned(&queued_build, &recipe, Some(&token)); drop(reservation); @@ -3226,6 +3234,19 @@ mod used_tests { (*(this as *mut RebuildFakePso)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 } + thread_local! { static RESTORE_REENTER_ATTEMPTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; } + + unsafe extern "system" fn rebuild_reenter_release(this: *mut std::ffi::c_void) -> u32 { + let remaining = rebuild_fake_release(this); + if remaining == 0 { + RESTORE_REENTER_ATTEMPTS.with(|address| if address.get() != 0 { assert!( + (&*(address.get() as *const Mutex<Vec<Arc<RestorationAttempt>>>)).try_lock().is_ok(), + "final native drop ran under the attempts lock", + ) }); + } + remaining + } + fn pressure_config() -> PressureAdmissionConfig { PressureAdmissionConfig { enabled: true, @@ -3565,11 +3586,20 @@ mod used_tests { assert!(success.replacement(&ledger_build(), &replacement).is_none(), "another build proved replacement"); assert!(!registry.publish(&success.token, RehydrateCompletion::Succeeded { replacement: ledger_native(99) }), "a forged native identity bypassed replacement proof"); + let mut foreign = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; let foreign_raw = &mut foreign as *mut RebuildFakePso as usize; + let foreign_recipe = Recipe::new(move || foreign_raw); + let foreign_build = Arc::new(Build::new_keyed(foreign_recipe.initial_job(), false, None, Some(foreign_recipe.clone()))); + let foreign_job = foreign_build.job.lock().unwrap().take().unwrap(); complete(&foreign_build, foreign_job()); + let foreign_pin = foreign_recipe.pin_with_residency(foreign_raw).0.unwrap(); + assert!(rehydrate_success::Proof::published(&success.token, &build, &recipe, &foreign_pin).is_none(), + "same-number generation from another recipe proved success"); let proof = success.replacement(&build, &replacement).unwrap(); let token = success.token.clone(); let mut newer_native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; let newer_raw = &mut newer_native as *mut RebuildFakePso as usize; let (newer, replaced) = recipe.publish(newer_raw); let old_raw = build.real.swap(newer_raw, Ordering::AcqRel); release(old_raw); drop(replaced); + assert!(rehydrate_success::Proof::published(&success.token, &build, &recipe, &replacement).is_none(), + "an older generation was relabeled as the published replacement"); assert!(!success.complete_success(proof), "generation A completed after B became current"); assert_eq!(registry.records(1)[0].state, RehydrateCompletion::Cancelled); assert!(registry.retire(&token)); let (_, success) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); @@ -3586,6 +3616,9 @@ mod used_tests { assert_eq!(registry.records(1)[0].state, RehydrateCompletion::Released); drop(replacement); drop(newer); drop(recipe); assert_eq!(native.refs.load(Ordering::Relaxed), 0); assert_eq!(newer_native.refs.load(Ordering::Relaxed), 0); + let foreign_owner = foreign_build.real.swap(0, Ordering::AcqRel); drop(foreign_pin); drop(foreign_build); + release(foreign_owner); drop(foreign_recipe); + assert_eq!(foreign.refs.load(Ordering::Relaxed), 0); } #[test] @@ -3801,6 +3834,95 @@ mod used_tests { assert_eq!(native.refs.load(Ordering::Relaxed), 0); } + #[test] + fn exact_restoration_promotes_without_inline_work_and_transfers_its_pin() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let replacement_vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_reenter_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: replacement_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); + let calls = Arc::new(AtomicUsize::new(0)); + let build_next = next.clone(); let build_calls = calls.clone(); + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + build_next.load(Ordering::Acquire) + }); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + let first_pin = recipe.pin_with_residency(first_raw).0.unwrap(); + let coordinator = RestorationCoordinator::<2, 2>::new(401).unwrap(); + let evicted = coordinator.reserve_eviction(&build, first_pin.ledger_identity()).unwrap().arm_detach().unwrap(); + drop(first_pin); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + next.store(replacement_raw, Ordering::Release); + let (captured_tx, captured_rx) = mpsc::channel(); + let (continue_tx, continue_rx) = mpsc::channel(); + *coordinator.captured.lock().unwrap() = Some(Box::new(move || { + captured_tx.send(()).unwrap(); continue_rx.recv().unwrap(); + })); + + let q = BuildQueue::new(); + let background = coordinator.request_exact_on(&evicted, RehydratePriority::Background, &q).unwrap(); + assert_eq!(calls.load(Ordering::Relaxed), 1, "request ran driver work inline"); + let foreground = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &q).unwrap(); + assert!(background.token().exact(foreground.token()), "foreground demand did not coalesce exactly"); + assert!(!q.try_run_one_between(Priority::Speculative, Priority::Preload)); + std::thread::scope(|scope| { + let worker = scope.spawn(|| q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + captured_rx.recv().unwrap(); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 2 }); + continue_tx.send(()).unwrap(); + assert!(worker.join().unwrap()); + }); + let pin = foreground.wait_and_take_pin().unwrap(); + assert_eq!((pin.raw(), pin.id(), calls.load(Ordering::Relaxed)), (replacement_raw, 2, 2)); + assert_eq!(pin.raw(), replacement_raw, "a second detach invalidated the handed-off generation"); + + drop(background); drop(foreground); drop(pin); + RESTORE_REENTER_ATTEMPTS.with(|address| address.set(&coordinator.attempts as *const _ as usize)); + assert_eq!(coordinator.reconcile(2), 1); + RESTORE_REENTER_ATTEMPTS.with(|address| address.set(0)); + drop(coordinator); drop(build); drop(recipe); + assert_eq!((first.refs.load(Ordering::Relaxed), replacement.refs.load(Ordering::Relaxed)), (0, 0)); + } + + #[test] + fn exact_restoration_tickets_report_every_terminal_and_do_not_reuse_attempts() { + let recipe = Recipe::new(|| 0); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + let coordinator = RestorationCoordinator::<1, 1>::new(402).unwrap(); + let evicted = coordinated_evicted(&coordinator, &build, 60); + + let refused = BuildQueue::new(); refused.shutdown(); + let refused = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &refused).unwrap(); + assert!(matches!(refused.wait_and_take_pin(), Err(RehydrateCompletion::Refused))); assert_eq!(coordinator.reconcile(1), 1); + let cancelled = BuildQueue::new(); + let first = coordinator.request_exact_on(&evicted, RehydratePriority::Background, &cancelled).unwrap(); + let first_token = first.token().clone(); cancelled.shutdown(); + assert!(matches!(first.wait_and_take_pin(), Err(RehydrateCompletion::Cancelled))); assert_eq!(coordinator.reconcile(1), 1); + let failed = BuildQueue::new(); + let second = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &failed).unwrap(); + assert!(!first_token.exact(second.token())); assert!(failed.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(matches!(second.wait_and_take_pin(), Err(RehydrateCompletion::BuildFailed))); assert_eq!(coordinator.reconcile(1), 1); + *coordinator.before_rebuild.lock().unwrap() = Some(Box::new(|| panic!("restoration panic"))); + let panicked = BuildQueue::new(); + let panic_ticket = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &panicked).unwrap(); + assert!(panicked.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(matches!(panic_ticket.wait_and_take_pin(), Err(RehydrateCompletion::Panicked))); assert_eq!(coordinator.reconcile(1), 1); + let retry_q = BuildQueue::new(); + let retry = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &retry_q).unwrap(); + assert!(retry_q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(matches!(retry.wait_and_take_pin(), Err(RehydrateCompletion::BuildFailed))); assert_eq!(coordinator.reconcile(1), 1); + let released_q = BuildQueue::new(); + let released = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &released_q).unwrap(); + build.owners.store(0, Ordering::Release); + assert!(released_q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(matches!(released.wait_and_take_pin(), Err(RehydrateCompletion::Released))); assert_eq!(coordinator.reconcile(1), 1); + } + #[test] fn pressure_observer_bounds_inspection_and_requeues_every_resident() { let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; From bf20fed1d5b7c2e5bbb363c08d9b4e8b04ea9ef1 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:47:58 -0800 Subject: [PATCH 247/265] D3D12.X: install exact eviction tokens before detach Publish an armed eviction token on its exact Build before a future policy may detach native owners. An uncommitted guard clears only its own token and poisons its ledger record, leaving resolver and policy wiring for a later stage. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 93 ++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 82934d9f54..4d8ea2c2a2 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -67,6 +67,9 @@ struct Build { /// This build already has one use record in the bounded eviction-candidate journal. /// Touched only while recipe retention is enabled. candidate_queued: AtomicBool, + /// Exact armed eviction visible before its native owners may be detached. Kept separate + /// from recipe state so coordinator locks never overlap the build/rebuild/generation chain. + eviction: Mutex<Option<EvictedBuildToken>>, done: Mutex<bool>, cv: Condvar, /// every stand-in interested in this build was released before it finished @@ -308,6 +311,7 @@ impl Build { last_use_frame: AtomicU64::new(super::present::presents()), completed_frame: AtomicU64::new(0), candidate_queued: AtomicBool::new(false), + eviction: Mutex::new(None), done: Mutex::new(false), cv: Condvar::new(), orphan: Default::default(), @@ -959,6 +963,38 @@ impl EvictedBuildToken { && Weak::ptr_eq(&self.build, &other.build) && self.native == other.native } + + fn belongs_to(&self, build: &Build) -> bool { + std::ptr::eq(self.build.as_ptr(), build) + } +} + +#[allow(dead_code)] +impl Build { + fn eviction_token(&self) -> Option<EvictedBuildToken> { + self.eviction.lock().unwrap().clone() + } + + fn install_eviction_token(&self, token: &EvictedBuildToken) -> bool { + if !token.belongs_to(self) { + return false; + } + let mut installed = self.eviction.lock().unwrap(); + if installed.is_some() { + return false; + } + *installed = Some(token.clone()); + true + } + + fn clear_eviction_token(&self, token: &EvictedBuildToken) -> bool { + let mut installed = self.eviction.lock().unwrap(); + if installed.as_ref().is_none_or(|current| !current.exact(token)) { + return false; + } + *installed = None; + true + } } struct EvictedBuildEntry { @@ -1628,6 +1664,41 @@ struct RestorationCoordinator<const E: usize, const R: usize> { before_rebuild: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>, } +/// An exact ledger record installed on its build before native detachment can begin. Dropping an +/// uncommitted preparation clears only that record and poisons its ledger slot; committing leaves +/// both visible for a later restoration request. +#[allow(dead_code)] +struct InstalledEviction<'a, const E: usize, const R: usize> { + coordinator: &'a RestorationCoordinator<E, R>, + build: Arc<Build>, + token: Option<EvictedBuildToken>, +} + +#[allow(dead_code)] +impl<const E: usize, const R: usize> InstalledEviction<'_, E, R> { + fn token(&self) -> &EvictedBuildToken { + self.token.as_ref().expect("committed eviction preparation") + } + + /// Consume only after exact generation revalidation and native detachment have succeeded. + fn commit(mut self) -> EvictedBuildToken { + self.token.take().expect("committed eviction preparation") + } + + fn cleanup(&mut self) { + let Some(token) = self.token.take() else { return }; + let _ = self.build.clear_eviction_token(&token); + let _ = self.coordinator.evicted.finish(&token, EvictedBuildState::Poisoned); + let _ = self.coordinator.evicted.retire(&token); + } +} + +impl<const E: usize, const R: usize> Drop for InstalledEviction<'_, E, R> { + fn drop(&mut self) { + self.cleanup(); + } +} + struct RestorationAttempt { token: RehydrateAttemptToken, job: Mutex<Option<JobHandle>>, @@ -1683,6 +1754,20 @@ impl<const E: usize, const R: usize> RestorationCoordinator<E, R> { self.evicted.reserve(build, native) } + /// Arm the exact ledger record, then publish it on the build. A future eviction path must + /// perform its state-chain revalidation and detach only while holding the returned guard. + fn install_eviction<'a>( + &'a self, build: &Arc<Build>, native: LedgerNativeGeneration, + ) -> Option<InstalledEviction<'a, E, R>> { + let token = self.reserve_eviction(build, native)?.arm_detach()?; + if !build.install_eviction_token(&token) { + let _ = self.evicted.finish(&token, EvictedBuildState::Poisoned); + let _ = self.evicted.retire(&token); + return None; + } + Some(InstalledEviction { coordinator: self, build: build.clone(), token: Some(token) }) + } + fn refuse_rehydrate(&self, evicted: &EvictedBuildToken) -> bool { match self.receipts.reserve_unique(evicted, true) { Ok(Some(reservation)) => reservation.refused().is_some(), @@ -1749,6 +1834,14 @@ impl<const E: usize, const R: usize> RestorationCoordinator<E, R> { let _ = self.evicted.finish(token, EvictedBuildState::Poisoned); } if self.receipts.retire(&record.token) { reconciled += 1 } + // Receipt, build, and ledger locks never overlap. Exact matching makes this safe + // after address or bounded-slot reuse, and retryable failures remain nonterminal. + if self.evicted.state(token).is_some_and(EvictedBuildState::terminal) { + if let Some(build) = token.build.upgrade() { + let _ = build.clear_eviction_token(token); + } + let _ = self.evicted.retire(token); + } } let removed = { let mut attempts = self.attempts.lock().unwrap(); From e2646dba9124bc0eef98aff2aee4eef234570049 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:48:56 -0800 Subject: [PATCH 248/265] Tests: cover exact eviction token installation Exercise pre-detach visibility, rollback after failed generation revalidation, and stale-token clearing after bounded ledger slot reuse. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 96 ++++++++++++++++++++++---- 1 file changed, 83 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 4d8ea2c2a2..7c5b9245bd 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -3754,6 +3754,54 @@ mod used_tests { assert!(coordinator.retries(1)[0].token.exact(&evicted)); } + #[test] + fn installed_eviction_is_visible_before_detach_commit() { + let coordinator = RestorationCoordinator::<1, 1>::new(308).unwrap(); + let build = ledger_build(); + let installed = coordinator.install_eviction(&build, ledger_native(50)).unwrap(); + let visible = build.eviction_token().expect("armed eviction was not installed"); + assert!(visible.exact(installed.token())); + assert_eq!(coordinator.evicted.state(&visible), Some(EvictedBuildState::Evicted)); + + let committed = installed.commit(); + assert!(build.eviction_token().is_some_and(|token| token.exact(&committed))); + assert!(build.clear_eviction_token(&committed)); + assert!(coordinator.evicted.finish(&committed, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&committed)); + } + + #[test] + fn failed_eviction_revalidation_clears_and_retires_installation() { + let coordinator = RestorationCoordinator::<1, 1>::new(309).unwrap(); + let build = ledger_build(); + { + let installed = coordinator.install_eviction(&build, ledger_native(51)).unwrap(); + assert!(build.eviction_token().is_some_and(|token| token.exact(installed.token()))); + // A future eviction path drops the guard when exact generation revalidation fails. + } + assert!(build.eviction_token().is_none()); + assert!(coordinator.evicted.records(1).is_empty()); + } + + #[test] + fn stale_eviction_token_cannot_clear_reused_installation() { + let coordinator = RestorationCoordinator::<1, 1>::new(310).unwrap(); + let build = ledger_build(); + let first = coordinator.install_eviction(&build, ledger_native(52)).unwrap().commit(); + assert!(build.clear_eviction_token(&first)); + assert!(coordinator.evicted.finish(&first, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&first)); + + let second = coordinator.install_eviction(&build, ledger_native(53)).unwrap().commit(); + assert_eq!(first.slot, second.slot); + assert_ne!(first.slot_generation, second.slot_generation); + assert!(!build.clear_eviction_token(&first)); + assert!(build.eviction_token().is_some_and(|token| token.exact(&second))); + assert!(build.clear_eviction_token(&second)); + assert!(coordinator.evicted.finish(&second, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&second)); + } + #[test] fn rehydrate_registry_atomically_returns_existing_before_readiness() { let build = ledger_build(); let evicted = receipt_evicted(&build, 49); @@ -3875,30 +3923,50 @@ mod used_tests { }; drop(build); drop(queued); assert_eq!(coordinator.reconcile(1), 1); - assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Released)); + assert_eq!(coordinator.evicted.state(&evicted), None); assert_eq!(coordinator.reconcile(1), 0); assert!(coordinator.retries(1).is_empty()); } #[test] - fn restoration_coordinator_poisons_mismatch_without_touching_reused_slot() { - let coordinator = RestorationCoordinator::<1, 1>::new(305).unwrap(); - let first_build = ledger_build(); - let first = coordinated_evicted(&coordinator, &first_build, 45); - assert!(coordinator.refuse_rehydrate(&first)); - assert!(coordinator.evicted.rehydrate_queued(&first)); + fn restoration_coordinator_release_clears_installation_and_reuses_capacity() { + let coordinator = RestorationCoordinator::<1, 1>::new(303).unwrap(); + let build = ledger_build(); + let evicted = coordinator.install_eviction(&build, ledger_native(43)).unwrap().commit(); + let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + assert!(queued.complete(RehydrateCompletion::Released)); assert_eq!(coordinator.reconcile(1), 1); - assert_eq!(coordinator.evicted.state(&first), Some(EvictedBuildState::Poisoned)); - assert!(coordinator.evicted.retire(&first)); + assert!(build.eviction_token().is_none()); + assert_eq!(coordinator.evicted.state(&evicted), None); + drop(coordinator.install_eviction(&build, ledger_native(44)).expect("terminal slot was not reusable")); + assert_eq!(coordinator.reconcile(1), 0); + assert!(coordinator.retries(1).is_empty()); + } - let second_build = ledger_build(); - let second = coordinated_evicted(&coordinator, &second_build, 46); + #[test] + fn restoration_coordinator_stale_terminal_cannot_clear_reused_installation() { + let coordinator = RestorationCoordinator::<1, 1>::new(305).unwrap(); + let build = ledger_build(); + let first = coordinator.install_eviction(&build, ledger_native(45)).unwrap().commit(); + let queued = match coordinator.queue_rehydrate(&first, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + assert!(queued.complete(RehydrateCompletion::Released)); + assert_eq!(coordinator.reconcile(1), 1); + let second = coordinator.install_eviction(&build, ledger_native(46)).unwrap().commit(); assert_eq!(first.slot, second.slot); assert_ne!(first.slot_generation, second.slot_generation); assert!(coordinator.receipts.reserve(&first).unwrap().refused().is_some()); assert_eq!(coordinator.reconcile(1), 1); assert_eq!(coordinator.evicted.state(&second), Some(EvictedBuildState::Evicted), "a stale receipt poisoned a reused eviction slot"); + assert!(build.eviction_token().is_some_and(|token| token.exact(&second)), + "a stale terminal receipt cleared the replacement installation"); + assert!(build.clear_eviction_token(&second)); + assert!(coordinator.evicted.finish(&second, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&second)); assert_eq!(coordinator.reconcile(1), 0); } @@ -3912,7 +3980,7 @@ mod used_tests { let job = build.job.lock().unwrap().take().unwrap(); complete(&build, job()); let replacement = recipe.pin_with_residency(raw).0.unwrap(); let coordinator = RestorationCoordinator::<1, 1>::new(304).unwrap(); - let evicted = coordinated_evicted(&coordinator, &build, 44); + let evicted = coordinator.install_eviction(&build, ledger_native(44)).unwrap().commit(); let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Foreground, false).unwrap() { RestorationQueue::Queued(queued) => queued, _ => unreachable!(), }; @@ -3920,7 +3988,9 @@ mod used_tests { assert!(queued.complete_success(proof)); assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::RehydrateQueued)); assert_eq!(coordinator.reconcile(1), 1); - assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Restored)); + assert!(build.eviction_token().is_none()); + assert_eq!(coordinator.evicted.state(&evicted), None); + drop(coordinator.install_eviction(&build, ledger_native(45)).expect("restored slot was not reusable")); assert_eq!(coordinator.reconcile(1), 0); let raw_owner = build.real.swap(0, Ordering::AcqRel); drop(build); release(raw_owner); drop(replacement); drop(recipe); From a8efddd97ddc0f7b99865074d5fc35f761981162 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:59:51 -0800 Subject: [PATCH 249/265] Scripts: compare native submission timing Enable the existing opt-in submission timer during reproducible perf runs and include its threshold in the recorded environment. Compare the raw submission count and slowest CPU-side ExecuteCommandLists duration/list count while preserving missing report data as an explicit state. Assisted-by: Codex (GPT-5.6-sol) --- scripts/perf-compare.ps1 | 50 ++++++++++++++++++++++++++++++++++ scripts/perf-compare.tests.ps1 | 22 +++++++++++++-- scripts/perf-run.ps1 | 7 +++-- scripts/perf-run.tests.ps1 | 24 ++++++++++++++-- 4 files changed, 96 insertions(+), 7 deletions(-) diff --git a/scripts/perf-compare.ps1 b/scripts/perf-compare.ps1 index 11e00ee2c6..ccfbc35555 100644 --- a/scripts/perf-compare.ps1 +++ b/scripts/perf-compare.ps1 @@ -100,6 +100,40 @@ function Read-Nonnegative-Integer($Object, [string]$Name, [string]$Context) { return $value } +function Read-Nonnegative-Number($Object, [string]$Name, [string]$Context) { + if (-not (Has-Property $Object $Name) -or $null -eq $Object.$Name -or + $Object.$Name -is [bool] -or $Object.$Name -is [string]) { + throw "malformed $Context value: $Name" + } + try { $value = [decimal]$Object.$Name } catch { throw "malformed $Context value: $Name" } + if ($value -lt 0) { throw "malformed $Context value: $Name" } + return $value +} + +function Read-SubmissionTiming([string]$Root, [int]$Order, [string]$Label) { + $mode = $Label.Substring(4) + $report = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'report.json')) + if (-not (Test-Path -LiteralPath $report -PathType Leaf)) { + return [ordered]@{ status = 'missing_report'; counters = $null } + } + $json = Read-Json $report + if (-not (Has-Property $json 'd3d12') -or $null -eq $json.d3d12) { + return [ordered]@{ status = 'missing_d3d12'; counters = $null } + } + $names = @('submissions', 'slowest_submission_ms', 'slowest_submission_lists') + $present = @($names | Where-Object { (Has-Property $json.d3d12 $_) -and $null -ne $json.d3d12.$_ }) + if ($present.Count -eq 0) { + return [ordered]@{ status = 'missing_metrics'; counters = $null } + } + if ($present.Count -ne $names.Count) { throw "incomplete submission timing in $report" } + $counters = [ordered]@{ + submissions = Read-Nonnegative-Integer $json.d3d12 'submissions' "submission timing in $report" + slowest_submission_ms = Read-Nonnegative-Number $json.d3d12 'slowest_submission_ms' "submission timing in $report" + slowest_submission_lists = Read-Nonnegative-Integer $json.d3d12 'slowest_submission_lists' "submission timing in $report" + } + return [ordered]@{ status = 'present'; counters = $counters } +} + function Read-Preparation([string]$Root, [int]$Order, [string]$Label) { $mode = $Label.Substring(4) $report = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'report.json')) @@ -303,6 +337,10 @@ for ($i = 0; $i -lt 2; $i++) { $sparseGateNames = @('submit_wait_ms', 'submit_hold_ms', 'readback_wait_ms', 'readback_hold_ms', 'readback_released_wait_reacquire_ms') $sparseUploadGate = Compare-Counters $beforeSparseGate.counters $afterSparseGate.counters $sparseGateNames + $beforeSubmissionTiming = Read-SubmissionTiming $baselineRoot ($i + 1) $beforeRun.cache_state + $afterSubmissionTiming = Read-SubmissionTiming $candidateRoot ($i + 1) $afterRun.cache_state + $submissionTimingNames = @('submissions', 'slowest_submission_ms', 'slowest_submission_lists') + $submissionTiming = Compare-Counters $beforeSubmissionTiming.counters $afterSubmissionTiming.counters $submissionTimingNames $comparison = [ordered]@{ label = $beforeRun.cache_state @@ -341,6 +379,11 @@ for ($i = 0; $i -lt 2; $i++) { candidate = $afterSparseGate.status } sparse_upload_gate = $sparseUploadGate + submission_timing_status = [ordered]@{ + baseline = $beforeSubmissionTiming.status + candidate = $afterSubmissionTiming.status + } + submission_timing = $submissionTiming } $comparisons += $comparison @@ -377,6 +420,13 @@ for ($i = 0; $i -lt 2; $i++) { Write-Host " $($name): $(Display-Value $sparseUploadGate.baseline.$name ' ms') -> $(Display-Value $sparseUploadGate.candidate.$name ' ms'); delta $(Display-Value $sparseUploadGate.delta.$name ' ms')" } } + Write-Host " submission timing: $($beforeSubmissionTiming.status) -> $($afterSubmissionTiming.status)" + if ($beforeSubmissionTiming.status -eq 'present' -or $afterSubmissionTiming.status -eq 'present') { + foreach ($name in $submissionTiming.delta.Keys) { + $suffix = if ($name -eq 'slowest_submission_ms') { ' ms' } else { '' } + Write-Host " $($name): $(Display-Value $submissionTiming.baseline.$name $suffix) -> $(Display-Value $submissionTiming.candidate.$name $suffix); delta $(Display-Value $submissionTiming.delta.$name $suffix)" + } + } } [ordered]@{ diff --git a/scripts/perf-compare.tests.ps1 b/scripts/perf-compare.tests.ps1 index 2b307e9087..7deba246a4 100644 --- a/scripts/perf-compare.tests.ps1 +++ b/scripts/perf-compare.tests.ps1 @@ -27,7 +27,7 @@ function Write-Fixture([string]$Root, [string]$Commit, [int]$ColdMs, $WarmMs) { function Write-Report([string]$Path, [int]$Count, [long]$Total, [long]$Maximum, $Preparation = $null, [int]$PreparationVersion = 1, $RankedPreloads = $null, - $AllocatorSubmits = $null, [switch]$ExtraKind) { + $AllocatorSubmits = $null, $SubmissionTiming = $null, [switch]$ExtraKind) { $aggregates = @( [ordered]@{ kind = 'dxc_compile'; count = $Count; total_ns = $Total; max_ns = $Maximum; histogram_log2_ns = @(0, $Count) } ) @@ -35,6 +35,7 @@ function Write-Report([string]$Path, [int]$Count, [long]$Total, [long]$Maximum, $aggregates += [ordered]@{ kind = 'gpu_wait'; count = 1; total_ns = 9; max_ns = 9; histogram_log2_ns = @(0, 0, 0, 1) } } $report = [ordered]@{ stalls = [ordered]@{ version = 1; aggregates = $aggregates; slow_events = @() } } + if ($null -ne $SubmissionTiming) { $report['d3d12'] = $SubmissionTiming } if ($null -ne $Preparation) { $report['preparation'] = [ordered]@{ version = $PreparationVersion @@ -60,8 +61,10 @@ try { $afterRanked = [ordered]@{ submissions = 24; started = 20; promoted = 2 } $beforeAllocator = [ordered]@{ outer_execute_calls = 10; chunks = 13; multi_chunk_calls = 2; forced_wait_boundaries = 3; lists_marked = 40; backing_mark_writes = 20; signal_attempts = 13; signal_failures = 1; state_lock_wait_ns = 100; state_lock_hold_ns = 500 } $afterAllocator = [ordered]@{ outer_execute_calls = 12; chunks = 14; multi_chunk_calls = 1; forced_wait_boundaries = 2; lists_marked = 44; backing_mark_writes = 22; signal_attempts = 14; signal_failures = 0; state_lock_wait_ns = 80; state_lock_hold_ns = 450 } - Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation 3 $beforeRanked $beforeAllocator - Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator -ExtraKind + $beforeSubmissionTiming = [ordered]@{ submissions = 20; slowest_submission_ms = 3.5; slowest_submission_lists = 4 } + $afterSubmissionTiming = [ordered]@{ submissions = 24; slowest_submission_ms = 2.25; slowest_submission_lists = 3 } + Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation 3 $beforeRanked $beforeAllocator $beforeSubmissionTiming + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator $afterSubmissionTiming -ExtraKind [ordered]@{ d3d12 = [ordered]@{} } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $baseline 'runs\02-warm\report.json') -Encoding utf8 @( '[00:00:02] upload gate submit wait/hold 1/2 ms, readback wait/hold/released wait+reacquire 3/4/5 ms; other active work 6 ms' @@ -136,6 +139,19 @@ try { $null -ne $json.runs[1].sparse_upload_gate.delta.submit_wait_ms) { throw 'missing sparse upload-gate metrics were treated as zero' } + $timing = $json.runs[0].submission_timing + if ($json.runs[0].submission_timing_status.baseline -ne 'present' -or + $json.runs[0].submission_timing_status.candidate -ne 'present' -or + $timing.baseline.submissions -ne 20 -or $timing.candidate.submissions -ne 24 -or + $timing.delta.submissions -ne 4 -or $timing.delta.slowest_submission_ms -ne -1.25 -or + $timing.delta.slowest_submission_lists -ne -1) { + throw 'submission timing counters, status, or deltas are wrong' + } + if ($json.runs[1].submission_timing_status.baseline -ne 'missing_metrics' -or + $json.runs[1].submission_timing_status.candidate -ne 'missing_report' -or + $null -ne $json.runs[1].submission_timing.delta.submissions) { + throw 'missing submission timing was treated as zero' + } $badGateLog = Join-Path $candidate 'runs\02-warm\xcl.log' 'upload gate submit wait/hold malformed' | Set-Content -LiteralPath $badGateLog -Encoding utf8 $refused = $false diff --git a/scripts/perf-run.ps1 b/scripts/perf-run.ps1 index 326d31aa15..14f73995fa 100644 --- a/scripts/perf-run.ps1 +++ b/scripts/perf-run.ps1 @@ -107,10 +107,11 @@ $null = New-Item -ItemType Directory -Path $dxilCache $environmentNames = @( 'XCL_ACTIVITY', 'XCL_ADAPTER', 'XCL_DEVICE_TYPE', 'XCL_DIRECT_DXIL', 'XCL_DXC_THREADS', 'XCL_FRAME_INTERVAL_US', 'XCL_HEAP_WINDOWS', - 'XCL_LAZY_PSO', 'XCL_NETWORK', 'XCL_PRESS_AT', 'XCL_PSO_PRELOAD', + 'XCL_GPU_TIMING', 'XCL_GPU_TIMING_MS', 'XCL_LAZY_PSO', 'XCL_NETWORK', 'XCL_PRESS_AT', 'XCL_PSO_PRELOAD', 'XCL_REQUIRE_GPU', 'XCL_RUN_SECONDS', 'XCL_STALL_TRACE' ) -$changedNames = @('XCL_ACTIVITY', 'XCL_DATA_ROOT', 'XCL_DXIL_CACHE', 'XCL_NETWORK', 'XCL_RUN_SECONDS', 'XCL_STALL_TRACE') +$changedNames = @('XCL_ACTIVITY', 'XCL_DATA_ROOT', 'XCL_DXIL_CACHE', 'XCL_GPU_TIMING', 'XCL_GPU_TIMING_MS', + 'XCL_NETWORK', 'XCL_RUN_SECONDS', 'XCL_STALL_TRACE') $savedEnvironment = @{} foreach ($name in $changedNames) { $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') @@ -199,6 +200,8 @@ try { $env:XCL_NETWORK = '0' $env:XCL_RUN_SECONDS = "$Seconds" $env:XCL_ACTIVITY = '1' + $env:XCL_GPU_TIMING = '1' + $env:XCL_GPU_TIMING_MS = '50' $env:XCL_STALL_TRACE = '1' $recordedEnvironment = [ordered]@{} diff --git a/scripts/perf-run.tests.ps1 b/scripts/perf-run.tests.ps1 index 38fb8ce464..b94e4df905 100644 --- a/scripts/perf-run.tests.ps1 +++ b/scripts/perf-run.tests.ps1 @@ -20,6 +20,8 @@ $oldTestXcl = $env:XCL_PERF_RUN_TEST_XCL $oldData = $env:XCL_DATA_ROOT $oldDxil = $env:XCL_DXIL_CACHE $oldPress = $env:XCL_PRESS_AT +$oldGpuTiming = $env:XCL_GPU_TIMING +$oldGpuTimingMs = $env:XCL_GPU_TIMING_MS try { $null = New-Item -ItemType Directory -Path $scripts, $game, $bin, $userData, $userDxil @@ -49,7 +51,8 @@ echo seen>"%XCL_DXIL_CACHE%\seen" :marker_done if not exist "%XCL_DATA_ROOT%\MockTitle\logs" mkdir "%XCL_DATA_ROOT%\MockTitle\logs" echo cache=%STATE%>"%XCL_DATA_ROOT%\MockTitle\logs\xcl.log" -echo {"d3d12":{"adapter":"Mock GPU"}}>"%XCL_DATA_ROOT%\MockTitle\logs\report.json" +echo gpu_timing=%XCL_GPU_TIMING% threshold=%XCL_GPU_TIMING_MS%>>"%XCL_DATA_ROOT%\MockTitle\logs\xcl.log" +echo {"d3d12":{"adapter":"Mock GPU","submissions":2,"slowest_submission_ms":1.5,"slowest_submission_lists":3}}>"%XCL_DATA_ROOT%\MockTitle\logs\report.json" echo Log: %XCL_DATA_ROOT%\MockTitle\logs\xcl.log exit /b 0 '@ | Set-Content -LiteralPath $mockXcl -Encoding Ascii @@ -66,6 +69,8 @@ exit /b 0 $env:XCL_DATA_ROOT = $userData $env:XCL_DXIL_CACHE = $userDxil $env:XCL_PRESS_AT = '20:A,24:A' + $env:XCL_GPU_TIMING = 'caller-value' + $env:XCL_GPU_TIMING_MS = '999' & (Join-Path $scripts 'perf-run.ps1') -Game $game -OutDir $out -Seconds 2 if ($LASTEXITCODE -ne 0) { throw "perf-run.ps1 exited with $LASTEXITCODE" } @@ -77,6 +82,9 @@ exit /b 0 if (($manifest.run_order -join ',') -ne 'xcl-cold,xcl-warm') { throw 'run order was not cold then warm' } if ($manifest.cache.driver -ne 'uncontrolled') { throw 'driver cache was not labelled uncontrolled' } if ($manifest.environment.XCL_PRESS_AT -ne '20:A,24:A') { throw 'input schedule was not recorded' } + if ($manifest.environment.XCL_GPU_TIMING -ne '1' -or $manifest.environment.XCL_GPU_TIMING_MS -ne '50') { + throw 'submission timing settings were not forced and recorded' + } if ($manifest.workload_id_algorithm -ne 'sha256-relative-path-length-mtime-utc-ticks' -or $manifest.workload_id_version -ne 1) { throw 'workload identity algorithm/version was not recorded' } if ($manifest.workload_id -notmatch '^[0-9a-f]{64}$') { throw 'workload identity is not a full SHA-256 value' } @@ -86,11 +94,21 @@ exit /b 0 if ($manifest.runs.Count -ne 2 -or $manifest.runs[0].cache_state -ne 'xcl-cold' -or $manifest.runs[1].cache_state -ne 'xcl-warm') { throw 'run records are incomplete' } if ((Get-Content -LiteralPath (Join-Path $out 'runs\01-cold\xcl.log') -Raw) -notmatch 'cache=cold') { throw 'cold run did not start with a fresh DXIL cache' } if ((Get-Content -LiteralPath (Join-Path $out 'runs\02-warm\xcl.log') -Raw) -notmatch 'cache=warm') { throw 'warm run did not reuse the cold cache' } + if ((Get-Content -LiteralPath (Join-Path $out 'runs\01-cold\xcl.log') -Raw) -notmatch 'gpu_timing=1 threshold=50') { + throw 'submission timing settings were not passed to XCL' + } if (-not (Test-Path -LiteralPath (Join-Path $out 'runs\01-cold\report.json')) -or -not (Test-Path -LiteralPath (Join-Path $out 'runs\02-warm\report.json'))) { throw 'reports were not preserved' } + $timing = (Get-Content -LiteralPath (Join-Path $out 'runs\01-cold\report.json') -Raw -Encoding utf8 | ConvertFrom-Json).d3d12 + if ($timing.submissions -ne 2 -or $timing.slowest_submission_ms -ne 1.5 -or $timing.slowest_submission_lists -ne 3) { + throw 'submission timing fields were not preserved' + } $artifactFiles = @(Get-ChildItem -LiteralPath $out -Recurse -File) $unexpectedArtifacts = @($artifactFiles | Where-Object { $_.Name -notin @('manifest.json', 'xcl.log', 'report.json') }) if ($artifactFiles.Count -ne 5 -or $unexpectedArtifacts.Count -ne 0) { throw 'the artifact folder contains something other than logs, reports, and the manifest' } - if ($env:XCL_DATA_ROOT -ne $userData -or $env:XCL_DXIL_CACHE -ne $userDxil) { throw 'the caller environment was not restored' } + if ($env:XCL_DATA_ROOT -ne $userData -or $env:XCL_DXIL_CACHE -ne $userDxil -or + $env:XCL_GPU_TIMING -ne 'caller-value' -or $env:XCL_GPU_TIMING_MS -ne '999') { + throw 'the caller environment was not restored' + } if (-not (Test-Path -LiteralPath (Join-Path $userData 'sentinel.txt')) -or -not (Test-Path -LiteralPath (Join-Path $userDxil 'sentinel.txt'))) { throw 'a user cache was touched' } if (Test-Path -LiteralPath (Join-Path ([IO.Path]::GetTempPath()) ("xcl-perf-$($manifest.cache.identity)"))) { throw 'the ephemeral cache was not removed' } if ((Get-Content -LiteralPath $cargoMarker -Raw) -notmatch 'build --locked --release -p xcl') { throw 'release build command was not run' } @@ -121,6 +139,8 @@ exit /b 0 $env:XCL_DATA_ROOT = $oldData $env:XCL_DXIL_CACHE = $oldDxil $env:XCL_PRESS_AT = $oldPress + $env:XCL_GPU_TIMING = $oldGpuTiming + $env:XCL_GPU_TIMING_MS = $oldGpuTimingMs Remove-Item Env:MOCK_CARGO_MARKER -ErrorAction SilentlyContinue if (Test-Path -LiteralPath $fixture) { Remove-Item -LiteralPath $fixture -Recurse -Force } } From 2579f3ac5ccd2e2b7c0f1a3c9ca71e5b12f9b400 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:59:34 -0800 Subject: [PATCH 250/265] D3D12.X: classify exact pipeline restoration without waiting Retain a structured resolver decision over the original Pending, distinguish cold builds from exact eviction attempts, and carry the exact restoration ticket or native generation without starting workers or changing live bind behavior. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 182 +++++++++++++++++++++++++ 1 file changed, 182 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 7c5b9245bd..27daf5c1c5 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1662,6 +1662,8 @@ struct RestorationCoordinator<const E: usize, const R: usize> { captured: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>, #[cfg(test)] before_rebuild: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>, + #[cfg(test)] + before_classified_request: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>, } /// An exact ledger record installed on its build before native detachment can begin. Dropping an @@ -1745,6 +1747,8 @@ impl<const E: usize, const R: usize> RestorationCoordinator<E, R> { captured: Arc::new(Mutex::new(None)), #[cfg(test)] before_rebuild: Arc::new(Mutex::new(None)), + #[cfg(test)] + before_classified_request: Arc::new(Mutex::new(None)), }) } @@ -6557,6 +6561,184 @@ pub(super) fn resolve_and_pin_for_bind(pso: usize) -> (usize, Option<NativeGener #[derive(Clone, Copy)] enum ResolveMode { Lazy, Wait, ForBind } +/// One retained resolver decision. This is private and unwired: a later list integration can +/// classify without waiting, retain the original `Pending` across title-address reuse, and wait +/// only when correctness-critical emission consumes an exact restoration ticket. +#[allow(dead_code)] +#[derive(Clone)] +enum StructuredResolve<const R: usize> { + Ready { + original: usize, + raw: usize, + pin: Option<NativeGeneration>, + }, + Initial { + original: usize, + pending: Arc<Pending>, + fallback: usize, + bound_unbuilt: bool, + }, + Restoring { + original: usize, + pending: Arc<Pending>, + fallback: usize, + ticket: RestorationTicket<R>, + }, + Terminal { + original: usize, + pending: Arc<Pending>, + fallback: usize, + failure: StructuredResolveFailure, + }, +} + +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum StructuredResolveFailure { + MissingEvictionRecord, + RestorationUnavailable, + Refused, + Cancelled, + Panicked, + BuildFailed, + Released, +} + +#[allow(dead_code)] +struct StructuredResolvedPipeline { + raw: usize, + pin: Option<NativeGeneration>, + bound_unbuilt: bool, +} + +#[allow(dead_code)] +impl<const R: usize> StructuredResolve<R> { + /// Never waits. An initial build or restoration returns only the retained Pending's fallback. + fn nonblocking(&self) -> StructuredResolvedPipeline { + match self { + Self::Ready { raw, pin, .. } => StructuredResolvedPipeline { + raw: *raw, pin: pin.clone(), bound_unbuilt: false, + }, + Self::Initial { fallback, bound_unbuilt, .. } => StructuredResolvedPipeline { + raw: *fallback, pin: None, bound_unbuilt: *bound_unbuilt, + }, + Self::Restoring { fallback, .. } | Self::Terminal { fallback, .. } => { + StructuredResolvedPipeline { raw: *fallback, pin: None, bound_unbuilt: true } + } + } + } + + /// Wait only for an already-classified exact restoration. Initial cold-build policy remains + /// with the existing resolver until the later call-site integration stage. + fn wait_exact(&self) -> Result<Option<StructuredResolvedPipeline>, StructuredResolveFailure> { + match self { + Self::Ready { raw, pin, .. } => Ok(Some(StructuredResolvedPipeline { + raw: *raw, pin: pin.clone(), bound_unbuilt: false, + })), + Self::Initial { .. } => Ok(None), + Self::Restoring { ticket, .. } => ticket.wait_and_take_pin() + .map(|pin| Some(StructuredResolvedPipeline { raw: pin.raw(), pin: Some(pin), bound_unbuilt: false })) + .map_err(StructuredResolveFailure::from), + Self::Terminal { failure, .. } => Err(*failure), + } + } +} + +impl From<RehydrateCompletion> for StructuredResolveFailure { + fn from(completion: RehydrateCompletion) -> Self { + match completion { + RehydrateCompletion::Refused => Self::Refused, + RehydrateCompletion::Cancelled => Self::Cancelled, + RehydrateCompletion::Panicked => Self::Panicked, + RehydrateCompletion::BuildFailed => Self::BuildFailed, + RehydrateCompletion::Released => Self::Released, + RehydrateCompletion::Reserved | RehydrateCompletion::Queued + | RehydrateCompletion::Succeeded { .. } => Self::RestorationUnavailable, + } + } +} + +/// Classify one retained Pending without running driver work or waiting. The caller supplies the +/// private coordinator and queue so this foundation neither creates a live policy singleton nor +/// starts workers. No Build, recipe, registry, coordinator, or queue lock overlaps submission. +#[allow(dead_code)] +fn classify_structured_on<const E: usize, const R: usize>( + original: usize, + pending: &Arc<Pending>, + coordinator: &RestorationCoordinator<E, R>, + q: &BuildQueue, +) -> StructuredResolve<R> { + enum Snapshot { + Ready(usize, Option<NativeGeneration>), + Initial(usize, bool), + Restore(usize), + } + let snapshot = || { + let done = pending.build.done.lock().unwrap(); + let raw = pending.build.real.load(Ordering::Acquire); + let fallback = pending.stand(original); + if !*done { + return Snapshot::Initial(fallback, true); + } + let Some(recipe) = pending.build.recipe.as_ref() else { + // A one-shot Build has no independent native pin. Leave its current resolution to + // the existing resolver instead of carrying an ownerless raw pointer across release. + return Snapshot::Initial(fallback, false); + }; + let (pin, residency) = recipe.pin_with_residency(raw); + match (pin, residency) { + // A speculative replacement may mark the recipe Rebuilding while the old exact + // resident generation remains published and fully usable. + (Some(pin), Residency::Resident | Residency::Rebuilding) => Snapshot::Ready(raw, Some(pin)), + (None, Residency::Evicted | Residency::Rebuilding) => Snapshot::Restore(fallback), + (None, Residency::Failed) => Snapshot::Initial(fallback, false), + _ => Snapshot::Restore(fallback), + } + }; + let fallback = match snapshot() { + Snapshot::Ready(raw, pin) => return StructuredResolve::Ready { original, raw, pin }, + Snapshot::Initial(fallback, bound_unbuilt) => return StructuredResolve::Initial { + original, pending: pending.clone(), fallback, bound_unbuilt, + }, + Snapshot::Restore(fallback) => fallback, + }; + let Some(evicted) = pending.build.eviction_token() else { + // Terminal reconciliation clears the token after publication. Reclassify once so that + // race returns the new exact resident pin instead of a false missing-record failure. + return match snapshot() { + Snapshot::Ready(raw, pin) => StructuredResolve::Ready { original, raw, pin }, + Snapshot::Initial(fallback, bound_unbuilt) => StructuredResolve::Initial { + original, pending: pending.clone(), fallback, bound_unbuilt, + }, + Snapshot::Restore(fallback) => StructuredResolve::Terminal { + original, pending: pending.clone(), fallback, + failure: StructuredResolveFailure::MissingEvictionRecord, + }, + }; + }; + #[cfg(test)] + let before_request = coordinator.before_classified_request.lock().unwrap().take(); + #[cfg(test)] + if let Some(before_request) = before_request { + before_request(); + } + let requested = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, q); + // Success may publish and reconcile after the token snapshot but before this request. Its + // exact current pin wins over the stale request's Cancelled terminal state. + if let Snapshot::Ready(raw, pin) = snapshot() { + return StructuredResolve::Ready { original, raw, pin }; + } + match requested { + Some(ticket) => StructuredResolve::Restoring { + original, pending: pending.clone(), fallback, ticket, + }, + None => StructuredResolve::Terminal { + original, pending: pending.clone(), fallback, + failure: StructuredResolveFailure::RestorationUnavailable, + }, + } +} + fn resolve_and_pin_mode(pso: usize, mode: ResolveMode) -> (usize, Option<NativeGeneration>) { let Some(p) = entry(pso) else { return (pso, None) }; resolve_and_pin_pending(pso, &p, mode) From 67a59b068b4790bf476bd00a781b9d2725d4cb3d Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 05:59:38 -0800 Subject: [PATCH 251/265] Tests: cover structured pipeline restoration classification Exercise retained Pending identity across title-address reuse, fail-closed missing eviction records, usable pins during speculative rebuilds, exact background promotion, and the publish-before-request race without inline driver work. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 157 +++++++++++++++++++++++++ 1 file changed, 157 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 27daf5c1c5..6e47420db8 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -4090,6 +4090,163 @@ mod used_tests { assert!(matches!(released.wait_and_take_pin(), Err(RehydrateCompletion::Released))); assert_eq!(coordinator.reconcile(1), 1); } + fn structured_pending(build: Arc<Build>, compute: bool) -> Arc<Pending> { + Arc::new(Pending { + build, + driver: AtomicUsize::new(0), + compute, + key: 0, + used: AtomicBool::new(false), + late: AtomicBool::new(false), + spared: AtomicBool::new(false), + }) + } + + #[test] + fn structured_resolve_retains_pending_across_title_address_reuse() { + let original = 0x7E57_D001usize; + let old = structured_pending(Arc::new(Build::new(Box::new(|| 0), false)), false); + let coordinator = RestorationCoordinator::<1, 1>::new(501).unwrap(); + let q = BuildQueue::new(); + let outcome = classify_structured_on(original, &old, &coordinator, &q); + let replacement = structured_pending(Arc::new(Build::new(Box::new(|| 0), false)), true); + PENDING.insert(original, replacement.clone()); + + match outcome { + StructuredResolve::Initial { original: retained_original, pending, fallback, bound_unbuilt } => { + assert_eq!((retained_original, fallback, bound_unbuilt), (original, original, true)); + assert!(Arc::ptr_eq(&pending, &old), "address reuse redirected a retained decision"); + assert!(!Arc::ptr_eq(&pending, &replacement)); + } + _ => panic!("unfinished build was not classified as initial"), + } + assert!(Arc::ptr_eq(&PENDING.remove(original).unwrap(), &replacement)); + } + + #[test] + fn structured_resolve_fails_closed_without_exact_eviction_record() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + let pending = structured_pending(build.clone(), false); + let coordinator = RestorationCoordinator::<1, 1>::new(502).unwrap(); + let outcome = classify_structured_on(0x7E57_D002, &pending, &coordinator, &BuildQueue::new()); + assert!(matches!(outcome, StructuredResolve::Terminal { + failure: StructuredResolveFailure::MissingEvictionRecord, .. + })); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + drop(pending); drop(build); drop(recipe); + } + + #[test] + fn structured_resolve_keeps_exact_pin_during_speculative_rebuild() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + assert!(matches!(recipe.begin_rebuild(), RebuildTurn::Leader)); + let pending = structured_pending(build.clone(), false); + let coordinator = RestorationCoordinator::<1, 1>::new(504).unwrap(); + let outcome = classify_structured_on(0x7E57_D004, &pending, &coordinator, &BuildQueue::new()); + let StructuredResolve::Ready { raw: chosen, pin: Some(pin), .. } = outcome else { + panic!("a rebuilding replacement hid the current exact generation") + }; + assert_eq!((chosen, pin.raw()), (raw, raw)); + recipe.finish_rebuild(RebuildResult::Failed); + let raw_owner = build.real.swap(0, Ordering::AcqRel); + drop(pin); drop(pending); drop(build); drop(recipe); release(raw_owner); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn structured_resolve_promotes_exact_background_without_inline_driver_work() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); + let calls = Arc::new(AtomicUsize::new(0)); + let build_next = next.clone(); let build_calls = calls.clone(); + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + build_next.load(Ordering::Acquire) + }); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + let pin = recipe.pin_with_residency(first_raw).0.unwrap(); + let coordinator = RestorationCoordinator::<1, 1>::new(503).unwrap(); + let evicted = coordinator.install_eviction(&build, pin.ledger_identity()).unwrap().commit(); + drop(pin); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + next.store(replacement_raw, Ordering::Release); + let pending = structured_pending(build.clone(), false); + let q = BuildQueue::new(); + let background = coordinator.request_exact_on(&evicted, RehydratePriority::Background, &q).unwrap(); + let outcome = classify_structured_on(0x7E57_D003, &pending, &coordinator, &q); + let StructuredResolve::Restoring { ticket, .. } = &outcome else { panic!("eviction did not classify as restoring") }; + assert!(background.token().exact(ticket.token()), "foreground classification did not coalesce exactly"); + assert_eq!(calls.load(Ordering::Relaxed), 1, "classification ran driver work inline"); + assert!(!q.try_run_one_between(Priority::Speculative, Priority::Preload), "attempt was not promoted"); + assert!(q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + let resolved = outcome.wait_exact().unwrap().unwrap(); + assert_eq!((resolved.raw, resolved.bound_unbuilt, calls.load(Ordering::Relaxed)), + (replacement_raw, false, 2)); + assert!(resolved.pin.is_some()); + + drop(resolved); drop(outcome); drop(background); + assert_eq!(coordinator.reconcile(1), 1); + let raw_owner = build.real.swap(0, Ordering::AcqRel); + drop(pending); drop(build); drop(recipe); release(raw_owner); + assert_eq!((first.refs.load(Ordering::Relaxed), replacement.refs.load(Ordering::Relaxed)), (0, 0)); + } + + #[test] + fn structured_resolve_prefers_publication_over_stale_cancelled_request() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); let build_next = next.clone(); + let recipe = Recipe::new(move || build_next.load(Ordering::Acquire)); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + let pin = recipe.pin_with_residency(first_raw).0.unwrap(); + let coordinator = RestorationCoordinator::<1, 2>::new(505).unwrap(); + let evicted = coordinator.install_eviction(&build, pin.ledger_identity()).unwrap().commit(); + drop(pin); assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + next.store(replacement_raw, Ordering::Release); + let pending = structured_pending(build.clone(), false); let q = BuildQueue::new(); + let background = coordinator.request_exact_on(&evicted, RehydratePriority::Background, &q).unwrap(); + let (seen_tx, seen_rx) = mpsc::channel(); let (continue_tx, continue_rx) = mpsc::channel(); + *coordinator.before_classified_request.lock().unwrap() = Some(Box::new(move || { + seen_tx.send(()).unwrap(); continue_rx.recv().unwrap(); + })); + std::thread::scope(|scope| { + let classifier = scope.spawn(|| classify_structured_on(0x7E57_D005, &pending, &coordinator, &q)); + seen_rx.recv().unwrap(); + assert!(q.try_run_one_between(Priority::Speculative, Priority::Preload)); + drop(background.wait_and_take_pin().unwrap()); drop(background); + assert_eq!(coordinator.reconcile(1), 1); + continue_tx.send(()).unwrap(); + let outcome = classifier.join().unwrap(); + assert!(matches!(outcome, StructuredResolve::Ready { raw, pin: Some(_), .. } if raw == replacement_raw), + "stale cancelled request hid a concurrently published generation"); + drop(outcome); + }); + assert_eq!(coordinator.reconcile(2), 1, "stale request was not retired"); + let raw_owner = build.real.swap(0, Ordering::AcqRel); + drop(pending); drop(build); drop(recipe); release(raw_owner); + assert_eq!((first.refs.load(Ordering::Relaxed), replacement.refs.load(Ordering::Relaxed)), (0, 0)); + } + #[test] fn pressure_observer_bounds_inspection_and_requeues_every_resident() { let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; From 0a2c5dafef279242b3b8bef6a82a0ba6680536f1 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:10:16 -0800 Subject: [PATCH 252/265] D3D12.X: aggregate native submission timing Record exact total CPU time and a bounded log2 distribution for opt-in native title ExecuteCommandLists timing. Report mean and histogram-derived p95/p99 upper bounds without describing them as GPU execution time. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/real.rs | 113 +++++++++++++++++++++++++----- 1 file changed, 97 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 7a6be9c158..cd74273f58 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -168,14 +168,25 @@ pub struct D3d12Stats { /// DXIL cache and compiler statistics. #[serde(default)] pub dxil_cache: crate::gpu::recomp::dxc::CacheStats, - /// Native title `ExecuteCommandLists` chunks timed while `XCL_GPU_TIMING=1`, plus the CPU - /// duration and list count of the slowest chunk. This is not GPU execution time. + /// Native title `ExecuteCommandLists` chunks timed while `XCL_GPU_TIMING=1`. These are CPU + /// durations inside the native call, not GPU execution or completion time. #[serde(default)] pub submissions: u64, #[serde(default)] pub slowest_submission_ms: f64, #[serde(default)] pub slowest_submission_lists: usize, + #[serde(default)] + pub submission_total_ns: u64, + #[serde(default)] + pub submission_mean_ms: f64, + #[serde(default)] + pub submission_p95_upper_ms: f64, + #[serde(default)] + pub submission_p99_upper_ms: f64, + /// Counts in base-2 nanosecond buckets. Bucket zero includes zero and one nanosecond. + #[serde(default)] + pub submission_histogram_log2_ns: Vec<u64>, } static ADAPTER: Mutex<String> = Mutex::new(String::new()); @@ -187,27 +198,61 @@ static FALLBACK_RS: AtomicU64 = AtomicU64::new(0); static TRANSLATED_PSO: AtomicU64 = AtomicU64::new(0); static TRANSLATE_ERRORS: Mutex<Vec<String>> = Mutex::new(Vec::new()); -#[derive(Clone, Copy, Default)] +#[derive(Clone, Copy)] struct SubmissionTiming { submissions: u64, - slowest_us: u64, + total_ns: u64, + slowest_ns: u64, slowest_lists: usize, + histogram: [u64; crate::stall::HISTOGRAM_BUCKETS], +} + +impl Default for SubmissionTiming { + fn default() -> Self { + Self { + submissions: 0, + total_ns: 0, + slowest_ns: 0, + slowest_lists: 0, + histogram: [0; crate::stall::HISTOGRAM_BUCKETS], + } + } } impl SubmissionTiming { - fn record(&mut self, us: u64, lists: usize) { + fn record(&mut self, ns: u64, lists: usize) { self.submissions = self.submissions.saturating_add(1); - if us > self.slowest_us { - self.slowest_us = us; + self.total_ns = self.total_ns.saturating_add(ns); + let bucket = submission_histogram_bucket(ns); + self.histogram[bucket] = self.histogram[bucket].saturating_add(1); + if ns > self.slowest_ns { + self.slowest_ns = ns; self.slowest_lists = lists; } } + + fn percentile_upper_ns(&self, percentile: u64) -> u64 { + if self.submissions == 0 { return 0 } + let target = ((self.submissions as u128 * percentile as u128 + 99) / 100) as u64; + let mut cumulative = 0u64; + let bucket = self.histogram.iter().position(|count| { + cumulative = cumulative.saturating_add(*count); + cumulative >= target + }).unwrap_or(self.histogram.len() - 1); + if bucket + 1 >= u64::BITS as usize { u64::MAX } else { (1u64 << (bucket + 1)) - 1 } + } +} + +const fn submission_histogram_bucket(ns: u64) -> usize { + if ns == 0 { 0 } else { (u64::BITS - 1 - ns.leading_zeros()) as usize } } static SUBMISSION_TIMING: Mutex<SubmissionTiming> = Mutex::new(SubmissionTiming { submissions: 0, - slowest_us: 0, + total_ns: 0, + slowest_ns: 0, slowest_lists: 0, + histogram: [0; crate::stall::HISTOGRAM_BUCKETS], }); fn gpu_timing_on_value(value: Option<&str>) -> bool { @@ -229,10 +274,11 @@ fn slow_submission_us() -> u64 { } fn note_submission_timing(elapsed: std::time::Duration, lists: usize, queue: *mut c_void) { - let us = elapsed.as_micros().min(u64::MAX as u128) as u64; + let ns = elapsed.as_nanos().min(u64::MAX as u128) as u64; if let Ok(mut timing) = SUBMISSION_TIMING.lock() { - timing.record(us, lists); + timing.record(ns, lists); } + let us = ns / 1_000; if us >= slow_submission_us() { crate::xlog_warn!("ExecuteCommandLists: {us} µs of CPU time for {lists} list(s), queue {queue:p}"); } @@ -513,8 +559,15 @@ pub fn stats() -> D3d12Stats { background_pipelines: super::pso_async::counts(), dxil_cache: crate::gpu::recomp::dxc::cache_stats(), submissions: submission_timing.submissions, - slowest_submission_ms: submission_timing.slowest_us as f64 / 1_000.0, + slowest_submission_ms: submission_timing.slowest_ns as f64 / 1_000_000.0, slowest_submission_lists: submission_timing.slowest_lists, + submission_total_ns: submission_timing.total_ns, + submission_mean_ms: if submission_timing.submissions == 0 { 0.0 } else { + submission_timing.total_ns as f64 / submission_timing.submissions as f64 / 1_000_000.0 + }, + submission_p95_upper_ms: submission_timing.percentile_upper_ns(95) as f64 / 1_000_000.0, + submission_p99_upper_ms: submission_timing.percentile_upper_ns(99) as f64 / 1_000_000.0, + submission_histogram_log2_ns: submission_timing.histogram.into(), } } @@ -9298,12 +9351,25 @@ mod submission_timing_tests { use super::*; #[test] - fn submission_timing_keeps_one_exact_slowest_sample() { + fn submission_timing_keeps_exact_total_histogram_and_slowest_sample() { let mut timing = SubmissionTiming::default(); - timing.record(20, 2); - timing.record(10, 9); - timing.record(30, 4); - assert_eq!((timing.submissions, timing.slowest_us, timing.slowest_lists), (3, 30, 4)); + timing.record(0, 2); + timing.record(1, 9); + timing.record(2, 3); + timing.record(3, 5); + timing.record(8, 4); + assert_eq!((timing.submissions, timing.total_ns, timing.slowest_ns, timing.slowest_lists), (5, 14, 8, 4)); + assert_eq!((timing.histogram[0], timing.histogram[1], timing.histogram[3]), (2, 2, 1)); + assert_eq!((timing.percentile_upper_ns(95), timing.percentile_upper_ns(99)), (15, 15)); + } + + #[test] + fn submission_timing_saturates_totals_and_uses_bounded_last_bucket() { + let mut timing = SubmissionTiming { submissions: u64::MAX, total_ns: u64::MAX, ..Default::default() }; + timing.record(u64::MAX, 7); + assert_eq!((timing.submissions, timing.total_ns, timing.slowest_ns), (u64::MAX, u64::MAX, u64::MAX)); + assert_eq!(timing.histogram[crate::stall::HISTOGRAM_BUCKETS - 1], 1); + assert_eq!(timing.percentile_upper_ns(99), u64::MAX); } #[test] @@ -9593,6 +9659,21 @@ mod cache_report_tests { crate::gpu::recomp::dxc::CacheStats::default() ); } + + #[test] + fn reports_without_submission_distribution_still_deserialize() { + let mut old = serde_json::to_value(D3d12Stats::default()).unwrap(); + let old = old.as_object_mut().unwrap(); + for field in [ + "submission_total_ns", "submission_mean_ms", "submission_p95_upper_ms", + "submission_p99_upper_ms", "submission_histogram_log2_ns", + ] { + old.remove(field); + } + let decoded: D3d12Stats = serde_json::from_value(serde_json::Value::Object(old.clone())).unwrap(); + assert_eq!(decoded.submission_total_ns, 0); + assert!(decoded.submission_histogram_log2_ns.is_empty()); + } } #[cfg(test)] From 56120a27651b6281490989b2653b621ae958f7e9 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:10:16 -0800 Subject: [PATCH 253/265] Scripts: compare submission timing distributions Validate complete timing histograms, preserve legacy and missing reports explicitly, and compare aggregate CPU submission time and bounded tail estimates. Assisted-by: Codex (GPT-5.6-sol) --- scripts/perf-compare.ps1 | 46 +++++++++++++++++++++++++-------- scripts/perf-compare.tests.ps1 | 47 +++++++++++++++++++++++++++++++--- 2 files changed, 80 insertions(+), 13 deletions(-) diff --git a/scripts/perf-compare.ps1 b/scripts/perf-compare.ps1 index ccfbc35555..d8ed637c4e 100644 --- a/scripts/perf-compare.ps1 +++ b/scripts/perf-compare.ps1 @@ -114,24 +114,45 @@ function Read-SubmissionTiming([string]$Root, [int]$Order, [string]$Label) { $mode = $Label.Substring(4) $report = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'report.json')) if (-not (Test-Path -LiteralPath $report -PathType Leaf)) { - return [ordered]@{ status = 'missing_report'; counters = $null } + return [ordered]@{ status = 'missing_report'; counters = $null; histogram_log2_ns = $null } } $json = Read-Json $report if (-not (Has-Property $json 'd3d12') -or $null -eq $json.d3d12) { - return [ordered]@{ status = 'missing_d3d12'; counters = $null } + return [ordered]@{ status = 'missing_d3d12'; counters = $null; histogram_log2_ns = $null } } - $names = @('submissions', 'slowest_submission_ms', 'slowest_submission_lists') - $present = @($names | Where-Object { (Has-Property $json.d3d12 $_) -and $null -ne $json.d3d12.$_ }) + $legacyNames = @('submissions', 'slowest_submission_ms', 'slowest_submission_lists') + $extendedNames = @('submission_total_ns', 'submission_mean_ms', 'submission_p95_upper_ms', + 'submission_p99_upper_ms', 'submission_histogram_log2_ns') + $present = @($legacyNames | Where-Object { (Has-Property $json.d3d12 $_) -and $null -ne $json.d3d12.$_ }) + $extendedPresent = @($extendedNames | Where-Object { (Has-Property $json.d3d12 $_) -and $null -ne $json.d3d12.$_ }) if ($present.Count -eq 0) { - return [ordered]@{ status = 'missing_metrics'; counters = $null } + if ($extendedPresent.Count -ne 0) { throw "incomplete submission timing in $report" } + return [ordered]@{ status = 'missing_metrics'; counters = $null; histogram_log2_ns = $null } } - if ($present.Count -ne $names.Count) { throw "incomplete submission timing in $report" } + if ($present.Count -ne $legacyNames.Count) { throw "incomplete submission timing in $report" } $counters = [ordered]@{ submissions = Read-Nonnegative-Integer $json.d3d12 'submissions' "submission timing in $report" slowest_submission_ms = Read-Nonnegative-Number $json.d3d12 'slowest_submission_ms' "submission timing in $report" slowest_submission_lists = Read-Nonnegative-Integer $json.d3d12 'slowest_submission_lists' "submission timing in $report" } - return [ordered]@{ status = 'present'; counters = $counters } + if ($extendedPresent.Count -eq 0) { + return [ordered]@{ status = 'present_legacy'; counters = $counters; histogram_log2_ns = $null } + } + if ($extendedPresent.Count -ne $extendedNames.Count) { throw "incomplete extended submission timing in $report" } + $counters['submission_total_ns'] = Read-Nonnegative-Integer $json.d3d12 'submission_total_ns' "submission timing in $report" + $counters['submission_mean_ms'] = Read-Nonnegative-Number $json.d3d12 'submission_mean_ms' "submission timing in $report" + $counters['submission_p95_upper_ms'] = Read-Nonnegative-Number $json.d3d12 'submission_p95_upper_ms' "submission timing in $report" + $counters['submission_p99_upper_ms'] = Read-Nonnegative-Number $json.d3d12 'submission_p99_upper_ms' "submission timing in $report" + $histogram = @($json.d3d12.submission_histogram_log2_ns) + if ($histogram.Count -ne 64) { throw "malformed submission timing histogram in $report" } + $histogram = @($histogram | ForEach-Object { + $value = [pscustomobject]@{ value = $_ } + Read-Nonnegative-Integer $value 'value' "submission timing histogram in $report" + }) + $histogramCount = [decimal]0 + foreach ($count in $histogram) { $histogramCount += $count } + if ($histogramCount -ne $counters.submissions) { throw "submission timing histogram count differs in $report" } + return [ordered]@{ status = 'present'; counters = $counters; histogram_log2_ns = $histogram } } function Read-Preparation([string]$Root, [int]$Order, [string]$Label) { @@ -339,7 +360,8 @@ for ($i = 0; $i -lt 2; $i++) { $sparseUploadGate = Compare-Counters $beforeSparseGate.counters $afterSparseGate.counters $sparseGateNames $beforeSubmissionTiming = Read-SubmissionTiming $baselineRoot ($i + 1) $beforeRun.cache_state $afterSubmissionTiming = Read-SubmissionTiming $candidateRoot ($i + 1) $afterRun.cache_state - $submissionTimingNames = @('submissions', 'slowest_submission_ms', 'slowest_submission_lists') + $submissionTimingNames = @('submissions', 'slowest_submission_ms', 'slowest_submission_lists', + 'submission_total_ns', 'submission_mean_ms', 'submission_p95_upper_ms', 'submission_p99_upper_ms') $submissionTiming = Compare-Counters $beforeSubmissionTiming.counters $afterSubmissionTiming.counters $submissionTimingNames $comparison = [ordered]@{ @@ -384,6 +406,10 @@ for ($i = 0; $i -lt 2; $i++) { candidate = $afterSubmissionTiming.status } submission_timing = $submissionTiming + submission_timing_histogram_log2_ns = [ordered]@{ + baseline = $beforeSubmissionTiming.histogram_log2_ns + candidate = $afterSubmissionTiming.histogram_log2_ns + } } $comparisons += $comparison @@ -421,9 +447,9 @@ for ($i = 0; $i -lt 2; $i++) { } } Write-Host " submission timing: $($beforeSubmissionTiming.status) -> $($afterSubmissionTiming.status)" - if ($beforeSubmissionTiming.status -eq 'present' -or $afterSubmissionTiming.status -eq 'present') { + if ($beforeSubmissionTiming.status -like 'present*' -or $afterSubmissionTiming.status -like 'present*') { foreach ($name in $submissionTiming.delta.Keys) { - $suffix = if ($name -eq 'slowest_submission_ms') { ' ms' } else { '' } + $suffix = if ($name -like '*_ms') { ' ms' } elseif ($name -eq 'submission_total_ns') { ' ns' } else { '' } Write-Host " $($name): $(Display-Value $submissionTiming.baseline.$name $suffix) -> $(Display-Value $submissionTiming.candidate.$name $suffix); delta $(Display-Value $submissionTiming.delta.$name $suffix)" } } diff --git a/scripts/perf-compare.tests.ps1 b/scripts/perf-compare.tests.ps1 index 7deba246a4..8c077f1660 100644 --- a/scripts/perf-compare.tests.ps1 +++ b/scripts/perf-compare.tests.ps1 @@ -61,8 +61,23 @@ try { $afterRanked = [ordered]@{ submissions = 24; started = 20; promoted = 2 } $beforeAllocator = [ordered]@{ outer_execute_calls = 10; chunks = 13; multi_chunk_calls = 2; forced_wait_boundaries = 3; lists_marked = 40; backing_mark_writes = 20; signal_attempts = 13; signal_failures = 1; state_lock_wait_ns = 100; state_lock_hold_ns = 500 } $afterAllocator = [ordered]@{ outer_execute_calls = 12; chunks = 14; multi_chunk_calls = 1; forced_wait_boundaries = 2; lists_marked = 44; backing_mark_writes = 22; signal_attempts = 14; signal_failures = 0; state_lock_wait_ns = 80; state_lock_hold_ns = 450 } - $beforeSubmissionTiming = [ordered]@{ submissions = 20; slowest_submission_ms = 3.5; slowest_submission_lists = 4 } - $afterSubmissionTiming = [ordered]@{ submissions = 24; slowest_submission_ms = 2.25; slowest_submission_lists = 3 } + $beforeHistogram = @(0) * 64 + $beforeHistogram[20] = 20 + $afterHistogram = @(0) * 64 + $afterHistogram[19] = 18 + $afterHistogram[21] = 6 + $beforeSubmissionTiming = [ordered]@{ + submissions = 20; slowest_submission_ms = 3.5; slowest_submission_lists = 4 + submission_total_ns = 20000000; submission_mean_ms = 1.0 + submission_p95_upper_ms = 2.097151; submission_p99_upper_ms = 2.097151 + submission_histogram_log2_ns = $beforeHistogram + } + $afterSubmissionTiming = [ordered]@{ + submissions = 24; slowest_submission_ms = 2.25; slowest_submission_lists = 3 + submission_total_ns = 18000000; submission_mean_ms = 0.75 + submission_p95_upper_ms = 4.194303; submission_p99_upper_ms = 4.194303 + submission_histogram_log2_ns = $afterHistogram + } Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation 3 $beforeRanked $beforeAllocator $beforeSubmissionTiming Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator $afterSubmissionTiming -ExtraKind [ordered]@{ d3d12 = [ordered]@{} } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $baseline 'runs\02-warm\report.json') -Encoding utf8 @@ -144,7 +159,10 @@ try { $json.runs[0].submission_timing_status.candidate -ne 'present' -or $timing.baseline.submissions -ne 20 -or $timing.candidate.submissions -ne 24 -or $timing.delta.submissions -ne 4 -or $timing.delta.slowest_submission_ms -ne -1.25 -or - $timing.delta.slowest_submission_lists -ne -1) { + $timing.delta.slowest_submission_lists -ne -1 -or $timing.delta.submission_total_ns -ne -2000000 -or + $timing.delta.submission_mean_ms -ne -0.25 -or $timing.delta.submission_p95_upper_ms -ne 2.097152 -or + $json.runs[0].submission_timing_histogram_log2_ns.baseline[20] -ne 20 -or + $json.runs[0].submission_timing_histogram_log2_ns.candidate[21] -ne 6) { throw 'submission timing counters, status, or deltas are wrong' } if ($json.runs[1].submission_timing_status.baseline -ne 'missing_metrics' -or @@ -152,6 +170,29 @@ try { $null -ne $json.runs[1].submission_timing.delta.submissions) { throw 'missing submission timing was treated as zero' } + $legacySubmissionTiming = [ordered]@{ submissions = 24; slowest_submission_ms = 2.25; slowest_submission_lists = 3 } + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator $legacySubmissionTiming -ExtraKind + $legacy = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json + if ($legacy.runs[0].submission_timing_status.candidate -ne 'present_legacy' -or + $legacy.runs[0].submission_timing.delta.submissions -ne 4 -or + $null -ne $legacy.runs[0].submission_timing.delta.submission_total_ns -or + $null -ne $legacy.runs[0].submission_timing_histogram_log2_ns.candidate) { + throw 'legacy submission timing was not preserved explicitly' + } + $badTimingPath = Join-Path $candidate 'runs\01-cold\report.json' + Write-Report $badTimingPath 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator $afterSubmissionTiming -ExtraKind + $badTiming = Get-Content -LiteralPath $badTimingPath -Raw -Encoding utf8 | ConvertFrom-Json + $badTiming.d3d12.submission_histogram_log2_ns[0] = 1 + $badTiming | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $badTimingPath -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'histogram count differs' } + if (-not $refused) { throw 'a submission histogram with the wrong count was not refused' } + [ordered]@{ d3d12 = [ordered]@{ submission_total_ns = 1 } } | + ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $badTimingPath -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'incomplete submission timing' } + if (-not $refused) { throw 'orphaned extended submission timing was not refused' } + Write-Report $badTimingPath 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator $afterSubmissionTiming -ExtraKind $badGateLog = Join-Path $candidate 'runs\02-warm\xcl.log' 'upload gate submit wait/hold malformed' | Set-Content -LiteralPath $badGateLog -Encoding utf8 $refused = $false From b534e4f958ba03256a86f5a2f30ed3f7071d60a6 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:11:46 -0800 Subject: [PATCH 254/265] D3D12.X: retain pipeline decisions in bind state Carry an opaque structured pipeline decision through command-list resets and split continuations without classifying or waiting in live paths. Replaced decisions are released after the bind-state lock so later native generation owners may re-enter bookkeeping safely. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 64 ++++++++++++++++++-------- crates/xcl/src/hle/d3d12x/pso_async.rs | 8 ++++ 2 files changed, 52 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 8d63d78405..b18490150a 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -29,6 +29,8 @@ struct State { /// untranslated pipeline – created with it – since SetGraphicsRootSignature binds nothing rs_gfx: usize, pso: usize, + /// Retained decision for `pso`; live classification is added by a later stage. + resolution: Option<super::pso_async::PipelineResolution>, allocator: usize, /// unified memory of this recording (io, argument tables) uma: Vec<usize>, @@ -86,32 +88,37 @@ fn native_backing(list: *mut c_void, allocator: usize) -> usize { /// pipeline and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { let backing = native_backing(list, allocator); - let (old, blocks) = with(list, |s| { + let (old, blocks, old_resolution) = with(list, |s| { let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.pso = initial_pso; + let old_resolution = s.resolution.take(); s.layout = None; s.args.clear(); s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; s.limits = [0; 3]; - (old, std::mem::take(&mut s.uma)) + (old, std::mem::take(&mut s.uma), old_resolution) }); console_list::hold_until_reset(old, blocks); + drop(old_resolution); } /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults /// with `pso` bound, keeping the current recording's allocator and UMA arena intact. pub(super) fn clear_state(list: *mut c_void, pso: usize) { - with(list, |s| { + let old_resolution = with(list, |s| { s.pso = pso; + let old_resolution = s.resolution.take(); s.layout = None; s.args.clear(); s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + old_resolution }); + drop(old_resolution); } /// Allocation-bearing root state captured before a mid-list split commits. Preparation also @@ -125,12 +132,14 @@ pub(super) struct PreparedSplit { args_gfx: Vec<u8>, rs_gfx: usize, pso: usize, + resolution: Option<super::pso_async::PipelineResolution>, } pub(super) fn prepare_split(from: *mut c_void, to: *mut c_void, allocator: usize) -> PreparedSplit { let backing = native_backing(to, allocator); - let (layout, args, layout_gfx, args_gfx, rs_gfx, pso) = with(from, |s| { - (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso) + let (layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution) = with(from, |s| { + (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso, + s.resolution.clone()) }); let (old, blocks) = with(to, |s| { let old = std::mem::replace(&mut s.allocator, 0); @@ -138,23 +147,27 @@ pub(super) fn prepare_split(from: *mut c_void, to: *mut c_void, allocator: usize (old, std::mem::take(&mut s.uma)) }); console_list::hold_until_reset(old, blocks); - PreparedSplit { to: to as usize, allocator: backing, layout, args, layout_gfx, args_gfx, rs_gfx, pso } + PreparedSplit { to: to as usize, allocator: backing, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution } } /// Install a preflighted split state without cloning or growing the state map. pub(super) fn install_prepared_split(prepared: PreparedSplit) { - let PreparedSplit { to, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso } = prepared; - let mut states = STATES.lock().unwrap(); - let s = states.as_mut().and_then(|m| m.get_mut(&to)).expect("prepared split destination state"); - debug_assert_eq!(s.allocator, 0); - debug_assert!(s.uma.is_empty()); - s.allocator = allocator; - s.layout = layout; - s.args = args; - s.layout_gfx = layout_gfx; - s.args_gfx = args_gfx; - s.rs_gfx = rs_gfx; - s.pso = pso; + let PreparedSplit { to, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution } = prepared; + let old_resolution = { + let mut states = STATES.lock().unwrap(); + let s = states.as_mut().and_then(|m| m.get_mut(&to)).expect("prepared split destination state"); + debug_assert_eq!(s.allocator, 0); + debug_assert!(s.uma.is_empty()); + s.allocator = allocator; + s.layout = layout; + s.args = args; + s.layout_gfx = layout_gfx; + s.args_gfx = args_gfx; + s.rs_gfx = rs_gfx; + s.pso = pso; + std::mem::replace(&mut s.resolution, resolution) + }; + drop(old_resolution); } pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { @@ -174,7 +187,10 @@ pub(super) fn pass_arena(from: *mut c_void, to: *mut c_void) { /// The list is gone. pub(super) fn forget(list: *mut c_void) { - if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { + let removed = { + STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) + }; + if let Some(s) = removed { console_list::hold_until_reset(s.allocator, s.uma); } } @@ -976,10 +992,18 @@ pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_vo /// #25 SetPipelineState: noted, then bound as on the PC pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: *mut c_void) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); - with(this, |s| s.pso = pso as usize); + set_tracked_pipeline_state(this, pso as usize); super::real::bind_pipeline(this, pso); } +fn set_tracked_pipeline_state(this: *mut c_void, pso: usize) { + let old_resolution = with(this, |s| { + s.pso = pso; + s.resolution.take() + }); + drop(old_resolution); +} + /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDispatch); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 6e47420db8..c6f7ac7f90 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -6749,6 +6749,14 @@ enum StructuredResolve<const R: usize> { }, } +const PIPELINE_RESOLUTION_RECEIPTS: usize = 1024; + +/// Opaque retained resolver decision carried by command-list state. Live callers do not make +/// these yet; the later classification stage supplies them without exposing coordinator types. +#[allow(dead_code)] +#[derive(Clone)] +pub(super) struct PipelineResolution(StructuredResolve<PIPELINE_RESOLUTION_RECEIPTS>); + #[allow(dead_code)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum StructuredResolveFailure { From 1f21f9948a98390067aeff2c0b054de81bdb47f1 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:12:34 -0800 Subject: [PATCH 255/265] Tests: cover retained pipeline decisions in bind state Exercise reset, clear, bind replacement, forget, split continuation identity, and title-address reuse. Final retained-decision destruction proves it can re-enter bind bookkeeping without the state lock held. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 59 +++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/pso_async.rs | 53 +++++++++++++++++++++++ 2 files changed, 111 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index b18490150a..4fa002a51f 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1301,7 +1301,7 @@ pub(super) fn tracked_pso(list: *mut c_void) -> usize { mod tests { use super::super::{device_x, list_x, pso_async, real, title_list}; use super::*; - use std::sync::atomic::AtomicUsize; + use std::sync::atomic::{AtomicBool, AtomicUsize}; /// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone. #[test] @@ -1570,6 +1570,63 @@ void main(uint t : SV_GroupIndex) { forget(list); } + fn probed_resolution(list: usize, original: usize, dropped: Arc<AtomicBool>) + -> pso_async::PipelineResolution { + pso_async::pipeline_resolution_for_test(original, move || { + assert!(STATES.try_lock().is_ok(), "pipeline resolution dropped under bind::STATES"); + dropped.store(true, Ordering::Release); + let _ = list; + }) + } + + #[test] + fn pipeline_resolution_replacements_drop_outside_state_lock() { + let cases: [fn(*mut c_void); 4] = [ + |list| clear_state(list, 0x7100_5001), + |list| reset(list, 0, 0x7100_5002), + |list| set_tracked_pipeline_state(list, 0x7100_5003), + forget, + ]; + for (n, replace) in cases.into_iter().enumerate() { + let list = (0x7100_5100usize + n) as *mut c_void; + let dropped = Arc::new(AtomicBool::new(false)); + let resolution = probed_resolution(list as usize, 0x7100_5200 + n, dropped.clone()); + with(list, |s| s.resolution = Some(resolution)); + replace(list); + assert!(dropped.load(Ordering::Acquire), "case {n} retained the replaced resolution"); + if n + 1 != cases.len() { + forget(list); + } + } + } + + #[test] + fn split_retains_the_exact_resolution_across_address_reuse() { + let from = 0x7100_6001usize as *mut c_void; + let to = 0x7100_6002usize as *mut c_void; + let original = 0x7100_6100usize; + let old = pso_async::pipeline_resolution_for_test(original, || {}); + let old_identity = old.identity_for_test(); + with(from, |s| { + s.pso = original; + s.resolution = Some(old); + }); + reset(to, 0, 0); + + let prepared = prepare_split(from, to, 0); + let replacement = pso_async::pipeline_resolution_for_test(original, || {}); + let replacement_identity = replacement.identity_for_test(); + assert_ne!(old_identity.1, replacement_identity.1); + with(from, |s| s.resolution = Some(replacement)); + install_prepared_split(prepared); + + assert_eq!(with(to, |s| s.resolution.as_ref().unwrap().identity_for_test()), old_identity, + "split state was redirected to the Pending now stored at the reused title address"); + assert_eq!(with(from, |s| s.resolution.as_ref().unwrap().identity_for_test()), replacement_identity); + forget(from); + forget(to); + } + #[test] fn split_preflight_transfers_destination_uma_before_install() { let from = 0x7101_0001usize as *mut c_void; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index c6f7ac7f90..5c7783686e 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -6757,6 +6757,59 @@ const PIPELINE_RESOLUTION_RECEIPTS: usize = 1024; #[derive(Clone)] pub(super) struct PipelineResolution(StructuredResolve<PIPELINE_RESOLUTION_RECEIPTS>); +#[cfg(test)] +struct PipelineResolutionDropProbe(Option<Box<dyn FnOnce() + Send>>); + +#[cfg(test)] +impl Drop for PipelineResolutionDropProbe { + fn drop(&mut self) { + if let Some(on_drop) = self.0.take() { + on_drop(); + } + } +} + +#[cfg(test)] +pub(super) fn pipeline_resolution_for_test( + original: usize, + on_drop: impl FnOnce() + Send + 'static, +) -> PipelineResolution { + let probe = PipelineResolutionDropProbe(Some(Box::new(on_drop))); + let build = Arc::new(Build::new(Box::new(move || { + let _keep = &probe; + 0 + }), false)); + let pending = Arc::new(Pending { + build, + driver: AtomicUsize::new(0), + compute: false, + key: 0, + used: AtomicBool::new(false), + late: AtomicBool::new(false), + spared: AtomicBool::new(false), + }); + PipelineResolution(StructuredResolve::Initial { + original, + pending, + fallback: original, + bound_unbuilt: true, + }) +} + +#[cfg(test)] +impl PipelineResolution { + pub(super) fn identity_for_test(&self) -> (usize, usize) { + match &self.0 { + StructuredResolve::Initial { original, pending, .. } + | StructuredResolve::Restoring { original, pending, .. } + | StructuredResolve::Terminal { original, pending, .. } => { + (*original, Arc::as_ptr(pending) as usize) + } + StructuredResolve::Ready { original, .. } => (*original, 0), + } + } +} + #[allow(dead_code)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum StructuredResolveFailure { From 7fa80e83d48f16c846ec489b2ba1eeeff722d67f Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:18:07 -0800 Subject: [PATCH 256/265] D3D12.X: own one dormant restoration coordinator Give the later bind integration one bounded coordinator and an opaque nonblocking classification seam. The accessor does not start workers, enable eviction, install bind state, or wait for restoration. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 36 ++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 5c7783686e..735fbc0e44 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -6749,7 +6749,19 @@ enum StructuredResolve<const R: usize> { }, } +const PIPELINE_RESTORATION_EVICTIONS: usize = 1024; const PIPELINE_RESOLUTION_RECEIPTS: usize = 1024; +type PipelineRestorationCoordinator = + RestorationCoordinator<PIPELINE_RESTORATION_EVICTIONS, PIPELINE_RESOLUTION_RECEIPTS>; + +/// One dormant coordinator identity for the later live classification stage. Merely obtaining it +/// neither starts workers nor enables eviction; no production caller classifies through it yet. +fn pipeline_restoration_coordinator() -> &'static PipelineRestorationCoordinator { + static COORDINATOR: OnceLock<PipelineRestorationCoordinator> = OnceLock::new(); + COORDINATOR.get_or_init(|| { + PipelineRestorationCoordinator::new(1).expect("nonzero pipeline restoration capacities") + }) +} /// Opaque retained resolver decision carried by command-list state. Live callers do not make /// these yet; the later classification stage supplies them without exposing coordinator types. @@ -6757,6 +6769,30 @@ const PIPELINE_RESOLUTION_RECEIPTS: usize = 1024; #[derive(Clone)] pub(super) struct PipelineResolution(StructuredResolve<PIPELINE_RESOLUTION_RECEIPTS>); +/// Wrap one nonblocking decision without exposing coordinator or receipt types to command-list +/// state. This does not start workers and never runs a queued driver build on the caller. +fn begin_pipeline_resolution_on<const E: usize>( + original: usize, + pending: &Arc<Pending>, + coordinator: &RestorationCoordinator<E, PIPELINE_RESOLUTION_RECEIPTS>, + q: &BuildQueue, +) -> PipelineResolution { + PipelineResolution(classify_structured_on(original, pending, coordinator, q)) +} + +/// Dormant live-queue seam for the later bind integration. There are intentionally no production +/// callers yet; worker startup, state installation, and emission waits remain separate stages. +#[allow(dead_code)] +fn begin_pipeline_resolution(original: usize) -> Option<PipelineResolution> { + let pending = entry(original)?; + Some(begin_pipeline_resolution_on( + original, + &pending, + pipeline_restoration_coordinator(), + queue(), + )) +} + #[cfg(test)] struct PipelineResolutionDropProbe(Option<Box<dyn FnOnce() + Send>>); From cdb0cd9514697be85ea91f9e7724dc5ff5555ff7 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:18:51 -0800 Subject: [PATCH 257/265] Tests: cover the dormant restoration coordinator Exercise stable singleton identity, bounded eviction-ledger exhaustion and reuse, and queue-shutdown refusal without running driver work on the classifier. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 73 ++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 735fbc0e44..ee4777e063 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -4102,6 +4102,79 @@ mod used_tests { }) } + #[test] + fn dormant_restoration_coordinator_has_one_stable_identity() { + let first = pipeline_restoration_coordinator() as *const _; + let second = pipeline_restoration_coordinator() as *const _; + assert_eq!(first, second); + assert!(PIPELINE_RESTORATION_EVICTIONS > 0 && PIPELINE_RESOLUTION_RECEIPTS > 0); + + let original = 0x7E57_D010usize; + let pending = structured_pending(Arc::new(Build::new(Box::new(|| { + panic!("dormant classification ran initial driver work inline") + }), false)), false); + PENDING.insert(original, pending.clone()); + let resolution = begin_pipeline_resolution(original).expect("registered pipeline"); + assert_eq!(resolution.identity_for_test(), (original, Arc::as_ptr(&pending) as usize)); + assert!(Arc::ptr_eq(&PENDING.remove(original).unwrap(), &pending)); + } + + #[test] + fn restoration_coordinator_reuses_its_bounded_eviction_capacity() { + let coordinator = RestorationCoordinator::<2, PIPELINE_RESOLUTION_RECEIPTS>::new(510).unwrap(); + let first_build = ledger_build(); + let second_build = ledger_build(); + let third_build = ledger_build(); + let first = coordinator.install_eviction(&first_build, ledger_native(70)).unwrap().commit(); + let second = coordinator.install_eviction(&second_build, ledger_native(71)).unwrap().commit(); + assert!(coordinator.install_eviction(&third_build, ledger_native(72)).is_none()); + + assert!(first_build.clear_eviction_token(&first)); + assert!(coordinator.evicted.finish(&first, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&first)); + drop(coordinator.install_eviction(&third_build, ledger_native(72)) + .expect("retired bounded slot was not reusable")); + + assert!(second_build.clear_eviction_token(&second)); + assert!(coordinator.evicted.finish(&second, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&second)); + assert!(coordinator.evicted.records(2).is_empty()); + } + + #[test] + fn dormant_resolution_maps_queue_shutdown_without_inline_driver_work() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + raw + }); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + let pin = recipe.pin_with_residency(raw).0.unwrap(); + let coordinator = RestorationCoordinator::<1, PIPELINE_RESOLUTION_RECEIPTS>::new(511).unwrap(); + let evicted = coordinator.install_eviction(&build, pin.ledger_identity()).unwrap().commit(); + drop(pin); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + let pending = structured_pending(build.clone(), false); + let q = BuildQueue::new(); + q.shutdown(); + + let resolution = begin_pipeline_resolution_on(0x7E57_D011, &pending, &coordinator, &q); + assert_eq!(calls.load(Ordering::Relaxed), 1, "classification ran driver work inline"); + assert!(matches!(resolution.0.wait_exact(), Err(StructuredResolveFailure::Refused))); + assert_eq!(coordinator.reconcile(1), 1); + + assert!(build.clear_eviction_token(&evicted)); + assert!(coordinator.evicted.finish(&evicted, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&evicted)); + drop(resolution); drop(pending); drop(build); drop(recipe); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + #[test] fn structured_resolve_retains_pending_across_title_address_reuse() { let original = 0x7E57_D001usize; From e444225140af46c28cf6fdcb287d20b35eec8d53 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:23:12 -0800 Subject: [PATCH 258/265] Scripts: record Cargo feature performance variants Let paired performance runs build canonical feature sets in deterministic target directories and record the exact executable hash. Comparisons keep workload invariants strict while exposing different baseline and candidate build variants for allocator A/B measurements. Assisted-by: Codex (GPT-5.6-sol) --- scripts/perf-compare.ps1 | 24 ++++++++++++++-- scripts/perf-compare.tests.ps1 | 24 ++++++++++++++-- scripts/perf-run.ps1 | 50 +++++++++++++++++++++++++++++++--- scripts/perf-run.tests.ps1 | 18 ++++++++++++ 4 files changed, 107 insertions(+), 9 deletions(-) diff --git a/scripts/perf-compare.ps1 b/scripts/perf-compare.ps1 index d8ed637c4e..cee046af68 100644 --- a/scripts/perf-compare.ps1 +++ b/scripts/perf-compare.ps1 @@ -38,6 +38,26 @@ function Read-Manifest([string]$Root, [string]$Side) { if ($manifest.dirty -ne $false -or $manifest.build.profile -ne 'release') { throw "$Side is not a clean release run" } + if (Has-Property $manifest.build 'cargo_features') { + $features = @($manifest.build.cargo_features) + [string[]]$canonical = @($features | ForEach-Object { [string]$_ }) + [Array]::Sort($canonical, [StringComparer]::Ordinal) + $seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + $malformedFeature = $false + foreach ($feature in $features) { + if ([string]::IsNullOrWhiteSpace([string]$feature) -or -not $seen.Add([string]$feature)) { + $malformedFeature = $true + } + } + if ($malformedFeature -or ($features -join ',') -cne ($canonical -join ',')) { + throw "$Side has malformed Cargo features" + } + } + if (Has-Property $manifest.build 'executable_sha256') { + if ([string]$manifest.build.executable_sha256 -cnotmatch '^[0-9a-f]{64}$') { + throw "$Side has malformed executable identity" + } + } if ([string]::IsNullOrWhiteSpace([string]$manifest.commit) -or -not (Has-Property $manifest 'environment')) { throw "$Side manifest is missing commit/environment" } @@ -462,7 +482,7 @@ for ($i = 0; $i -lt 2; $i++) { workload_id_algorithm = $beforeManifest.workload_id_algorithm workload_id_version = [int]$beforeManifest.workload_id_version run_order = @($beforeManifest.run_order) - baseline = [ordered]@{ commit = $beforeManifest.commit; path = $baselineRoot } - candidate = [ordered]@{ commit = $afterManifest.commit; path = $candidateRoot } + baseline = [ordered]@{ commit = $beforeManifest.commit; path = $baselineRoot; build = $beforeManifest.build } + candidate = [ordered]@{ commit = $afterManifest.commit; path = $candidateRoot; build = $afterManifest.build } runs = $comparisons } | ConvertTo-Json -Depth 12 diff --git a/scripts/perf-compare.tests.ps1 b/scripts/perf-compare.tests.ps1 index 8c077f1660..c64607bcf3 100644 --- a/scripts/perf-compare.tests.ps1 +++ b/scripts/perf-compare.tests.ps1 @@ -4,14 +4,20 @@ $fixture = Join-Path ([IO.Path]::GetTempPath()) ('xcl-perf-compare-test-' + [gui $baseline = Join-Path $fixture 'baseline' $candidate = Join-Path $fixture 'candidate' -function Write-Fixture([string]$Root, [string]$Commit, [int]$ColdMs, $WarmMs) { +function Write-Fixture([string]$Root, [string]$Commit, [int]$ColdMs, $WarmMs, + [string[]]$CargoFeatures = @(), [string]$ExecutableSha256 = ('0' * 64)) { $null = New-Item -ItemType Directory -Path (Join-Path $Root 'runs\01-cold'), (Join-Path $Root 'runs\02-warm') -Force $manifest = [ordered]@{ schema = 'xcl-perf-run' version = 1 commit = $Commit dirty = $false - build = [ordered]@{ profile = 'release' } + build = [ordered]@{ + profile = 'release' + cargo_features = @($CargoFeatures) + target_dir_kind = 'repository-default' + executable_sha256 = $ExecutableSha256 + } workload_id = 'same-workload' workload_id_algorithm = 'sha256-relative-path-length-mtime-utc-ticks' workload_id_version = 1 @@ -54,7 +60,7 @@ function Write-Report([string]$Path, [int]$Count, [long]$Total, [long]$Maximum, try { Write-Fixture $baseline 'base-commit' 1000 0 - Write-Fixture $candidate 'candidate-commit' 850 0 + Write-Fixture $candidate 'candidate-commit' 850 0 @('mimalloc-allocator') ('1' * 64) $beforePreparation = [ordered]@{ keyed_submissions = 12; coalescing_hits = 5; unique_keyed_builds = 7; current_in_flight = 0; peak_in_flight = 3 } $afterPreparation = [ordered]@{ keyed_submissions = 10; coalescing_hits = 6; unique_keyed_builds = 4; current_in_flight = 1; peak_in_flight = 5 } $beforeRanked = [ordered]@{ submissions = 20; started = 15; promoted = 3 } @@ -94,6 +100,18 @@ try { if ($json.schema -ne 'xcl-perf-comparison' -or $json.version -ne 1) { throw 'wrong output schema' } if ($json.workload_id_algorithm -ne 'sha256-relative-path-length-mtime-utc-ticks' -or $json.workload_id_version -ne 1) { throw 'workload identity contract is missing from output' } + if (@($json.baseline.build.cargo_features).Count -ne 0 -or + (@($json.candidate.build.cargo_features) -join ',') -ne 'mimalloc-allocator' -or + $json.candidate.build.executable_sha256 -ne ('1' * 64)) { + throw 'different build variants were refused or not exposed in comparison output' + } + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.build.cargo_features = @('zeta', 'alpha') + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed Cargo features' } + if (-not $refused) { throw 'noncanonical build features were not refused' } + Write-Fixture $candidate 'candidate-commit' 850 0 @('mimalloc-allocator') ('1' * 64) if ($json.runs[0].duration_ms.delta -ne -150) { throw 'cold duration delta is wrong' } if ($json.runs[1].duration_ms.delta -ne 0) { throw 'zero durations were not compared as raw values' } if ($json.runs[1].exit_code.candidate -ne $null -or $json.runs[1].timed_out.candidate -ne $true) { throw 'missing exit/timeout was not preserved' } diff --git a/scripts/perf-run.ps1 b/scripts/perf-run.ps1 index 14f73995fa..9c5aa3fe99 100644 --- a/scripts/perf-run.ps1 +++ b/scripts/perf-run.ps1 @@ -4,7 +4,9 @@ param( [Parameter(Mandatory = $true)][string]$Game, [Parameter(Mandatory = $true)][string]$OutDir, - [int]$Seconds = 120 + [int]$Seconds = 120, + [string[]]$CargoFeatures = @(), + [string]$CargoTargetDir ) $ErrorActionPreference = 'Stop' @@ -15,6 +17,22 @@ $root = Split-Path $PSScriptRoot -Parent $workloadAlgorithm = 'sha256-relative-path-length-mtime-utc-ticks' $workloadAlgorithmVersion = 1 +function Get-CanonicalCargoFeatures([string[]]$Values) { + $features = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + foreach ($value in @($Values)) { + foreach ($feature in @($value -split '[,\s]+')) { + if ([string]::IsNullOrWhiteSpace($feature)) { continue } + if ($feature.StartsWith('-')) { throw "invalid Cargo feature: $feature" } + $null = $features.Add($feature) + } + } + [string[]]$canonical = @($features) + [Array]::Sort($canonical, [StringComparer]::Ordinal) + return $canonical +} + +$cargoFeaturesCanonical = @(Get-CanonicalCargoFeatures $CargoFeatures) + function Read-InventoryRecords([string]$Path) { $separators = [char[]]@([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar) $prefix = $Path.TrimEnd($separators) + [IO.Path]::DirectorySeparatorChar @@ -79,9 +97,25 @@ if (Test-Path -LiteralPath $OutDir) { } $outPath = [IO.Path]::GetFullPath($OutDir) +$cargoTargetKind = 'repository-default' +$cargoTargetPath = Join-Path $root 'target' +if (-not [string]::IsNullOrWhiteSpace($CargoTargetDir)) { + $cargoTargetKind = 'explicit' + $cargoTargetPath = if ([IO.Path]::IsPathRooted($CargoTargetDir)) { + [IO.Path]::GetFullPath($CargoTargetDir) + } else { + [IO.Path]::GetFullPath((Join-Path $root $CargoTargetDir)) + } +} +[string[]]$cargoArguments = @('build', '--locked', '--release', '-p', 'xcl') +if ($cargoFeaturesCanonical.Count -ne 0) { + $cargoArguments += '--features=' + [string]::Join(',', $cargoFeaturesCanonical) +} +$cargoArguments += '--target-dir', $cargoTargetPath + Push-Location $root try { - & cargo build --locked --release -p xcl + & cargo @cargoArguments if ($LASTEXITCODE -ne 0) { throw "release build failed with exit code $LASTEXITCODE" } } finally { Pop-Location @@ -90,12 +124,13 @@ if (@(Run-Git -Arguments @('status', '--porcelain', '--untracked-files=all')).Co throw 'the worktree changed during the release build' } -$xcl = Join-Path $root 'target\release\xcl.exe' +$xcl = Join-Path $cargoTargetPath 'release\xcl.exe' # Test scripts use a command file after still exercising the clean-tree and release-build steps. if ($env:XCL_PERF_RUN_TESTING -eq '1' -and $env:XCL_PERF_RUN_TEST_XCL) { $xcl = $env:XCL_PERF_RUN_TEST_XCL } if (-not (Test-Path -LiteralPath $xcl)) { throw "release build did not produce $xcl" } +$xclSha256 = (Get-FileHash -LiteralPath $xcl -Algorithm SHA256).Hash.ToLowerInvariant() $cacheId = [guid]::NewGuid().ToString('n') $cacheRoot = Join-Path ([IO.Path]::GetTempPath()) ("xcl-perf-$cacheId") @@ -232,7 +267,14 @@ try { version = 1 commit = $commit dirty = $false - build = [ordered]@{ profile = 'release'; command = 'cargo build --locked --release -p xcl' } + build = [ordered]@{ + profile = 'release' + command = 'cargo ' + [string]::Join(' ', $cargoArguments) + arguments = @($cargoArguments) + cargo_features = $cargoFeaturesCanonical + target_dir_kind = $cargoTargetKind + executable_sha256 = $xclSha256 + } workload_id = $workloadIdentity.id workload_id_algorithm = $workloadIdentity.algorithm workload_id_version = $workloadIdentity.version diff --git a/scripts/perf-run.tests.ps1 b/scripts/perf-run.tests.ps1 index b94e4df905..986ddb05db 100644 --- a/scripts/perf-run.tests.ps1 +++ b/scripts/perf-run.tests.ps1 @@ -9,6 +9,8 @@ $game = Join-Path $fixture 'Mock Game' $out = Join-Path $fixture 'artifacts' $otherGame = Join-Path (Join-Path $fixture 'other-build') 'Mock Game' $otherOut = Join-Path $fixture 'other-artifacts' +$featureOut = Join-Path $fixture 'feature-artifacts' +$featureTarget = Join-Path $fixture 'feature target' $bin = Join-Path $fixture 'bin' $userData = Join-Path $fixture 'user-data' $userDxil = Join-Path $fixture 'user-dxil' @@ -113,6 +115,22 @@ exit /b 0 if (Test-Path -LiteralPath (Join-Path ([IO.Path]::GetTempPath()) ("xcl-perf-$($manifest.cache.identity)"))) { throw 'the ephemeral cache was not removed' } if ((Get-Content -LiteralPath $cargoMarker -Raw) -notmatch 'build --locked --release -p xcl') { throw 'release build command was not run' } + & (Join-Path $scripts 'perf-run.ps1') -Game $game -OutDir $featureOut -Seconds 2 ` + -CargoFeatures @('zeta,alpha', 'alpha') -CargoTargetDir $featureTarget + if ($LASTEXITCODE -ne 0) { throw "feature perf-run.ps1 exited with $LASTEXITCODE" } + $featureManifest = Get-Content -LiteralPath (Join-Path $featureOut 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + if ((@($featureManifest.build.cargo_features) -join ',') -ne 'alpha,zeta' -or + $featureManifest.build.target_dir_kind -ne 'explicit' -or + $featureManifest.build.executable_sha256 -notmatch '^[0-9a-f]{64}$') { + throw 'the canonical Cargo build variant was not recorded' + } + $cargoInvocation = Get-Content -LiteralPath $cargoMarker -Raw + if ($cargoInvocation -notmatch '--features=alpha,zeta' -or + $cargoInvocation -notmatch '--target-dir' -or + $cargoInvocation -notmatch ([regex]::Escape($featureTarget))) { + throw 'Cargo features/target directory were not passed as canonical arguments' + } + $null = New-Item -ItemType Directory -Path $otherGame -Force 'a different title build with the same folder leaf' | Set-Content -LiteralPath (Join-Path $otherGame 'game-data.bin') -Encoding Ascii & (Join-Path $scripts 'perf-run.ps1') -Game $otherGame -OutDir $otherOut -Seconds 2 From dad23980b39fdbe7fb40a34878d635a6b2d0b902 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:27:24 -0800 Subject: [PATCH 259/265] Tests: benchmark allocator contention across workers Measure a bounded PSO-job-like mix of Box, Arc, Vec, and String allocations with a single-thread control and persistent worker threads. Thread creation stays outside measured iterations so allocator A/B runs report job throughput instead of startup cost. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/benches/runtime.rs | 107 +++++++++++++++++++++++++++++++++- 1 file changed, 106 insertions(+), 1 deletion(-) diff --git a/crates/xcl/benches/runtime.rs b/crates/xcl/benches/runtime.rs index 3ff4a99f4a..6dd6d4f33c 100644 --- a/crates/xcl/benches/runtime.rs +++ b/crates/xcl/benches/runtime.rs @@ -3,6 +3,9 @@ mod support; use std::collections::BTreeMap; use std::hint::black_box; use std::path::Path; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Barrier}; +use std::thread::JoinHandle; use support::{BatchSize, BenchmarkId, Criterion, Throughput}; use xcl::config::Config; use xcl::manifest; @@ -53,6 +56,108 @@ mouse_sensitivity = 1.0 "example.dll!Example" = "S_OK" "#; +const ALLOCATION_JOBS: usize = 128; + +struct AllocationJob { + owner: Arc<[u8; 64]>, + label: String, + payload: Vec<u8>, +} + +fn allocation_job_batch(seed: usize) -> usize { + let owner = Arc::new([seed as u8; 64]); + let mut jobs = Vec::with_capacity(ALLOCATION_JOBS); + for index in 0..ALLOCATION_JOBS { + let mut label = String::with_capacity(48); + label.push_str("pipeline-job-"); + label.extend(std::iter::repeat_n((b'a' + (index % 26) as u8) as char, 16 + index % 16)); + jobs.push(Box::new(AllocationJob { + owner: owner.clone(), + label, + payload: vec![(seed ^ index) as u8; 96 + index % 64], + })); + } + let checksum = jobs.iter().fold(0usize, |checksum, job| { + checksum ^ job.owner[0] as usize ^ job.label.len() ^ job.payload.len() + }); + black_box(&jobs); + checksum +} + +#[repr(align(64))] +struct AllocationResult(AtomicUsize); + +struct AllocationWorkers { + start: Arc<Barrier>, + done: Arc<Barrier>, + stop: Arc<AtomicBool>, + epoch: Arc<AtomicUsize>, + results: Arc<Vec<AllocationResult>>, + threads: Vec<JoinHandle<()>>, +} + +impl AllocationWorkers { + fn new(count: usize) -> Self { + let start = Arc::new(Barrier::new(count + 1)); + let done = Arc::new(Barrier::new(count + 1)); + let stop = Arc::new(AtomicBool::new(false)); + let epoch = Arc::new(AtomicUsize::new(0)); + let results: Arc<Vec<AllocationResult>> = + Arc::new((0..count).map(|_| AllocationResult(AtomicUsize::new(0))).collect()); + let threads = (0..count).map(|worker| { + let start = start.clone(); + let done = done.clone(); + let stop = stop.clone(); + let epoch = epoch.clone(); + let results = results.clone(); + std::thread::Builder::new().name(format!("alloc-bench-{worker}")).spawn(move || loop { + start.wait(); + if stop.load(Ordering::Acquire) { break } + let checksum = allocation_job_batch(epoch.load(Ordering::Acquire).wrapping_add(worker)); + results[worker].0.store(checksum, Ordering::Release); + done.wait(); + }).expect("allocator benchmark worker") + }).collect(); + Self { start, done, stop, epoch, results, threads } + } + + fn run(&self) -> usize { + self.epoch.fetch_add(1, Ordering::Release); + self.start.wait(); + self.done.wait(); + self.results.iter().fold(0, |checksum, result| checksum ^ result.0.load(Ordering::Acquire)) + } +} + +impl Drop for AllocationWorkers { + fn drop(&mut self) { + self.stop.store(true, Ordering::Release); + self.start.wait(); + for thread in self.threads.drain(..) { + thread.join().expect("allocator benchmark worker panicked"); + } + } +} + +fn allocator_benches(c: &mut Criterion) { + let mut group = c.benchmark_group("runtime/allocator"); + group.throughput(Throughput::Elements(ALLOCATION_JOBS as u64)); + group.bench_function("job_mix_single", |b| { + let mut seed = 0usize; + b.iter(|| { + seed = seed.wrapping_add(1); + allocation_job_batch(black_box(seed)) + }); + }); + + let workers = std::thread::available_parallelism().map_or(4, |count| count.get()) + .saturating_sub(1).clamp(2, 8); + let pool = AllocationWorkers::new(workers); + group.throughput(Throughput::Elements((ALLOCATION_JOBS * workers) as u64)); + group.bench_function(&format!("job_mix_parallel_{workers}"), |b| b.iter(|| pool.run())); + group.finish(); +} + fn utility_benches(c: &mut Criterion) { let mut group = c.benchmark_group("runtime/util"); for (name, pattern, value) in [ @@ -201,5 +306,5 @@ fn vfs_benches(c: &mut Criterion) { } fn main() { - support::run(&[utility_benches, manifest_and_config_benches, vfs_benches]); + support::run(&[utility_benches, manifest_and_config_benches, vfs_benches, allocator_benches]); } From e76454bbbef7cceac02d431294f5bd239da1eb1b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:36:04 -0800 Subject: [PATCH 260/265] Tests: seed resubmit lifetime identity The resubmit fixture manually published LastSubmit without first capturing the exact list address lifetime that note_resubmits requires. Exercise the real begin-submit reservation path before publishing the synthetic incomplete submit so the Windows test checks the detector rather than a stale fixture. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 58c93bb7f6..49614531ff 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -2438,6 +2438,9 @@ mod tests { let (alloc, list) = (ids.as_mut_ptr() as usize, ids.as_mut_ptr() as usize + 1); let queue = 0x10usize as *mut c_void; created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + // A real first submission captures the list's exact address lifetime before it + // publishes LastSubmit. Seed that identity before constructing the synthetic submit. + drop(begin_submit(&[list as *mut c_void]).unwrap()); { let mut g = STATE.lock().unwrap(); let s = g.as_mut().unwrap(); From a134a5fb5263a05dd8d9bb31bcea23c1b6501976 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 10:12:46 -0700 Subject: [PATCH 261/265] Recompiler: use larger compact tables on every GPU Use the 12,288-word compact table cap for every GPU now that nested compact dispatch is the default. The old 8,192-word wave64 gate selected the much larger plain form and left its CPU size-comparison test obsolete; the existing late-entry GPU test retains coverage above the old cap. Preserve the branch's automatic atomic-candidate policy while removing the adapter-dependent translation API. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/compact.rs | 8 ++--- crates/xcl/src/gpu/dxil/compact_tests.rs | 44 +++++++----------------- crates/xcl/src/gpu/dxil/kernel.rs | 28 ++++++--------- crates/xcl/src/gpu/recomp/pso.rs | 2 +- 4 files changed, 27 insertions(+), 55 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index b84298be5e..c8bfab774b 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -22,9 +22,7 @@ pub struct Plan { } /// Most 32-bit words of tables a program may need to take the form by itself. -pub const TABLE_WORDS: usize = 8192; -/// `TABLE_WORDS` on a GPU that runs only 32-lane waves. -pub const TABLE_WORDS_WAVE32: usize = 12288; +const MAX_TABLE_WORDS: usize = 12288; impl Plan { /// Bits of a table entry: the class, and the taken successor or the index of the pair of offsets. @@ -48,11 +46,11 @@ pub(super) fn atomic_candidate(cfg: &Cfg) -> bool { }) } -pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool, tables: usize) -> Option<Plan> { +pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option<Plan> { let large = large(cfg); if !large && !(split_compute && atomic_candidate(cfg)) { return None; } let p = plan(cfg, lw)?; - if p.words() > tables { return None; } + if p.words() > MAX_TABLE_WORDS { return None; } let insts = |n: usize| cfg.blocks[p.order[n]].insts.len(); let all: usize = (0..p.order.len()).map(insts).sum(); let once: usize = p.rep.iter().map(|&n| insts(n)).sum(); diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index e0bb2e8935..86d41bfd68 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -181,7 +181,16 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() { assert_ne!(p.class[0], p.class[2]); } -fn two_segments(copies: usize) -> Vec<u8> { +#[test] +fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { + if compact_mode().is_some() { + return; + } + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + const COPIES: usize = 8192; let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); let mut code = Vec::new(); code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 2)])); @@ -189,48 +198,21 @@ fn two_segments(copies: usize) -> Vec<u8> { code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", r), ("SRC0", 256 + r)])); } for marker in [3, 4] { - for k in 0..copies { + for k in 0..COPIES { code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 1)])); code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 256), ("VSRC1", 1)])); - let offset = (copies - 1 - k) * 3 + 1; + let offset = (COPIES - 1 - k) * 3 + 1; assert!(offset <= i16::MAX as usize); code.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", offset as u64)])); } code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", marker), ("SSRC0", 129)])); } code.extend(i("S_ENDPGM", "ENC_SOPP", &[])); - code -} - -#[test] -fn a_gpu_with_64_lane_waves_keeps_the_first_table_limit() { - if compact_mode().is_some() { - return; - } - let code = two_segments(8192); - let o = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; - let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 }; - let size = |wave32_only| super::kernel::translate_compute_on(&code, o, &cs, wave32_only).unwrap().dxil.len(); - let (compact, plain) = (size(true), size(false)); - assert!(compact * 20 < plain, "{compact} B on a GPU with 32-lane waves only, {plain} B on one with 64-lane waves"); -} - -#[test] -fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { - if compact_mode().is_some() { - return; - } - match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { - (Ok(_), Ok(true), Ok(_)) => {} - (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), - } - const COPIES: usize = 8192; - let code = two_segments(COPIES); let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; let cfg = super::cfg::Cfg::build(&code).unwrap(); let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); - let p = super::compact::automatic_plan(&cfg, &lw, false, super::compact::TABLE_WORDS_WAVE32).unwrap(); + let p = super::compact::automatic_plan(&cfg, &lw, false).unwrap(); assert!(p.inline && p.words() > 8192 && p.words() <= 12288); let k = translate_full(&code, o).unwrap(); for initial in [0u32, u32::MAX - 1, 0u32.wrapping_sub(COPIES as u32), 0u32.wrapping_sub((2 * COPIES) as u32), 0u32.wrapping_sub(COPIES as u32 + 1)] { diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index b03c024799..71a472d7db 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -91,39 +91,39 @@ pub fn compact_nest_tag() -> Option<String> { /// `translate_full` in the compact form (`compact = true`) or the plain one. #[cfg(test)] pub fn translate_full_as(code: &[u8], o: KernelOptions, compact: bool) -> Result<Kernel, String> { - translate_entry(code, o, Entry::Kernel, Some(compact), None, super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, Some(compact), None) } /// `translate_full` in the compact form with an explicit dispatch nesting policy. #[cfg(test)] pub fn translate_full_nested(code: &[u8], o: KernelOptions, nest: super::compact::Nest) -> Result<Kernel, String> { - translate_entry(code, o, Entry::Kernel, Some(true), Some(nest), super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, Some(true), Some(nest)) } pub fn translate_full(code: &[u8], o: KernelOptions) -> Result<Kernel, String> { - translate_entry(code, o, Entry::Kernel, compact_mode(), None, super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, compact_mode(), None) } /// A mesh-mode (NGG) program: the first pass that writes one record per group into /// `res` (the recompiler's `Mode::Mesh`; the pass-through mesh shader draws them). pub fn translate_mesh(code: &[u8], o: KernelOptions, ms: &MsInterface) -> Result<Kernel, String> { - translate_entry(code, o, Entry::Mesh(ms.clone()), None, None, 0) + translate_entry(code, o, Entry::Mesh(ms.clone()), None, None) } /// A vertex shader (the recompiler's `Mode::Vertex`; wave-size independent). pub fn translate_vertex(code: &[u8], o: KernelOptions, vs: &VsInterface) -> Result<Kernel, String> { - translate_entry(code, o, Entry::Vertex(vs.clone()), None, None, 0) + translate_entry(code, o, Entry::Vertex(vs.clone()), None, None) } /// A pixel shader (the recompiler's `Mode::Pixel`; wave-size independent). pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Result<Kernel, String> { - translate_entry(code, o, Entry::Pixel(ps.clone()), None, None, 0) + translate_entry(code, o, Entry::Pixel(ps.clone()), None, None) } /// A geometry-mode (ES+GS) program: the compute pass that writes one mesh record per /// group of 21 triangles into `res` (the recompiler's `Mode::Geometry`). Always wave64. pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Result<Kernel, String> { - translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0) + translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None) } /// Whether `entry` uses the measured, one-path heap-window read form. Graphics, mesh and @@ -160,13 +160,7 @@ pub enum Entry { /// A compute-mode program (the CS ABI of `cs`). pub fn translate_compute(code: &[u8], o: KernelOptions, cs: &CsInterface) -> Result<Kernel, String> { - translate_compute_on(code, o, cs, true) -} - -/// `translate_compute` for a GPU: one that runs only 32-lane waves takes larger compact tables. -pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wave32_only: bool) -> Result<Kernel, String> { - let tables = if wave32_only { super::compact::TABLE_WORDS_WAVE32 } else { super::compact::TABLE_WORDS }; - translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables) + translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None) } fn translate_entry( @@ -175,7 +169,6 @@ fn translate_entry( entry: Entry, compact: Option<bool>, nest: Option<super::compact::Nest>, - tables: usize, ) -> Result<Kernel, String> { // SSA construction recurses along the CFG (one level per guarded memory access between // a register's definition and its use): a thread with a large stack for big programs @@ -188,7 +181,7 @@ fn translate_entry( .spawn(move || { #[cfg(test)] super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold)); - translate_on_this_thread(&code, o, entry, compact, nest, tables) + translate_on_this_thread(&code, o, entry, compact, nest) }) .map_err(|e| format!("translator thread: {e}"))? .join() @@ -219,7 +212,6 @@ fn translate_on_this_thread( entry: Entry, compact: Option<bool>, nest: Option<super::compact::Nest>, - tables: usize, ) -> Result<Kernel, String> { let geo = match &entry { Entry::Geometry(g) => Some(g.clone()), @@ -309,7 +301,7 @@ fn translate_on_this_thread( _ if !compute && !kernel => None, Some(false) => None, Some(true) => super::compact::plan(&cfg, &lw), - None => super::compact::automatic_plan(&cfg, &lw, compute && split, tables), + None => super::compact::automatic_plan(&cfg, &lw, compute && split), }; if let Some(p) = &plan { crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len()); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index acc5ef06b2..abe3728260 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1094,7 +1094,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } } } - let k = crate::gpu::dxil::kernel::translate_compute_on(code, o, &cs, split_wave64)?; + let k = crate::gpu::dxil::kernel::translate_compute(code, o, &cs)?; dump_direct(blob, &k.dxil); Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) } From f3566e06da4c75ba610c107bb63c3ec3cc864f67 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:43:39 -0800 Subject: [PATCH 262/265] Tests: bound concurrent direct-DXIL translations Each translation already owns a 256 MiB-stack worker. Keep two translations concurrent to exercise separate thread-local and hash-map state, but remove redundant outer 64 MiB stacks and avoid crowding the other direct-DXIL tests in the four-thread suite. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/robustness_tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/dxil/robustness_tests.rs b/crates/xcl/src/gpu/dxil/robustness_tests.rs index 46a06c63d4..00b1b45aeb 100644 --- a/crates/xcl/src/gpu/dxil/robustness_tests.rs +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -87,7 +87,10 @@ fn translation_is_byte_identical_across_runs_and_threads() { for _ in 0..3 { assert!(translate_all() == first, "a second translation differs"); } - let threads: Vec<_> = (0..4).map(|_| std::thread::Builder::new().stack_size(64 << 20).spawn(translate_all).unwrap()).collect(); + // Every translate already runs on its own 256 MiB-stack worker. Keep genuine concurrent + // translator coverage without adding four redundant 64 MiB outer stacks or crowding the + // other direct-DXIL tests which the harness runs in parallel. + let threads: Vec<_> = (0..2).map(|_| std::thread::spawn(translate_all)).collect(); for t in threads { assert!(t.join().unwrap() == first, "a translation on another thread differs"); } From cd435a98594e1cd1c60c1c9647746527ee1b0b46 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:48:47 -0800 Subject: [PATCH 263/265] Scripts: show Windows test failures before abort Run the no-GPU CI suite without output capture so a later native fast-fail cannot hide earlier Rust assertion or translator-spawn diagnostics. Assisted-by: Codex (GPT-5.6-sol) --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc905cb1bc..4ceaa9d97f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,4 +51,4 @@ jobs: - name: Build and test shell: pwsh - run: ./scripts/test.ps1 --skip test_title_runs_and_game_folder_is_untouched + run: ./scripts/test.ps1 --nocapture --skip test_title_runs_and_game_folder_is_untouched From 7cd41d2856f6fec5cafab8266476df28b5b0e673 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 06:28:00 -0500 Subject: [PATCH 264/265] Recompiler: leave unsafe group barriers to HLSL Reject direct-DXIL compute and mesh programs whose group barrier spans multiple hardware waves. The direct barrier waits for waves the console may allow to leave or bypass it; the HLSL fallback already uses the safe counted barrier. Keep the coherence test on a one-wave group so it continues to test handle properties rather than the fallback boundary. Adapted from upstream commit fb55e49e. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/kernel.rs | 5 ++++ crates/xcl/src/gpu/dxil/lower.rs | 15 +++++++++++ crates/xcl/src/gpu/dxil/robustness_tests.rs | 28 +++++++++++++++++++++ crates/xcl/src/gpu/recomp/emit.rs | 8 +++++- crates/xcl/src/gpu/recomp/tests.rs | 19 +++++++++++--- 5 files changed, 71 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 71a472d7db..8212d12948 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -557,6 +557,7 @@ impl Lw { xs: None, xw: None, xc: None, + barrier_waves: None, waves: 1, cw: z, xn: z, @@ -615,6 +616,10 @@ impl Lw { if let (Some(t), true) = (group_threads, split) { lw.waves = t.div_ceil(64).max(1); } + if let (Some(t), Entry::Compute(_) | Entry::Mesh(_)) = (group_threads, entry) { + let hw_lanes = if split || !o.wave64 { 32 } else { 64 }; + lw.barrier_waves = Some(t.div_ceil(hw_lanes).max(1)); + } if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(insts, kernel); } diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 14754f7aa7..f38769dfd0 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -228,6 +228,9 @@ pub struct Lw { pub xw: Option<(super::ops::GroupShared, u32)>, /// arrival counters of the spin exchange (two per console wave) pub xc: Option<(super::ops::GroupShared, u32)>, + /// hardware waves of a compute or mesh thread group (None: another kind of entry), as the + /// HLSL emitter's `compute_or_mesh_hw_waves` + pub barrier_waves: Option<u32>, /// console waves per group, this thread's console wave and its partner half's lanes pub waves: u32, pub cw: Value, @@ -1018,6 +1021,18 @@ impl Lw { fn sopp(&mut self, d: &Decoded, name: &str) -> LResult<()> { match name { "s_barrier" => { + // A compute or mesh group of several hardware waves: this barrier waits for + // every one of them at a barrier, and a console wave that has left – s_endpgm + // behind a branch around the barrier, the loop budget – or that ran one barrier + // fewer never arrives. On the console the waves left go on; on NVIDIA they wait + // for ever and the GPU hangs (`recomp::emit::PRELUDE_SAFE_BARRIER`). A retail + // title's mesh programs all have it: the first wave of a group whose vertex or + // primitive count is 0 runs a barrier the other waves branch around, then the + // one they all run. The HLSL path counts the waves still there + // (`xcl_s_barrier`): such a program is left to it. + if self.barrier_waves.is_some_and(|w| w > 1) && crate::gpu::recomp::emit::safe_barrier_wanted() { + return err(d, "s_barrier in a group of several hardware waves"); + } self.s.barrier(super::ops::barrier::GROUP_SYNC); Ok(()) } diff --git a/crates/xcl/src/gpu/dxil/robustness_tests.rs b/crates/xcl/src/gpu/dxil/robustness_tests.rs index 00b1b45aeb..9bd172ef70 100644 --- a/crates/xcl/src/gpu/dxil/robustness_tests.rs +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -96,6 +96,34 @@ fn translation_is_byte_identical_across_runs_and_threads() { } } +/// A group barrier in a compute group of several hardware waves is not translated here: the +/// plain barrier waits for waves that have left (the GPU hangs on NVIDIA), and only the HLSL +/// path has the barrier that counts the waves still there. +#[test] +fn a_group_barrier_of_several_hardware_waves_is_left_to_the_hlsl_path() { + let code = prog(&[("S_BARRIER", "ENC_SOPP", &[], None)]); + let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let cs = |threads| CsInterface { threads, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + // 16 x 16 threads: 8 hardware waves in the split form, 4 native 64-lane ones, 8 of a + // 32-lane program; and the two 32-lane halves of one console wave + for (wave64, split, threads) in [(true, true, [16, 16, 1]), (true, false, [16, 16, 1]), (false, false, [16, 16, 1]), (true, true, [64, 1, 1]), (false, false, [64, 1, 1])] { + let e = kernel::translate_compute(&code, o(wave64, split), &cs(threads)).err().unwrap_or_else(|| panic!("translated: wave64 {wave64}, split {split}, {threads:?}")); + assert!(e.contains("s_barrier in a group of several hardware waves"), "{e}"); + } + // one hardware wave has nobody to wait for: translated as before + kernel::translate_compute(&code, o(true, false), &cs([64, 1, 1])).expect("one 64-lane wave"); + kernel::translate_compute(&code, o(false, false), &cs([32, 1, 1])).expect("one 32-lane wave"); + // (the kernel form of the tests is no thread group of a title's: its barrier stays) + kernel::translate(&code, o(true, true)).expect("kernel"); + // a mesh program's compute pass: two console waves a group, as a retail title's + let ms = |threads| crate::gpu::recomp::MsInterface { outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], threads, max_vertices: 64, max_primitives: 64 }; + for split in [true, false] { + let e = kernel::translate_mesh(&code, o(true, split), &ms(128)).err().unwrap_or_else(|| panic!("a mesh pass translated (split {split})")); + assert!(e.contains("s_barrier in a group of several hardware waves"), "{e}"); + } + kernel::translate_mesh(&code, o(true, false), &ms(64)).expect("a mesh pass of one 64-lane wave"); +} + // ---- builder misuse: recorded as the first error, finish fails instead of panicking use super::container::Stage; diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index a99bb5a715..b551dfd7cb 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -695,7 +695,7 @@ impl Em { self.has_s_barrier = has_s_barrier; self.safe_barrier = has_s_barrier && self.compute_or_mesh_hw_waves().is_some_and(|w| w > 1) - && std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0"); + && safe_barrier_wanted(); } pub fn take(&mut self) -> String { @@ -6268,6 +6268,12 @@ uint2 xcl_x_ballot_local(bool b) { uint xcl_x_rla_half(uint v, uint l) { return WaveReadLaneAt(v, l & 31u); } "#; +/// Whether a multi-warp Compute / Mesh `s_barrier` gets the early-exit-safe barrier +/// (`XCL_SAFE_BARRIER=0`: the plain group barrier, in both translators). +pub(crate) fn safe_barrier_wanted() -> bool { + std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0") +} + /// Early-exit-safe, bounded workgroup barrier for multi-warp Compute / Mesh `s_barrier`. /// /// On RDNA2, `S_ENDPGM` decrements the CU's active wave count so remaining waves executing diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 79a95df537..747f1542f2 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -87,8 +87,18 @@ fn direct_or(code: &[u8], opt: &Options, hlsl: Vec<u8>) -> Vec<u8> { let o = KernelOptions { wave64: opt.wave64, split, mem_windows, sampler_base: opt.static_sampler_base }; match &opt.mode { Mode::Kernel => translate(code, o).unwrap_or_else(|e| panic!("direct DXIL: {e}")), - Mode::Compute(cs) => translate_compute(code, o, cs).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, - Mode::Mesh(ms) => crate::gpu::dxil::kernel::translate_mesh(code, o, ms).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, + // (a group barrier in a group of several hardware waves is left to the HLSL path, as + // the runtime's fallback does: `dxil::lower`'s s_barrier) + Mode::Compute(cs) => match translate_compute(code, o, cs) { + Ok(k) => k.dxil, + Err(e) if e.contains("s_barrier in a group of several hardware waves") => hlsl, + Err(e) => panic!("direct DXIL: {e}"), + }, + Mode::Mesh(ms) => match crate::gpu::dxil::kernel::translate_mesh(code, o, ms) { + Ok(k) => k.dxil, + Err(e) if e.contains("s_barrier in a group of several hardware waves") => hlsl, + Err(e) => panic!("direct DXIL: {e}"), + }, Mode::Vertex(vs) => crate::gpu::dxil::kernel::translate_vertex(code, o, vs).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, Mode::Pixel(ps) => crate::gpu::dxil::kernel::translate_pixel(code, o, ps).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, _ => hlsl, @@ -9990,9 +10000,12 @@ fn compute_globallycoherent_only_when_needed() { // Direct DXIL backend: check the IsGloballyCoherent bit (0x4000) in annotateHandle properties // (RAW_BUFFER=11 | IsUAV=0x1000 = 4107 vs RAW_BUFFER=11 | IsUAV=0x1000 | IsGloballyCoherent=0x4000 = 20491). + // (the plain program in a group of one 32-lane wave: its s_barrier in a group of several + // hardware waves is left to the HLSL path) + let one_wave = super::CsInterface { threads: [32, 1, 1], ..cs.clone() }; for mw in [1u32, super::HEAP_WINDOWS | 2] { let o = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: mw, sampler_base: 0 }; - let plain_k = crate::gpu::dxil::kernel::translate_compute(&plain, o, &cs).unwrap(); + let plain_k = crate::gpu::dxil::kernel::translate_compute(&plain, o, &one_wave).unwrap(); let coh_k = crate::gpu::dxil::kernel::translate_compute(&coherent_cases[6].1, o, &cs).unwrap(); if super::dxc::location().is_ok() { let plain_dis = crate::gpu::dxil::validate::disassemble(&plain_k.dxil).unwrap(); From e9211ff44ec580a0ae2e10ab5a4f45a4f7995751 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:54:50 -0800 Subject: [PATCH 265/265] Recompiler: keep backedge values behind loop phis Trivial-phi elimination could replace a loop-header phi with its sole distinct backedge value. That rewrote header uses to an instruction serialized later in the loop and tripped the direct-DXIL well-formed-use invariant after CFG simplification. Only eliminate a phi when its replacement is already available before it in function order. Cover the self/backedge loop form that the branchy compute translation exposes. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/dxil/module/opt.rs | 78 +++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index ebe4338a6d..14dbbca01f 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -646,6 +646,14 @@ impl Module { } let mut repl: Vec<Option<Value>> = vec![None; self.insts.len()]; + let mut inst_at = vec![usize::MAX; self.insts.len()]; + let mut at = 0; + for &b in &order { + for &i in &self.blocks[b as usize] { + inst_at[i as usize] = at; + at += 1; + } + } // trivial phis (all incoming values the phi itself or one value), to a fixed point while !skip("phi") { @@ -671,7 +679,14 @@ impl Module { } same = Some(v); } - if let (true, Some(v)) = (trivial, same) { + // A phi may refer to a value produced on a backedge. Replacing the phi + // with that value would make uses near the block header precede its + // definition in the serialized function. + let available = same.is_some_and(|v| match v { + Value::Inst(j) => inst_at[j as usize] < inst_at[i], + _ => true, + }); + if let (true, true, Some(v)) = (trivial, available, same) { repl[i] = Some(v); changed = true; } @@ -775,7 +790,11 @@ impl Module { } same = Some(v); } - if let (true, Some(v)) = (trivial, same) { + let available = same.is_some_and(|v| match v { + Value::Inst(j) => inst_at[j as usize] < inst_at[i], + _ => true, + }); + if let (true, true, Some(v)) = (trivial, available, same) { repl[i] = Some(v); changed = true; } @@ -831,6 +850,14 @@ impl Module { if !skip("merge") && self.simplify_cfg() { let order: Vec<u32> = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + inst_at.fill(usize::MAX); + let mut at = 0; + for &b in &order { + for &i in &self.blocks[b as usize] { + inst_at[i as usize] = at; + at += 1; + } + } let mut repl2: Vec<Option<Value>> = vec![None; self.insts.len()]; let mut phi_changed = false; while !skip("phi") { @@ -856,7 +883,11 @@ impl Module { } same = Some(v); } - if let (true, Some(v)) = (trivial, same) { + let available = same.is_some_and(|v| match v { + Value::Inst(j) => inst_at[j as usize] < inst_at[i], + _ => true, + }); + if let (true, true, Some(v)) = (trivial, available, same) { repl2[i] = Some(v); changed = true; phi_changed = true; @@ -1567,6 +1598,47 @@ mod tests { assert!(!inc.iter().any(|&(_, b)| b == latch), "merged latch must not remain in header phi"); } + #[test] + fn trivial_loop_phi_keeps_backedge_definition_after_header_uses() { + let mut m = Module::new(); + m.define_entry("main"); + let entry = m.entry_block(); + let header = m.new_block(); + let latch = m.new_block(); + let exit = m.new_block(); + + let void = m.void(); + let i32t = m.i32(); + let sink_ty = m.func_ty(void, &[i32t]); + let sink = m.declare("dx.op.storeOutput.i32", sink_ty, FnAttrs::NoUnwind); + + m.set_block(entry); + let one = m.i32c(1); + let limit = m.i32c(10); + m.br(header); + + m.set_block(header); + let iv = m.phi(i32t); + m.add_incoming(iv, iv, entry); + m.br(latch); + + m.set_block(latch); + let next = m.bin(BinOp::Add, iv, one); + m.add_incoming(iv, next, latch); + let cont = m.cmp(Pred::ULt, next, limit); + m.cond_br(cont, header, exit); + + m.set_block(exit); + m.call(sink, &[next]); + m.ret(); + + m.optimize(); + let order: Vec<u32> = m.block_layout().0.into_iter().map(|b| b as u32).collect(); + assert!(m.uses_well_formed(&order)); + let Value::Inst(iv_i) = iv else { unreachable!() }; + assert!(m.blocks.iter().any(|b| b.contains(&iv_i)), "the backedge value cannot replace the header phi"); + } + #[test] fn simplify_cfg_does_not_inflate_multi_pred_phi_trampoline() { let mut m = Module::new();