use super::*; struct Copier { allocator: ID3D12CommandAllocator, list: ID3D12GraphicsCommandList, } static SPARE: Mutex> = Mutex::new(Vec::new()); struct InUse(Option); unsafe impl Send for Copier {} impl Drop for InUse { fn drop(&mut self) { if let Some(copier) = self.0.take() { let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); if spare.len() < 64 { spare.push(copier); } } } } type Copy = (ID3D12Resource, u64, ID3D12Resource, u64, u64, usize); pub(super) fn send(host: &Host, first: &HostList) -> Option { if !crate::arena::mirror::on() && !crate::arena::mirror::pool_on() { return None; } crate::arena::mirror::sweep(); let taken = crate::arena::mirror::take_dirty(); crate::arena::mirror::map_pending(&host.device, host.queue()); if taken.is_empty() { return None; } let ranges = taken; let started = std::time::Instant::now(); let mut copies: Vec = Vec::new(); let mut bytes = 0u64; 'ranges: for (i, (at, len, window, offset)) in ranges.iter().enumerate() { let (at, len, offset) = (*at, *len, *offset); let mut done = 0; while done < len { let n = (len - done).min(crate::arena::mirror::PIECE); let Some((buffer, from, data)) = first.scratch_at(n as u64) else { let mut rest = vec![(at + done, len - done)]; rest.extend(ranges[i + 1..].iter().map(|r| (r.0, r.1))); crate::arena::mirror::again(&rest); break 'ranges; }; crate::host::copy_mapped(data, (at + done) as *const u8, n, false); copies.push((buffer, from, window.clone(), offset + done as u64, n as u64, at + done)); done += n; bytes += n as u64; } } crate::arena::mirror::sent(copies.len() as u64, bytes, started.elapsed().as_micros() as u64); if copies.is_empty() { return None; } let Some(list) = record(host, &copies) else { let ranges: Vec<(usize, usize)> = copies.iter().map(|c| (c.5, c.4 as usize)).collect(); crate::arena::mirror::again(&ranges); return None; }; for c in &copies { crate::cardpool::card_written(c.5 as u64, c.4); } Some(list) } fn record(host: &Host, copies: &[Copy]) -> Option { let taken = SPARE.lock().unwrap_or_else(|e| e.into_inner()).pop(); let copier = match taken { Some(copier) => copier, None => { let made: windows::core::Result = unsafe { (|| { let allocator: ID3D12CommandAllocator = host.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; let list: ID3D12GraphicsCommandList = host.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; list.Close()?; Ok(Copier { allocator, list }) })() }; match made { Ok(copier) => { name(&copier.list, || "copies into the arena's mirror".into()); copier } Err(e) => { tracing::warn!(%e, "arena mirror: CreateCommandAllocator/CreateCommandList failed; its copies wait for the next submission"); return None; } } } }; let recorded = unsafe { copier.allocator.Reset().map_err(|e| ("ID3D12CommandAllocator::Reset", e)).and_then(|()| { copier.list.Reset(&copier.allocator, None).map_err(|e| ("ID3D12GraphicsCommandList::Reset", e))?; let mut windows: Vec<&ID3D12Resource> = Vec::new(); for (from, at, window, to, len, _) in copies { copier.list.CopyBufferRegion(window, *to, from, *at, *len); if !windows.iter().any(|w| w.as_raw() == window.as_raw()) { windows.push(window); } } let back: Vec = windows.iter().map(|w| transition(w, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)).collect(); crate::barstat::rb(&copier.list, &back); copier.list.Close().map_err(|e| ("ID3D12GraphicsCommandList::Close (an invalid copy or barrier)", e)) }) }; if let Err((call, e)) = recorded { tracing::error!(%e, call, copies = copies.len(), "arena mirror: its copies' list did not record; they wait for the next submission"); return None; } let list = copier.list.cast().ok(); retire(InUse(Some(copier))); list } pub(super) fn pool_back(host: &Host, runs: &[&HostList], number: u64) -> (Option, Option) { use crate::arena::mirror; if !mirror::pool_on() { return (None, None); } let mut ranges = mirror::take_pool_writes(); for list in runs { ranges.extend(list.pool_writes()); } let coherent = mirror::coherent_on(); if ranges.is_empty() && !coherent { return (None, None); } if !ranges.is_empty() { mirror::shaders_will_write(&ranges); } if !mirror::back_on() && !coherent { return (None, None); } let mut pull = None; if coherent { mirror::coherent_declared(number, &ranges); if !mirror::coherent_copies_back() { return (None, None); } ranges = mirror::coherent_clip(ranges); pull = mirror::pull_due().and_then(|plan| match pull_buffer(host) { Some(data) => Some((plan, data)), None => { mirror::pull_dropped(); None } }); } let both = if ranges.is_empty() { None } else { copy_back(host, ranges, number, &mut pull) }; match (both, pull) { (Some((first, last)), _) => (Some(first), Some(last)), (None, Some((plan, (buffer, data)))) => { let last = record_with(host, |list| { unsafe { list.ResourceBarrier(&[uav_all()]); record_pull(list, &buffer, &plan); } }); match last { Some(last) => { mirror::pull_sent(number, data, plan); (None, Some(last)) } None => { mirror::pull_dropped(); (None, None) } } } (None, None) => (None, None), } } unsafe fn record_pull(list: &ID3D12GraphicsCommandList, buffer: &ID3D12Resource, plan: &crate::arena::mirror::PullPlan) { let mut at = 0u64; for (_, len, window, offset) in &plan.parts { unsafe { list.CopyBufferRegion(buffer, at, window, *offset, *len as u64) }; at += *len as u64; } } type PullWith = Option<(crate::arena::mirror::PullPlan, (ID3D12Resource, usize))>; fn copy_back(host: &Host, ranges: Vec<(usize, usize)>, number: u64, pull: &mut PullWith) -> Option<(ID3D12CommandList, ID3D12CommandList)> { let t0 = std::time::Instant::now(); let plan = crate::arena::mirror::back_plan(ranges); crate::arena::mirror::timed(2, t0); crate::arena::mirror::counted(0, plan.len() as u64); let total: u64 = plan.iter().map(|p| p.1 as u64).sum(); if total == 0 { return None; } let Some(pass) = diff_pass(host) else { crate::arena::mirror::refused(crate::arena::mirror::Refused::NoUpload); return None; }; let blocks = total / BLOCK; let cap = blocks.min(MAX_ENTRIES); let t0 = std::time::Instant::now(); let scratch = Scratch::take(host, total, 16 + cap * ENTRY); crate::arena::mirror::timed(3, t0); let t0 = std::time::Instant::now(); let Some(scratch) = scratch else { crate::arena::mirror::refused(crate::arena::mirror::Refused::NoUpload); return None; }; unsafe { (scratch.out_data as *mut u32).write_volatile(0) }; let mut items = Vec::with_capacity(plan.len()); let mut at = 0u64; let mut parts = Vec::with_capacity(plan.len()); for (title, len, window, offset, gpu) in plan { items.push((title, len, at as usize)); parts.push((window, offset, gpu, at, len as u64)); at += len as u64; } let copy = &scratch.copy; let out = &scratch.out; let first = record_with(host, |list| { unsafe { list.ResourceBarrier(&[transition(copy, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); for (window, offset, _, at, len) in &parts { list.CopyBufferRegion(copy, *at, window, *offset, *len); } list.ResourceBarrier(&[transition(copy, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); } })?; let verify = crate::arena::mirror::verify_due().and_then(|plan| match verify_buffer(host) { Some(buffer) => Some((plan, buffer)), None => { crate::arena::mirror::verify_dropped(); None } }); let copy_gpu = scratch.copy_gpu; let last = record_with(host, |list| { unsafe { list.ResourceBarrier(&[uav_all(), transition(out, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); list.SetComputeRootSignature(&pass.root); list.SetPipelineState(&pass.pso); list.SetComputeRootUnorderedAccessView(3, scratch.out_gpu); for (_, _, gpu, at, len) in &parts { let blocks = len / BLOCK; list.SetComputeRootShaderResourceView(1, *gpu); list.SetComputeRootShaderResourceView(2, copy_gpu + at); let mut first = 0u64; while first < blocks { let n = (blocks - first).min(65535); let constants = [first as u32, blocks as u32, cap as u32, (at / BLOCK) as u32]; list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); list.Dispatch(n as u32, 1, 1); first += n; } } list.ResourceBarrier(&[transition(out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON)]); if let Some((plan, (buffer, _))) = &verify { let mut at = 0u64; for (_, len, window, offset) in plan { list.CopyBufferRegion(buffer, at, window, *offset, *len as u64); at += *len as u64; } } if let Some((plan, (buffer, _))) = pull.as_ref() { record_pull(list, buffer, plan); } } }); let Some(last) = last else { if verify.is_some() { crate::arena::mirror::verify_dropped(); } return None; }; if let Some((plan, (_, data))) = verify { let mut at = 0usize; let runs = plan .into_iter() .map(|(title, len, _, _)| { at += len; (title, len, at - len) }) .collect(); crate::arena::mirror::verify_sent(number, data, runs); } if let Some((plan, (_, data))) = pull.take() { crate::arena::mirror::pull_sent(number, data, plan); } crate::arena::mirror::timed(4, t0); let data = scratch.out_data; crate::arena::mirror::back_sent(number, Box::new(scratch), data, cap as u32, items); Some((first, last)) } const BLOCK: u64 = crate::arena::mirror::BACK_BLOCK as u64; const ENTRY: u64 = 16 + BLOCK; const MAX_ENTRIES: u64 = 65536; const DIFF: &str = r#" #define RS "RootConstants(num32BitConstants=4, b0), SRV(t0), SRV(t1), UAV(u0)" cbuffer Span : register(b0) { uint first; uint blocks; uint cap; uint base; }; ByteAddressBuffer now : register(t0); ByteAddressBuffer was : register(t1); RWByteAddressBuffer packed : register(u0); groupshared uint lo; groupshared uint hi; groupshared uint slot; [RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_GroupID, uint t : SV_GroupIndex) { uint block = first + id.x; if (t == 0u) { lo = 0u; hi = 0u; slot = 0xFFFFFFFFu; } GroupMemoryBarrierWithGroupSync(); uint at = block * 256u + t * 4u; uint a = 0u; if (block < blocks) { a = now.Load(at); if (a != was.Load(at)) { if (t < 32u) { InterlockedOr(lo, 1u << t); } else { InterlockedOr(hi, 1u << (t - 32u)); } } } GroupMemoryBarrierWithGroupSync(); if (t == 0u && (lo | hi) != 0u) { uint s; packed.InterlockedAdd(0, 1u, s); slot = s; } GroupMemoryBarrierWithGroupSync(); if (slot >= cap) { return; } uint e = 16u + slot * 272u; if (t == 0u) { packed.Store3(e, uint3(base + block, lo, hi)); } packed.Store(e + 16u + t * 4u, a); } "#; struct Pass { root: ID3D12RootSignature, pso: ID3D12PipelineState, } unsafe impl Send for Pass {} unsafe impl Sync for Pass {} fn diff_pass(host: &Host) -> Option<&'static Pass> { static PASS: OnceLock> = OnceLock::new(); PASS.get_or_init(|| { let made = (|| -> windows::core::Result { let code = crate::hlsl::compile_compute("pool mirror compare", DIFF)?; unsafe { let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code)?; let pso: ID3D12PipelineState = host.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr().cast(), BytecodeLength: code.len() }, ..Default::default() })?; Ok(Pass { root, pso }) } })(); made.map_err(|e| tracing::warn!(%e, "pool mirror: its compare pass could not be made; what shaders write there is not landed")).ok() }) .as_ref() } struct Scratch { copy: ID3D12Resource, copy_size: u64, copy_gpu: u64, out: ID3D12Resource, out_size: u64, out_data: usize, out_gpu: u64, } unsafe impl Send for Scratch {} static SCRATCH: Mutex<(Vec<(ID3D12Resource, u64)>, Vec<(ID3D12Resource, u64, usize)>)> = Mutex::new((Vec::new(), Vec::new())); impl Scratch { fn take(host: &Host, copy: u64, out: u64) -> Option { let (copy_size, out_size) = (copy.max(1 << 20).next_power_of_two(), out.max(1 << 20).next_power_of_two()); let (mut c, mut o) = (None, None); { let mut spare = SCRATCH.lock().unwrap_or_else(|e| e.into_inner()); if let Some(i) = (0..spare.0.len()).filter(|&i| spare.0[i].1 >= copy && spare.0[i].1 <= copy_size * 4).min_by_key(|&i| spare.0[i].1) { c = Some(spare.0.swap_remove(i)); } if let Some(i) = (0..spare.1.len()).filter(|&i| spare.1[i].1 >= out && spare.1[i].1 <= out_size * 4).min_by_key(|&i| spare.1[i].1) { o = Some(spare.1.swap_remove(i)); } } let c = match c { Some(c) => c, None => { crate::arena::mirror::counted(1, copy_size); let made = host.uav_buffer_now(copy_size)?; name(&made, || "pool mirror compare copy".into()); (made, copy_size) } }; let o = match o { Some(o) => o, None => { crate::arena::mirror::counted(2, out_size); let (made, data) = host.shared_buffer_own(out_size)?; name(&made, || "pool mirror compare out".into()); (made, out_size, data as usize) } }; let (copy_gpu, out_gpu) = unsafe { (c.0.GetGPUVirtualAddress(), o.0.GetGPUVirtualAddress()) }; Some(Scratch { copy: c.0, copy_size: c.1, copy_gpu, out: o.0, out_size: o.1, out_data: o.2, out_gpu }) } } impl Drop for Scratch { fn drop(&mut self) { let mut spare = SCRATCH.lock().unwrap_or_else(|e| e.into_inner()); if spare.0.iter().map(|b| b.1).sum::() + self.copy_size <= 512 << 20 { spare.0.push((self.copy.clone(), self.copy_size)); } if spare.1.iter().map(|b| b.1).sum::() + self.out_size <= 256 << 20 { spare.1.push((self.out.clone(), self.out_size, self.out_data)); } } } fn transition(resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { 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: unsafe { std::mem::transmute_copy(resource) }, Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: before, StateAfter: after, }), }, } } fn uav_all() -> D3D12_RESOURCE_BARRIER { 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) }), }, } } fn record_with(host: &Host, fill: impl FnOnce(&ID3D12GraphicsCommandList)) -> Option { let taken = SPARE.lock().unwrap_or_else(|e| e.into_inner()).pop(); let copier = match taken { Some(copier) => copier, None => { let made: windows::core::Result = unsafe { (|| { let allocator: ID3D12CommandAllocator = host.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; let list: ID3D12GraphicsCommandList = host.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; list.Close()?; Ok(Copier { allocator, list }) })() }; match made { Ok(copier) => copier, Err(e) => { tracing::warn!(%e, "pool mirror: CreateCommandAllocator/CreateCommandList failed; its writes are not landed"); return None; } } } }; let recorded = unsafe { copier.allocator.Reset().map_err(|e| ("ID3D12CommandAllocator::Reset", e)).and_then(|()| { copier.list.Reset(&copier.allocator, None).map_err(|e| ("ID3D12GraphicsCommandList::Reset", e))?; fill(&copier.list); copier.list.Close().map_err(|e| ("ID3D12GraphicsCommandList::Close", e)) }) }; if let Err((call, e)) = recorded { tracing::error!(%e, call, "pool mirror: its list did not record; its writes are not landed"); return None; } let list = copier.list.cast().ok(); retire(InUse(Some(copier))); list } fn verify_buffer(host: &Host) -> Option<(ID3D12Resource, usize)> { struct Held(ID3D12Resource, usize); unsafe impl Send for Held {} unsafe impl Sync for Held {} static BUFFER: OnceLock> = OnceLock::new(); BUFFER .get_or_init(|| host.shared_buffer_own(crate::arena::mirror::VERIFY_BYTES as u64).map(|(b, d)| Held(b, d as usize))) .as_ref() .map(|h| (h.0.clone(), h.1)) } fn pull_buffer(host: &Host) -> Option<(ID3D12Resource, usize)> { struct Held(ID3D12Resource, usize); unsafe impl Send for Held {} unsafe impl Sync for Held {} static BUFFER: OnceLock> = OnceLock::new(); BUFFER .get_or_init(|| host.shared_buffer_own(crate::arena::mirror::PULL_BYTES as u64).map(|(b, d)| Held(b, d as usize))) .as_ref() .map(|h| (h.0.clone(), h.1)) }