diff --git a/README.md b/README.md index 4010879d7c..53e79748b1 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ The on/off switches below (`...=1`) are off when unset or set to `0`. | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | | `VICTORY_SKIP_PIPELINES=,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | | `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands; a device removal names the list it happened in and lists all its commands | -| `VICTORY_TRACE_SHADERS=,...` | with `VICTORY_D3D12_DRED`, every draw and dispatch of a listed shader logged with what it binds (user data, heap slots, root views and their first dwords; the first 500) | +| `VICTORY_TRACE_SHADERS=,...` | with `VICTORY_D3D12_DRED`, every draw and dispatch of a listed shader logged with what it binds (user data, heap slots, root views and their first dwords; the first 500, and all of them in listed capture frames); the records of its indirect executions are read back and logged in every frame (records with work, the first four, the frame) | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | | `VICTORY_PIPELINE_LOG=` | a line per title pipeline created (key, shaders, state), first used, and made or loaded (library name); `translate --cache --pipelines` writes the last kind too | | `VICTORY_PREBUILD_KEYS=` | `translate --cache --pipelines` makes nothing and lists each pack record's key, shaders and state (or why it is skipped) | diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 032306d817..71afedd9a2 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -57,8 +57,9 @@ pub fn run( // Before the import registry is first used: it holds the module only // when the host's FidelityFX serves. victory_hle::modules::fidelityfx::use_host_dir(cfg.fidelityfx_dir.as_deref()); - let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; - let prepared = victory_loader::prepare(&original)?; + let prepared = victory_loader::prepare( + &std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?, + )?; let hash = prepared.original_hash.to_hex(); let title_dir = exe.parent().unwrap_or(Path::new(".")); match victory_game::identify(&hash) { @@ -82,6 +83,8 @@ pub fn run( } victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); let image = victory_loader::load(&prepared, &images)?; + // Mapped: the patched bytes (the exe's size, 114 MB) are not needed. + drop(prepared); victory_hle::runtime::set_main_image(image.base()); victory_hle::runtime::set_image_path(image.base(), exe); println!( diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index cd56afdec0..5ac2893dce 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -434,6 +434,7 @@ pub(crate) fn read_indirect( count: Option<(&ID3D12Resource, u64)>, (kind, stride, max): (u32, u32, u32), name: String, + always: bool, ) { struct Readback(ID3D12Resource); // SAFETY: D3D12 objects are free-threaded. @@ -488,7 +489,8 @@ pub(crate) fn read_indirect( let counted = count.is_some(); list.defer_after(move || { // Recorded ahead: logged if the frame running it is listed. - if !listed(crate::queue::presented() + 1) { + let frame = crate::queue::presented() + 1; + if !always && !listed(frame) { return; } let mut data = std::ptr::null_mut(); @@ -513,7 +515,7 @@ pub(crate) fn read_indirect( let shown: Vec<&[u32]> = (0..records.min(4)).map(first).collect(); tracing::info!( target: "victory_gpu::trace", - "indirect kind {kind} max {max} count {n:?}: {busy} of {records} records with work, {total} in all; first {shown:?} {name}" + "indirect kind {kind} max {max} count {n:?}: {busy} of {records} records with work, {total} in all; first {shown:?} {name} frame {frame}" ); buffer.0.Unmap(0, None); }); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d34c610335..c524847188 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1705,12 +1705,17 @@ impl State { counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) }; - // A listed frame: what the records held (after the clamp). + // A listed frame, or any frame for a traced shader: what the records + // held (after the clamp). #[cfg(feature = "diagnostics")] - if crate::capture::dump_on() { - let count = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); - let name = crate::pipeline::shaders_of(pipeline); - crate::capture::read_indirect(list, (&args.buffer, args.offset(arguments)), count, (kind, stride, max), name); + { + let always = !crate::host::traced_shaders().is_empty() + && crate::host::is_traced(&crate::pipeline::shaders_of(pipeline)); + if always || crate::capture::dump_on() { + let count = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); + let name = crate::pipeline::shaders_of(pipeline); + crate::capture::read_indirect(list, (&args.buffer, args.offset(arguments)), count, (kind, stride, max), name, always); + } } crate::indirect::done(list, &args.buffer); if kind == DISPATCH { @@ -2022,6 +2027,128 @@ void main(uint3 id : SV_DispatchThreadID) { } } + /// Which pixels of a 64x64 host D32S8 `texture` (title texture `depth`) + /// pass an EQUAL depth test against a square (two triangles, as the + /// title's rectangles become) drawn over pixel `k - 1` (row by row) with + /// z = k times the title's 1/65535 (`0x37800080`), the depth + /// `VS_TiledLighting` gives draw k: entry `k - 1`. + fn equal_test_passes(depth: This, texture: &ID3D12Resource) -> Vec { + use windows::Win32::Graphics::Dxgi::Common::*; + const SOURCE: &str = r#" +#define RS "RootFlags(0)" +static const float2 CORNERS[6] = { float2(0, 0), float2(1, 0), float2(0, 1), float2(1, 0), float2(1, 1), float2(0, 1) }; +[RootSignature(RS)] +float4 vs(uint v : SV_VertexID) : SV_Position { + uint i = v / 6; + float2 p = float2(i % 64, i / 64) + CORNERS[v % 6]; + return float4(p.x / 32.0 - 1.0, 1.0 - p.y / 32.0, (float)(i + 1) * asfloat(0x37800080), 1.0); +} +uint ps() : SV_Target { return 1; } +"#; + let host = crate::host::host().unwrap(); + let blob = |entry: windows::core::PCSTR, target: windows::core::PCSTR| { + let mut code: Option = None; + // SAFETY: the source and names outlive the call. + unsafe { D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("equal"), None, None, entry, target, 0, 0, &mut code, None) }.unwrap(); + code.unwrap() + }; + let (vs, ps) = (blob(s!("vs"), s!("vs_5_1")), blob(s!("ps"), s!("ps_5_1"))); + // SAFETY: the blobs' own bytes. + let bytes = |b: &ID3DBlob| unsafe { D3D12_SHADER_BYTECODE { pShaderBytecode: b.GetBufferPointer(), BytecodeLength: b.GetBufferSize() } }; + // SAFETY: a compiled shader with its root signature inside. + let root: ID3D12RootSignature = unsafe { + host.device.CreateRootSignature(0, std::slice::from_raw_parts(vs.GetBufferPointer().cast::(), vs.GetBufferSize())) + } + .unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: borrowed for the call. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + VS: bytes(&vs), + PS: bytes(&ps), + SampleMask: u32::MAX, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + DSVFormat: DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.RTVFormats[0] = DXGI_FORMAT_R32_UINT; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = true.into(); + desc.DepthStencilState.DepthEnable = true.into(); + desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_EQUAL; + // SAFETY: a complete description. + let pso: ID3D12PipelineState = unsafe { host.device.CreateGraphicsPipelineState(&desc) }.unwrap(); + let target_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut target: Option = None; + // SAFETY: plain creation. + unsafe { + host.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut target) + } + .unwrap(); + let target = target.unwrap(); + let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0; + // SAFETY: outputs for one subresource. + unsafe { host.device.GetCopyableFootprints(&target_desc, 0, 1, 0, Some(&mut f), None, None, Some(&mut total)) }; + let (raw, data) = host.shared_buffer(total).unwrap(); + let list = host.new_list().unwrap(); + crate::list::ensure_state(&list, depth, 0x10); + let dsv = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let (rtv, dsv) = (host.rtv(&target, None), host.dsv(texture, Some(&dsv))); + // SAFETY: an open list; the target in the render target state, the + // depth texture in the depth write state; copies into our buffer. + unsafe { + let l = &list.list; + l.ClearRenderTargetView(rtv, &[0.0; 4], None); + l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); + l.RSSetViewports(&[D3D12_VIEWPORT { Width: 64.0, Height: 64.0, MaxDepth: 1.0, ..Default::default() }]); + l.RSSetScissorRects(&[windows::Win32::Foundation::RECT { right: 64, bottom: 64, ..Default::default() }]); + l.SetGraphicsRootSignature(&root); + l.SetPipelineState(&pso); + l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + l.DrawInstanced(64 * 64 * 6, 1, 0, 0); + l.ResourceBarrier(&[crate::host::transition(&target, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&raw), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&target), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); + } + list.close(); + host.execute(&[&list]); + (0..64 * 64) + .map(|i| { + // SAFETY: inside the mapped buffer, by the footprint. + unsafe { (data.add(f.Offset as usize + (i / 64) * f.Footprint.RowPitch as usize + (i % 64) * 4) as *const u32).read() == 1 } + }) + .collect() + } + /// A title buffer of `bytes` in memory of its own. fn buffer(bytes: u64) -> This { let desc: [u32; 14] = [1, 0, 0, 0, bytes as u32, (bytes >> 32) as u32, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0]; @@ -2300,11 +2427,11 @@ void main(uint3 id : SV_DispatchThreadID) { } /// A depth texture with stencil (the console's 16-bit depth, the - /// host's 24-bit) written through unordered views of its planes, then - /// read as depth and stencil: the 16-bit depth arrives in 24 bits as - /// the host converts the same value, the stencil as written. Rendered - /// as depth (a clear), then used through the unordered view: back in - /// 16 bits. + /// host's 32-bit float) written through unordered views of its planes, + /// then read as depth and stencil: the 16-bit depth arrives as the + /// float the title's shaders compute for it, the stencil as written, + /// and a draw at that depth passes an EQUAL test. Rendered as depth (a + /// clear), then used through the unordered view: back in 16 bits. #[test] fn a_depth_texture_written_through_unordered_views_reads_as_depth() { let Some(host) = crate::host::host() else { @@ -2391,7 +2518,8 @@ void main(uint3 id : SV_DispatchThreadID) { } list.close(); host.execute(&[&list]); - let d24 = |u: u32| u * 256 + (u * 255 + 32767) / 65535; + // The title's float for 16-bit value u (its 1/65535 is 0x37800080). + let float = |u: u32| (u as f32 * f32::from_bits(0x3780_0080)).to_bits(); for (x, y) in [(0usize, 0usize), (5, 0), (63, 2), (17, 40), (63, 63)] { let k = (1 + x + 64 * y) as u32; // SAFETY: inside the mapped buffers. @@ -2406,15 +2534,22 @@ void main(uint3 id : SV_DispatchThreadID) { raw_data.add(f[1].Offset as usize + y * f[1].Footprint.RowPitch as usize + x).read(), ) }; - assert_eq!(word & 0xff_ffff, d24(k), "24-bit depth at {x},{y}"); + assert_eq!(word, float(k), "depth at {x},{y}"); assert_eq!(u32::from(byte), ((x ^ y) & 0xff) as u32); } + // Tested EQUAL against a point at the depth the title's tiled + // lighting gives value k (k times its 1/65535), as the console's + // 16-bit depth passes it for every k. In 24-bit depth on the RX 6700 + // XT only k = 258 of 1..=4096 passed. + let passed = equal_test_passes(depth, ©.texture); + let failed: Vec = (1..=4096).filter(|&k| !passed[k as usize - 1]).collect(); + assert!(failed.is_empty(), "EQUAL fails at {failed:?}"); // Rendered as depth (a clear of both planes), then used through // the unordered view: copied to the twin, converted back. list.reset(); crate::list::ensure_state(&list, depth, 0x10); let dsv = D3D12_DEPTH_STENCIL_VIEW_DESC { - Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D24_UNORM_S8_UINT, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT_S8X24_UINT, ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, ..Default::default() }; diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 935e0dd192..6bfb752fc7 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -230,11 +230,17 @@ fn last(kind: u32) -> &'static AtomicU64 { &LAST[(kind as usize).min(LAST.len() - 1)] } -/// The next tick after now and after the last one a wait for `kind` took -/// (an event happens once per tick: a wait woken a little early must not -/// let the next one end on the same tick), and how long until it. A wait -/// that comes within `limit` takes the tick here, under the clock's lock, -/// so two threads waiting for one kind never take the same tick. +/// The tick a wait for `kind` ends on, and how long until it: the first +/// one after the last a wait for `kind` took (an event happens once per +/// tick: a wait woken a little early must not let the next one end on the +/// same tick), the latest one passed if that is later. A wait begun after +/// its tick passed (a frame slower than the interval) so ends at once, as +/// an event signalled at the tick and left signalled until a wait takes it +/// would (assumed: nothing we have says what a late wait does); waiting for +/// the next tick instead cost the cutscene's frames 0-33 ms each (4 % of +/// the frame thread, run perf3). A wait that +/// comes within `limit` takes the tick here, under the clock's lock, so two +/// threads waiting for one kind never take the same tick. fn next_tick(kind: u32, limit: Duration) -> (u64, Duration) { let mut clock = clock(); let fps = fps_limit(); @@ -253,7 +259,7 @@ fn next_tick(kind: u32, limit: Duration) -> (u64, Duration) { let elapsed = c.start.elapsed().as_nanos(); let interval = interval.as_nanos().max(1); let tick = - (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1); + (c.first + (elapsed / interval) as u64).max(last(kind).load(Ordering::Relaxed) + 1); let at = u128::from(tick - c.first) * interval; let wait = Duration::from_nanos(at.saturating_sub(elapsed) as u64); if wait <= limit { @@ -368,6 +374,13 @@ pub(crate) extern "system" fn wait( if kind == FLIP && hr == S_OK { FLIPS.fetch_add(1, Ordering::Relaxed); } + #[cfg(feature = "diagnostics")] + { + WAITS[0].fetch_add(1, Ordering::Relaxed); + if hr == S_OK && wait.is_zero() { + WAITS[1].fetch_add(1, Ordering::Relaxed); + } + } // A frame begun on a time-out takes no tick: its flip still does. if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) { // Tokens count frames (consecutive), not ticks. @@ -395,6 +408,29 @@ pub(crate) extern "system" fn wait( hr } +/// Diagnostics: frame waits, and those that ended at once (their tick had +/// passed); presents whose flip tick was the previous present's. +#[cfg(feature = "diagnostics")] +static WAITS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; +#[cfg(feature = "diagnostics")] +static PRESENT_TICK: AtomicU64 = AtomicU64::new(0); + +/// Diagnostics: a frame was presented (counts presents sharing a flip tick). +#[cfg(feature = "diagnostics")] +pub(crate) fn presented() { + let flip = LAST[2].load(Ordering::Relaxed); + if flip != 0 && PRESENT_TICK.swap(flip, Ordering::Relaxed) == flip { + WAITS[2].fetch_add(1, Ordering::Relaxed); + } +} + +/// Diagnostics: logs [`WAITS`] since the last call. +#[cfg(feature = "diagnostics")] +pub(crate) fn log() { + let [waits, at_once, shared] = [0, 1, 2].map(|i| WAITS[i].swap(0, Ordering::Relaxed)); + tracing::info!("frame waits: {waits}, {at_once} of them ended at once; presents sharing a flip tick: {shared}"); +} + /// Device method: refreshes monotonic frame statistics and reports 0 console /// records until the console's frame-statistics output struct layout is /// verified (avoiding unverified writes into caller-owned `out`). @@ -486,6 +522,16 @@ mod tests { // Even when a flip wait begins on the tick another just ended on. let (tick, _) = next_tick(FLIP, Duration::ZERO); assert!(tick > flips[3]); + // A flip wait begun after its tick passed (two ticks missed) ends at + // once, on the latest tick passed; the next one waits for the next. + std::thread::sleep(Duration::from_millis(110)); + let before = Instant::now(); + assert_eq!(wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), S_OK); + assert!(before.elapsed() < Duration::from_millis(10), "{:?}", before.elapsed()); + let late = LAST[2].load(Ordering::Relaxed); + assert!(late >= flips[3] + 2, "{late} after {}", flips[3]); + assert_eq!(wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), S_OK); + assert_eq!(LAST[2].load(Ordering::Relaxed), late + 1); // Uncapped override (Some(0)): even with a 30 FPS title interval, // waits return immediately and still advance frames and flips. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 66e1261662..9f237c1670 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1801,6 +1801,15 @@ impl HostList { Some((buffer, data)) } + /// A mapped readback buffer of `size` bytes, alive until the list is + /// reset. + pub(crate) fn readback(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let (buffer, data) = host.mapped_buffer(size, true)?; + name(&buffer, || format!("list readback {size:#x}")); + self.deferred().uploads.push(buffer.clone()); + Some((buffer, data)) + } + /// `len` bytes of upload memory (256-byte aligned) until the list is /// reset: the host GPU address and the CPU pointer. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> { @@ -2625,8 +2634,14 @@ impl Host { } pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + self.mapped_buffer(size, false) + } + + /// A mapped buffer of `size` bytes: upload memory, or (`readback`) + /// readback memory in the copy-destination state. + fn mapped_buffer(&self, size: u64, readback: bool) -> Option<(ID3D12Resource, *mut u8)> { let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_UPLOAD, + Type: if readback { D3D12_HEAP_TYPE_READBACK } else { D3D12_HEAP_TYPE_UPLOAD }, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { @@ -2651,7 +2666,7 @@ impl Host { &heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_GENERIC_READ, + if readback { D3D12_RESOURCE_STATE_COPY_DEST } else { D3D12_RESOURCE_STATE_GENERIC_READ }, None, &mut buffer, ) @@ -2663,7 +2678,7 @@ impl Host { match made { Ok(()) => Some((buffer?, data.cast())), Err(e) => { - tracing::warn!(error = %e, size, "no upload buffer"); + tracing::warn!(error = %e, size, readback, "no mapped buffer"); None } } @@ -2919,11 +2934,20 @@ impl Meter { #[cfg(feature = "diagnostics")] { let copy_frames = std::mem::take(&mut self.copy_stats_frames) as f64; + crate::frame::log(); crate::copystat::log(copy_frames); crate::shadow::lazy::log(copy_frames); crate::bindless::log(copy_frames); crate::shadow::log_views(copy_frames); crate::descriptor::log_heaps(copy_frames); + let [n, bytes] = [0, 1].map(|i| crate::list::READ_BACKS[i].swap(0, Ordering::Relaxed)); + if n > 0 { + tracing::info!( + "texture read backs: {:.1}/frame, {:.1} KB/frame", + n as f64 / frames, + bytes as f64 / frames / 1e3 + ); + } for (why, n) in drops.iter().take(40) { tracing::info!( "dropped {:.1}/frame without a host pipeline: {why}", @@ -3230,7 +3254,7 @@ impl Host { /// memory that shaders write, which upload memory cannot be. Starts in /// the common state (buffers move out of it implicitly). pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { - self.mapped_buffer(size, false) + self.shared_mapped(size, false) } /// A buffer in video memory that the CPU maps through the PCI BAR (a @@ -3254,7 +3278,7 @@ impl Host { }); return None; } - let Some((buffer, data)) = self.mapped_buffer(size, true) else { + let Some((buffer, data)) = self.shared_mapped(size, true) else { UPLOAD_BYTES.fetch_sub(size, Ordering::Relaxed); return None; }; @@ -3397,7 +3421,9 @@ impl Host { } } - fn mapped_buffer(&self, size: u64, upload: bool) -> Option<(ID3D12Resource, *mut u8)> { + /// A mapped buffer shaders may write: system memory (write-back), or + /// (`upload`) a GPU upload heap. + fn shared_mapped(&self, size: u64, upload: bool) -> Option<(ID3D12Resource, *mut u8)> { let heap = if upload { D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_GPU_UPLOAD, @@ -3472,21 +3498,36 @@ pub(crate) fn release_retired() { } /// Diagnostics: a noted command running a shader `VICTORY_TRACE_SHADERS` -/// names (hashes, comma-separated) is logged with what it binds, the first -/// 500. +/// names (hashes, comma-separated) is logged with what it binds: all of +/// them in listed capture frames, the first 500 elsewhere. #[cfg(feature = "diagnostics")] fn traced(what: &str) { - static HASHES: OnceLock> = OnceLock::new(); static LOGGED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let hashes = HASHES.get_or_init(|| { - let v = std::env::var("VICTORY_TRACE_SHADERS").unwrap_or_default(); - v.split(',').map(str::trim).filter(|h| !h.is_empty()).map(str::to_owned).collect() - }); - if hashes.iter().any(|h| what.contains(h.as_str())) && LOGGED.fetch_add(1, Ordering::Relaxed) < 500 { + if is_traced(what) + && (crate::capture::listed(crate::queue::presented() + 1) + || LOGGED.fetch_add(1, Ordering::Relaxed) < 500) + { tracing::info!("traced command: {what}"); } } +/// The shader hashes `VICTORY_TRACE_SHADERS` lists (comma-separated; +/// diagnostics). +#[cfg(feature = "diagnostics")] +pub(crate) fn traced_shaders() -> &'static [String] { + static HASHES: OnceLock> = OnceLock::new(); + HASHES.get_or_init(|| { + let v = std::env::var("VICTORY_TRACE_SHADERS").unwrap_or_default(); + v.split(',').map(str::trim).filter(|h| !h.is_empty()).map(str::to_owned).collect() + }) +} + +/// Whether `what` names a shader [`traced_shaders`] lists. +#[cfg(feature = "diagnostics")] +pub(crate) fn is_traced(what: &str) -> bool { + traced_shaders().iter().any(|h| what.contains(h.as_str())) +} + /// Diagnostics, `VICTORY_GPU_TIMING`: every command of the list during /// whose run (each list alone) the device was found removed. fn removed_during(runs: &[&HostList], list: Option) -> String { diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index edcebb866e..8df296f96c 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -497,8 +497,8 @@ pub(crate) struct CopyLocation { } /// Texture to texture on the GPU; buffer to texture through an upload -/// buffer filled at submission. Texture to buffer (read back) is not done -/// yet. +/// buffer filled at submission; texture to buffer through readback memory +/// ([`read_back`]). extern "system" fn copy_texture_region( this: This, dst: *const CopyLocation, @@ -522,8 +522,9 @@ extern "system" fn copy_texture_region( return; }; let Some(to) = crate::resource::host_resource(dst.resource) else { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!("texture to buffer copies not implemented")); + if dst.kind == FOOTPRINT && src.kind != FOOTPRINT { + read_back(list, &dst, [x, y, z], &src, source_box); + } return; }; let mut from = src; @@ -607,6 +608,118 @@ extern "system" fn copy_texture_region( let _ = (this, dst, x, y, z, src, source_box); } +/// Texture read backs since the last frame-rate line: how many, bytes +/// (diagnostics). +#[cfg(feature = "diagnostics")] +pub(crate) static READ_BACKS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// (texture, buffer) pairs read back so far, each logged once (diagnostics). +#[cfg(feature = "diagnostics")] +static READ_BACK_PAIRS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Texture to buffer (a read back): the region is copied on the host into +/// readback memory laid out as the title's footprint, and once the list has +/// run its rows go into the title's buffer (the title reads them on the CPU +/// after its fence). +#[cfg(windows)] +fn read_back(list: &crate::host::HostList, dst: &CopyLocation, at: [u32; 3], src: &CopyLocation, source_box: *const [u32; 6]) { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_BOX, D3D12_RESOURCE_DIMENSION_TEXTURE3D, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + }; + use windows::core::Interface; + macro_rules! refused { + ($why:literal) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(concat!("texture to buffer copy refused: ", $why))); + return; + }}; + } + let (Some(host), Some(texture)) = (crate::host::host(), crate::resource::host_resource(src.resource)) else { + refused!("no host texture"); + }; + // SAFETY: the title's box (same layout as the host's) or null; a live texture. + let (b, desc) = unsafe { (source_box.cast::().as_ref(), texture.GetDesc()) }; + let size = match b { + Some(b) => [b.right.saturating_sub(b.left), b.bottom.saturating_sub(b.top), b.back.saturating_sub(b.front)], + None => { + // A subresource index shares the footprint's first dword. + let mip = src.footprint.offset as u32 % u32::from(desc.MipLevels.max(1)); + let depth = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { u32::from(desc.DepthOrArraySize) } else { 1 }; + [((desc.Width >> mip) as u32).max(1), (desc.Height >> mip).max(1), (depth >> mip).max(1)] + } + }; + // The host takes footprints of 256-byte pitches only (as the console). + if !dst.footprint.row_pitch.is_multiple_of(256) { + refused!("a row pitch not a multiple of 256"); + } + // shortcut: depth and stencil planes copy out in typeless formats of + // their own; refused until a title is seen reading one back. + if desc.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0 { + refused!("a depth or stencil texture"); + } + // The host copies into a footprint only within a buffer that holds all + // of it, so readback memory spans the footprint, not just the region. + let (Some(rows), Some(len)) = (dst.footprint.rows(at, size), dst.footprint.bytes()) else { + refused!("a region outside its footprint"); + }; + let (Some(title), Some((buffer, data))) = (buffer_range(dst.resource, dst.footprint.offset, len), list.readback(host, len)) else { + return; + }; + if crate::texture::title_written(texture) { + crate::texture::upload(list, src.resource, texture); + } + ensure_state(list, src.resource, COPY_SOURCE); + let (mut to, mut from) = (*dst, *src); + to.resource = buffer.as_raw().cast_const().cast(); + to.footprint.offset = 0; + from.resource = texture.as_raw().cast_const().cast(); + #[cfg(feature = "diagnostics")] + { + let text = || { + let mem = crate::resource::texture_memory(src.resource).map_or(0, |(at, _)| at as usize); + format!( + "read back {:?} (mem {mem:#x}, {}x{} f{} sub {}) {size:?} at {at:?} into {:?}+{:#x}, {len} bytes", + src.resource, + desc.Width, + desc.Height, + desc.Format.0, + src.footprint.offset as u32, + dst.resource, + dst.footprint.offset + ) + }; + READ_BACKS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + READ_BACKS[1].fetch_add(len, std::sync::atomic::Ordering::Relaxed); + let pair = (src.resource as usize, dst.resource as usize); + let mut seen = READ_BACK_PAIRS.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&pair) { + seen.push(pair); + tracing::info!("a texture read back (first of this pair): {}", text()); + } + list.note_op(text); + } + // SAFETY: an open list; both locations in the host's layout, naming live + // resources; the region lies in the footprint (checked). + unsafe { + list.list.CopyTextureRegion( + (&raw const to).cast(), + at[0], + at[1], + at[2], + (&raw const from).cast(), + b.map(std::ptr::from_ref), + ) + }; + let (data, title) = (data as usize, title as usize); + list.defer_after(move || { + for &(at, n) in &rows { + let (at, n) = (at as usize, n as usize); + let _writing = crate::watch::writing(title + at, n); + crate::host::write_mapped((title + at) as *mut u8, (data + at) as *const u8, n); + } + }); +} + #[allow(clippy::too_many_arguments)] // the method's own arguments extern "system" fn copy_texture_region_x( this: This, diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 99a0d07a73..ba071b7977 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -243,6 +243,8 @@ extern "system" fn present( _parameters: *const u8, ) -> HRESULT { let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; + #[cfg(feature = "diagnostics")] + crate::frame::presented(); if frame.is_power_of_two() { let (draws, dispatches) = crate::list::take_counts(); #[cfg(windows)] diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index c6059523c6..a750c9d6a1 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -227,12 +227,17 @@ fn footprint(desc: &ResourceDesc) -> Option { } /// A format as the host has it. The console's 16-bit depth with stencil -/// (and its typeless views) has no PC format: the 24-bit ones stand in. +/// (and its typeless views) has no PC format: the 32-bit float ones stand +/// in, so that depth its shaders write through unordered views +/// (`crate::twin`) arrives as the very float a draw rasterises; copied into +/// 24-bit depth it never tested EQUAL against a draw on the RX 6700 XT. +/// shortcut: a depth bias on such a target counts in float steps, not +/// 1/65535; scale it if a title's 16-bit depth biased draws show acne. pub(crate) fn pc_format(format: u32) -> u32 { match format { - 118 => 45, - 119 => 46, - 120 => 47, + 118 => 20, + 119 => 21, + 120 => 22, other => other, } } @@ -316,11 +321,11 @@ fn mip_count(desc: &ResourceDesc) -> u32 { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct PlacedFootprint { pub(crate) offset: u64, - format: u32, - width: u32, - height: u32, - depth: u32, - row_pitch: u32, + pub(crate) format: u32, + pub(crate) width: u32, + pub(crate) height: u32, + pub(crate) depth: u32, + pub(crate) row_pitch: u32, } impl PlacedFootprint { @@ -331,6 +336,27 @@ impl PlacedFootprint { let last = u64::from(self.width).div_ceil(block) * element; Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last) } + + /// The byte ranges (from the footprint's start) that a `size` texel + /// region at texel `at` covers: one per row of blocks; `None` if the + /// format has no size or the region leaves the footprint. + pub(crate) fn rows(&self, at: [u32; 3], size: [u32; 3]) -> Option> { + let (element, block) = element(self.format)?; + let blocks = |texels: u32| u64::from(texels).div_ceil(block); + let [x, y, z] = at.map(u64::from); + let (w, h, d) = (blocks(size[0]), blocks(size[1]), u64::from(size[2])); + let (x, y) = (x / block, y / block); + if x + w > blocks(self.width) || y + h > blocks(self.height) || z + d > u64::from(self.depth) { + return None; + } + let pitch = u64::from(self.row_pitch); + let slice = pitch * blocks(self.height); + Some( + (z..z + d) + .flat_map(|k| (y..y + h).map(move |r| (k * slice + r * pitch + x * element, w * element))) + .collect(), + ) + } } const _: () = assert!(size_of::() == 32); @@ -1855,6 +1881,17 @@ pub(crate) fn test_buffer(width: u64) -> This { #[cfg(test)] mod tests { use super::*; + + #[test] + fn a_regions_rows_in_a_footprint() { + // R32_FLOAT (41) 100x8x1, pitch 512. + let f = PlacedFootprint { offset: 4096, format: 41, width: 100, height: 8, depth: 1, row_pitch: 512 }; + assert_eq!(f.rows([2, 3, 0], [10, 2, 1]), Some(vec![(3 * 512 + 8, 40), (4 * 512 + 8, 40)])); + assert_eq!(f.rows([95, 0, 0], [10, 1, 1]), None, "past the width"); + // BC1 (71) 16x16, 8 bytes a 4x4 block, pitch 256: a block row per 4 texel rows. + let bc = PlacedFootprint { offset: 0, format: 71, width: 16, height: 16, depth: 1, row_pitch: 256 }; + assert_eq!(bc.rows([4, 4, 0], [8, 8, 1]), Some(vec![(256 + 8, 16), (2 * 256 + 8, 16)])); + } use crate::object::slot; #[test] @@ -2388,6 +2425,76 @@ mod tests { } } + /// A texture region copied into a title buffer through our list and + /// queue: once the list has run, its rows are in the buffer at the + /// footprint's offset and pitch, and nothing else of the buffer moved. + #[cfg(windows)] + #[test] + fn a_texture_read_back_reaches_the_title_buffer() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let iid = &RESOURCE_IIDS[0]; + const COPY_DEST: u32 = 0x400; + let (mut image, mut source, mut target) = (null, null, null); + let created = |desc: &ResourceDesc, state, out: &mut This| { + assert_eq!(create_committed(null, &PROPERTIES, 0, desc, state, null.cast(), iid, out), S_OK); + }; + created(&texture(4, 4, 28, 1), COPY_DEST, &mut image); + created(&buffer(1024), 0, &mut source); + created(&buffer(4096), 0, &mut target); + let (data, _) = buffer_bytes(source).unwrap(); + // SAFETY: the buffer holds 1024 bytes. + let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) }; + for (i, b) in bytes.iter_mut().enumerate() { + *b = (i % 251) as u8; + } + let (out, _) = buffer_bytes(target).unwrap(); + // SAFETY: the buffer holds 4096 bytes. + unsafe { std::ptr::write_bytes(out, 0xEE, 4096) }; + let (mut queue, mut allocator, mut list) = (null, null, null); + let queue_desc = [0u32; 4]; + assert_eq!( + crate::queue::create(null, queue_desc.as_ptr().cast(), &guid(0x0ec870a6, 0x5d7e, 0x4c22, [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed]), &mut queue), + S_OK + ); + assert_eq!( + crate::list::create_allocator(null, 0, &guid(0x6102dee4, 0xaf59, 0x4b09, [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24]), &mut allocator), + S_OK + ); + assert_eq!( + crate::list::create_list(null, 0, 0, allocator, null, &guid(0x5b160d0f, 0xac1b, 0x4185, [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55]), &mut list), + S_OK + ); + #[repr(C)] + struct Location { + resource: This, + kind: u32, + footprint: PlacedFootprint, + } + let rows = PlacedFootprint { offset: 0, format: 28, width: 4, height: 4, depth: 1, row_pitch: 256 }; + let image_at = Location { resource: image, kind: 0, footprint: rows }; + let from_source = Location { resource: source, kind: 1, footprint: rows }; + // Texels (1..3, 1..3) into the target's footprint at 512, at texel (2, 1). + let into_target = Location { resource: target, kind: 1, footprint: PlacedFootprint { offset: 512, ..rows } }; + let region: [u32; 6] = [1, 1, 0, 3, 3, 1]; + type Copy = extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8); + let copy = slot::(list, 0x80); + copy(list, &image_at, 0, 0, 0, &from_source, null.cast()); + copy(list, &into_target, 2, 1, 0, &image_at, region.as_ptr().cast()); + slot:: HRESULT>(list, 0x48)(list); + slot::(queue, 0x50)(queue, 1, &list); + // SAFETY: the buffer holds 4096 bytes; the submission has run. + let read = unsafe { std::slice::from_raw_parts(out, 4096) }; + let mut want = vec![0xEEu8; 4096]; + for row in 0..2 { + let (to, from) = (512 + (1 + row) * 256 + 2 * 4, (1 + row) * 256 + 4); + want[to..to + 8].copy_from_slice(&bytes[from..from + 8]); + } + assert!(read == want.as_slice(), "the region's rows, and nothing else"); + } + #[test] fn committed_and_placed_resources_map_at_their_gpu_address() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/twin.rs b/crates/victory-gpu/src/twin.rs index b3a17306c8..89554ec787 100644 --- a/crates/victory-gpu/src/twin.rs +++ b/crates/victory-gpu/src/twin.rs @@ -8,7 +8,7 @@ //! contents move between the two by copies where the use changes: within //! a list where it records the change (`HostList::transition`), and at //! submission for each list's first use, from the side the lists before it -//! left newer. A 16-bit depth plane in the host's 24-bit one (the +//! left newer. A 16-bit depth plane in the host's 32-bit float one (the //! console's 16-bit depth with stencil) is converted on the way, so a //! value written as 16-bit depth compares equal to the same depth //! rasterised. @@ -75,7 +75,7 @@ struct Route { /// Its place in the scratch buffer as the twin's texture has it. twin: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, /// As the depth texture has it, where that differs: a 16-bit depth - /// plane the host keeps in 24 bits (32 per texel), converted. + /// plane the host keeps as 32-bit floats, converted. depth: Option, } @@ -453,24 +453,16 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { } } -/// 16-bit depth (unorm, two per dword) to the host's 24-bit depth plane (in -/// the low 24 bits of 32) and back, in the scratch buffer: `u * (2^24 - 1) -/// / 65535` rounded, exactly, and back to the 16-bit value whose 24-bit one -/// is nearest. +/// 16-bit depth (unorm, two per dword) to the host's 32-bit float depth +/// plane and back, in the scratch buffer: `u` becomes `u` times +/// `0x37800080` (the title's 1/65535; its tiled-lighting draws rasterise +/// that very float and test it EQUAL), and a float back the nearest `u`. const SOURCE: &str = r#" #define RS "RootConstants(num32BitConstants=8, b0), UAV(u0)" cbuffer C : register(b0) { uint width; uint height; uint pitch16; uint at16; uint pitch32; uint at32; uint toDepth; uint unused; }; RWByteAddressBuffer buf : register(u0); -uint d24(uint u) { return u * 256 + (u * 255 + 32767) / 65535; } -uint u16(uint d) { - d &= 0xffffff; - uint u = min(d >> 8, 65535); - uint best = u; - int err = abs((int)d24(u) - (int)d); - if (u > 0 && abs((int)d24(u - 1) - (int)d) < err) { best = u - 1; err = abs((int)d24(u - 1) - (int)d); } - if (u < 65535 && abs((int)d24(u + 1) - (int)d) < err) { best = u + 1; } - return best; -} +uint depth(uint u) { return asuint((float)u * asfloat(0x37800080)); } +uint u16(uint d) { return (uint)(saturate(asfloat(d)) * 65535.0 + 0.5); } [RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { @@ -482,8 +474,8 @@ void main(uint3 id : SV_DispatchThreadID) { bool two = x + 1 < width; if (toDepth != 0) { uint pair = buf.Load(a); - buf.Store(b, d24(pair & 0xffff)); - if (two) buf.Store(b + 4, d24(pair >> 16)); + buf.Store(b, depth(pair & 0xffff)); + if (two) buf.Store(b + 4, depth(pair >> 16)); } else { uint lo = u16(buf.Load(b)); uint hi = two ? u16(buf.Load(b + 4)) : 0; diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 5e14ab68a9..5a74e21e39 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -295,7 +295,10 @@ fn runtime_memory(at: usize, views: bool) -> bool { impl Drop for Tracked { /// Pages no tracker holds any more get write access back, so that the - /// guard set never names memory freed and allocated again. + /// guard set never names memory freed and allocated again; unless another + /// mapping of the page is held: the guard here is that tracker's too (it + /// was set when that tracker took its page), and with it opened a write + /// here went unseen there. fn drop(&mut self) { let mut g = guards(); let mut free = Vec::new(); @@ -309,7 +312,10 @@ impl Drop for Tracked { } } for page in free { - open(&mut g, page); + let watched_elsewhere = g.alias_of.get(&page).is_some_and(|o| o.iter().any(|p| g.holders.contains_key(p))); + if !watched_elsewhere { + open(&mut g, page); + } } } } @@ -1113,6 +1119,22 @@ pub(crate) mod tests { assert_eq!(t.take(a, a + 2 * PAGE), [(a, a + PAGE)]); } + /// A tracker of one mapping going away leaves the guard its page shares + /// with a tracker of another mapping, so a write there still counts (it + /// was opened, and the pages it went unseen in stayed clean). + #[test] + fn a_tracker_dropped_on_one_mapping_leaves_the_other_guarded() { + let (a, b) = twin_views(1); + let t = track(a, PAGE, true).expect("views are tracked"); + let u = track(b, PAGE, true).expect("views are tracked"); + assert_eq!(t.take(a, a + PAGE), [(a, a + PAGE)]); + assert_eq!(u.take(b, b + PAGE), [(b, b + PAGE)]); + drop(u); + // SAFETY: the second view, guarded for `t`'s page too. + unsafe { ((b + 4) as *mut u32).write_volatile(7) }; + assert_eq!(t.take(a, a + PAGE), [(a, a + PAGE)]); + } + /// A write or mapping that runs past the end of the address space (a /// title's `fread` with a huge count) covers up to the end; the sum used /// to overflow. Up there no test has guarded blocks. diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 83a7a81ae2..9cef4f09a1 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -144,7 +144,7 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened"); // SAFETY: a handle we just opened and nobody else owns. let file = unsafe { std::fs::File::from_raw_handle(handle) }; - let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file }); + let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file, path: name }); put(out, file) } @@ -258,6 +258,8 @@ static FACTORY_VTABLE: Methods<16> = Methods([ struct File { file: std::fs::File, + /// As the title named it (diagnostics). + path: String, } static FILE_VTABLE: Methods<8> = Methods([ @@ -368,6 +370,9 @@ struct Lane { clock: u64, /// Enqueued, not yet submitted. unsubmitted: Vec, + /// Left out when the queue submitted itself, until the title's Submit: + /// reads into physical pages and the status entries behind them. + held: Vec, /// Submitted, by sequence number: reads not started, status entries /// not written, reads running, and failures not yet reported. reads: VecDeque<(u64, Request)>, @@ -547,8 +552,20 @@ impl Lanes { } } - /// Moves a queue's enqueued commands to the workers. + /// Moves a queue's enqueued commands to the workers (the title's + /// Submit). fn submit(&mut self, id: u64) { + self.submit_as(id, true); + } + + /// As [`Lanes::submit`]; `explicit` false when a half-full queue submits + /// itself, which leaves reads into physical pages for the title's + /// Submit: their page lists point into the title's page table, which + /// Grand Theft Auto VI fills for the batch in its own submit path, right + /// before Submit (`sub_1400e88f0`), so until then they name no page or a + /// page that now holds something else. A status entry behind a held + /// read waits with it. + fn submit_as(&mut self, id: u64, explicit: bool) { let Some(class) = self.lanes.get(&id).map(|l| l.class) else { return; }; @@ -567,7 +584,18 @@ impl Lanes { if lane.reads.is_empty() { lane.clock = lane.clock.max(self.lane_now[class]); } - for command in std::mem::take(&mut lane.unsubmitted) { + let mut commands = if explicit { std::mem::take(&mut lane.held) } else { Vec::new() }; + commands.append(&mut lane.unsubmitted); + for command in commands { + let hold = !explicit + && match &command { + Command::Read(r) => r.options & PAGE_DESTINATION != 0, + Command::Status(_) => !lane.held.is_empty(), + }; + if hold { + lane.held.push(command); + continue; + } let seq = self.next_seq; self.next_seq += 1; match command { @@ -586,6 +614,7 @@ impl Lane { capacity: usize::from(capacity), clock: 0, unsubmitted: Vec::new(), + held: Vec::new(), reads: VecDeque::new(), statuses: VecDeque::new(), running: BTreeSet::new(), @@ -596,7 +625,11 @@ impl Lane { /// Requests and status entries held, submitted or not. fn entries(&self) -> usize { - self.unsubmitted.len() + self.reads.len() + self.statuses.len() + self.running.len() + self.unsubmitted.len() + + self.held.len() + + self.reads.len() + + self.statuses.len() + + self.running.len() } /// Writes the status entries whose earlier reads have all finished. @@ -644,6 +677,7 @@ fn close_lane(id: u64) { }; lane.closed = true; lane.unsubmitted.clear(); + lane.held.clear(); lane.reads.clear(); lane.statuses.clear(); // releases their arrays while lanes.lanes.get(&id).is_some_and(|l| !l.running.is_empty()) { @@ -755,6 +789,16 @@ fn queue(this: QueueRef, command: Command) { if lane.entries() + 1 < lane.capacity.max(2) { break; } + // Full with reads held for a Submit the title cannot make while it + // waits here: they go now, page lists as they are. + if !lane.held.is_empty() { + static WARNED: AtomicBool = AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + tracing::warn!("dstorage: a full queue's reads into physical pages start before the title's Submit"); + } + lanes.submit(id); + scheduler.work.notify_all(); + } lanes = scheduler .finished .wait(lanes) @@ -765,8 +809,19 @@ fn queue(this: QueueRef, command: Command) { }; lane.unsubmitted.push(command); if lane.unsubmitted.len() >= (lane.capacity / 2).max(1) { - lanes.submit(id); + let capacity = lane.capacity; + lanes.submit_as(id, false); scheduler.work.notify_all(); + let held = lanes.lanes.get(&id).map_or(0, |l| l.held.len()); + let n = AUTO_SUBMITS.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::info!( + n, + capacity, + held, + "dstorage: a queue half full submitted itself; reads into physical pages wait for the title's Submit" + ); + } } } @@ -777,7 +832,7 @@ extern "system" fn submit(this: QueueRef) { return; }; let mut lanes = scheduler.lock(); - let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len()); + let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len() + l.held.len()); tracing::debug!(commands = pending, "dstorage: submit"); lanes.submit(id); scheduler.work.notify_all(); @@ -1012,11 +1067,28 @@ fn into_destination( offset, len, pages = pages.len(), + unknown = super::xmem::unknown_pages(pages), + list = format_args!("{:x?}", &pages[..pages.len().min(8)]), + options = format_args!("{:#x}", request.options), + file = source_name(request), + file_offset = request.offset, "dstorage: a destination's physical pages could not be written; its request fails" ); Err(E_INVALIDARG) } +/// The file a request reads, as the title named it, or "memory". +fn source_name(request: &Request) -> &str { + if request.options & MEMORY_SOURCE != 0 { + return "memory"; + } + // SAFETY: a file object we created; the title keeps it open. + &unsafe { &*request.source.cast::>() }.state.path +} + +/// Queues that submitted themselves, half full (diagnostics). +static AUTO_SUBMITS: AtomicU32 = AtomicU32::new(0); + /// Milliseconds a page list naming page 0 is read again for. const LATE_LIST_TRIES: u32 = 8; /// Page lists filled after their request started (written late). @@ -1573,6 +1645,95 @@ mod tests { let seen = unsafe { std::slice::from_raw_parts(mapped.cast::(), plain.len()) }; assert_eq!(seen, plain); } + #[test] + fn a_queue_that_submits_itself_holds_reads_into_pages() { + let mut l = lanes(STAGING); + l.lanes.insert(0, Lane::new(0, 64)); + let array = status_array(1).cast::>(); + read(&mut l, 0, PAGE_DESTINATION, 16); + read(&mut l, 0, 0, 16); + add_ref_instance(array); + l.lanes.get_mut(&0).unwrap().unsubmitted.push(Command::Status(Status { array, index: 0 })); + l.submit_as(0, false); + // Only the plain read starts; the status waits behind the held one. + let plain = l.start().unwrap(); + assert_eq!(plain.request.options, 0); + assert!(l.start().is_none()); + l.finish(&plain, Ok(())); + assert_eq!(l.lanes[&0].held.len(), 2); + l.submit(0); + let paged = l.start().unwrap(); + assert_eq!(paged.request.options, PAGE_DESTINATION); + assert!(l.lanes[&0].held.is_empty()); + assert!(!l.lanes[&0].statuses.is_empty()); + l.finish(&paged, Ok(())); + assert!(l.lanes[&0].statuses.is_empty()); + } + + #[test] + fn a_page_list_the_title_changes_before_its_submit() { + use crate::modules::xmem; + let (mut given, mut pages) = (2usize, [0usize; 2]); + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!(xmem::XMemMapPhysicalPages(mapped, 2, pages.as_ptr()), mapped); + // The title's page table: still the page's previous owner when the + // request is enqueued, the right page by its Submit. + let mut list = [pages[0]]; + let plain = pattern(4096); + let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = + call(factory(), 0x50); + let desc = QueueDesc { + source_type: 0, + capacity: 4, + priority: 1, + name: c"pages".as_ptr(), + unknown: 1, + }; + let mut queue = std::ptr::null_mut(); + assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); + let array = status_array(1); + let r = request( + PAGE_DESTINATION | MEMORY_SOURCE, + list.as_mut_ptr().cast(), + plain.len(), + plain.as_ptr().cast(), + 0, + plain.len(), + ); + enqueue(queue, &r); + let mut out = [0u8; 16]; + enqueue(queue, &request(MEMORY_SOURCE, out.as_mut_ptr().cast(), 16, plain.as_ptr().cast(), 0, 16)); + // Half of four: the queue submitted itself. Time for a read started + // then to land in the old page. + std::thread::sleep(std::time::Duration::from_millis(50)); + // SAFETY: the list outlives the request, which reads it when it runs. + unsafe { std::ptr::write_volatile(list.as_mut_ptr(), pages[1]) }; + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, plain[..16]); + // SAFETY: both pages are mapped read-write. + let (first, second) = unsafe { + ( + std::slice::from_raw_parts(mapped.cast::(), plain.len()), + std::slice::from_raw_parts(mapped.cast::().add(PAGE), plain.len()), + ) + }; + assert_eq!(second, plain); + assert!(first.iter().all(|&b| b == 0), "the old page was written"); + } + #[test] fn zlib_into_pages_in_place_and_across_allocations() { use crate::modules::xmem; diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index f4e5ff8a75..7002884fba 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -441,10 +441,18 @@ fn shown_at(pages: &[usize]) -> Vec { /// view showing them (DirectStorage's page destinations). fn report_written(shown: &[usize]) { for &page in shown { + #[cfg(test)] + REPORTED.with(|r| r.borrow_mut().push(page)); drop(victory_gpu::kernel_will_write(page, PAGE)); } } +#[cfg(test)] +thread_local! { + /// The title addresses this thread's writes into physical pages reported. + static REPORTED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + static PHYSICAL: LazyLock> = LazyLock::new(|| { Mutex::new(Physical { // Page numbers are opaque to titles; 0 stays unused. @@ -523,6 +531,13 @@ pub extern "system" fn XMemAllocatePhysicalPages( /// them with `<< 4` (128 GiB of pages at most). const FRAMES: usize = PAGE >> 12; +/// How many of `pages` are no allocated page (diagnostics: a DirectStorage +/// destination that could not be written). +pub(crate) fn unknown_pages(pages: &[usize]) -> usize { + let physical = physical(); + pages.iter().filter(|p| !physical.pages.contains_key(p)).count() +} + /// Pages still mapped stay readable through their views until unmapped. pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL { if pages.is_null() { @@ -615,8 +630,8 @@ pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> boo let Some(runs) = runs(pages, offset, data.len()) else { return false; }; - let shown = shown_at(pages.get(offset / PAGE..(offset + data.len()).div_ceil(PAGE)).unwrap_or(&[])); - flush_shown(&shown); + // The GPU's pending writes go in first, where the pages show now. + flush_shown(&shown_at(pages.get(offset / PAGE..(offset + data.len()).div_ceil(PAGE)).unwrap_or(&[]))); let (mut within, mut done) = (offset % PAGE, 0); for (slice, n) in &runs { let Some(mut view) = View::map(slice, *n) else { @@ -626,7 +641,8 @@ pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> boo view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]); (within, done) = (0, done + k); } - report_written(&shown); + // Where the pages show once written (see `PageWindow`). + report_written(&shown_at(pages.get(offset / PAGE..(offset + data.len()).div_ceil(PAGE)).unwrap_or(&[]))); true } @@ -637,13 +653,18 @@ pub(crate) struct PageWindow { view: View, within: usize, len: usize, - /// Title views showing the pages, told when the window is done. - shown: Vec, + /// The pages (page numbers) the bytes reach: the title views showing + /// them when the window is done are told. Looked up then, not when the + /// window opens: a decode takes milliseconds, and the title may map a + /// page at another address meanwhile (its GPU heap); a copy that took + /// the page there before the bytes landed would never hear of them. An + /// address that stops showing a page meanwhile was told by the unmap. + pages: Vec, } impl Drop for PageWindow { fn drop(&mut self) { - report_written(&self.shown); + report_written(&shown_at(&self.pages)); } } @@ -664,13 +685,14 @@ pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option< let [(slice, n)] = runs.as_slice() else { return None; }; - let shown = shown_at(pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or(&[])); - flush_shown(&shown); + let pages = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or(&[]).to_vec(); + // The GPU's pending writes go in first, where the pages show now. + flush_shown(&shown_at(&pages)); Some(PageWindow { view: View::map(slice, *n)?, within: offset % PAGE, len, - shown, + pages, }) } @@ -1355,6 +1377,35 @@ mod tests { assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); } + /// A page mapped at a second address while a window writes it is + /// reported there too when the window is done (the title maps streamed + /// pages into its GPU heap while their reads decode); an address that + /// stopped showing it meanwhile is not. + #[test] + fn page_windows_report_where_the_pages_show_when_done() { + let pages = allocate(1); + let reserve = || XMemVirtualAlloc(std::ptr::null_mut(), PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + let (a, b) = (reserve(), reserve()); + assert!(!a.is_null() && !b.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 1, pages.as_ptr()), a); + REPORTED.with(|r| r.borrow_mut().clear()); + let mut window = page_window(&pages, 0, 16).expect("one run"); + // Mapped at `b`, unmapped from `a`, while the bytes are written. + assert_eq!(XMemMapPhysicalPages(b, 1, pages.as_ptr()), b); + assert_eq!(XMemMapPhysicalPages(a, 1, std::ptr::null()), a); + window.bytes().fill(3); + drop(window); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), [b as usize]); + // SAFETY: mapped read-write. + assert_eq!(unsafe { b.cast::().read() }, 3); + // `write_physical` the same way. + REPORTED.with(|r| r.borrow_mut().clear()); + assert!(write_physical(&pages, 0, &[4])); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), [b as usize]); + assert_eq!(XMemMapPhysicalPages(b, 1, std::ptr::null()), b); + assert_eq!(XMemFreePhysicalPages(1, pages.as_ptr()), 1); + } + #[test] fn page_windows_cover_one_run_in_place() { let (a, b) = (allocate(3), allocate(1));