diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 1b8c561..8ca22c9 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -221,7 +221,7 @@ static BAKE_SERVED: AtomicU64 = AtomicU64::new(0); /// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the /// frame listings print it. They draw into a 256x256 corner of 2048x2048 /// targets and name no texture in a table. -const BAKE_PIXEL_SHADERS: [&str; 4] = +pub(crate) const BAKE_PIXEL_SHADERS: [&str; 4] = ["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"]; /// Since the start: early runs of the texture pass, and those of them @@ -2239,7 +2239,15 @@ impl State { }); let per_frame = match asked { Some(mb) => mb << 20, - None => staging_budget_per_frame(memory.map(|[budget, ..]| budget)), + None => { + let base = staging_budget_per_frame(memory.map(|[budget, ..]| budget)); + let capped = if crate::residency::limited_host_ram() { + base.min(128 << 20) + } else { + base + }; + crate::residency::prefetch_limit(capped, crate::residency::pressured()) + } }; static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); static SPENT: AtomicU64 = AtomicU64::new(0); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6bedd50..f05b5f3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -376,7 +376,7 @@ pub(crate) fn ram_idle_ms(avail_phys: Option) -> u64 { (Some(a), Some(b)) => Some(a.min(b)), (a, b) => a.or(b), }; - ram_idle_for(effective, keep_freed()) + ram_idle_for(effective, keep_freed() && !crate::residency::limited_host_ram()) } fn ram_idle_for(avail_phys: Option, keep: bool) -> u64 { @@ -2236,6 +2236,8 @@ enum Step { /// Brings a texture's staging buffer up to date: once per submission, /// whichever lists sample it, until a `Copy` or `Run` intervenes. Texture(std::sync::Arc), + /// Reads a CPU-written linear movie plane into a per-list upload buffer. + Plane((usize, usize), Box), /// A title buffer copy that the list does on the card ([`place`]): what /// is done on the CPU for it. Placed(place::Placed), @@ -2249,6 +2251,8 @@ struct Deferred { /// Destination, source, bytes. copies: Vec, uploads: Vec, + /// Standalone upload footprints kept through this list's fence (movie planes). + plane_uploads: Vec<(Chunk, u64)>, /// The bytes of `uploads` (counted in [`ALIVE`] while they are held). upload_bytes: u64, /// Host objects the list's commands name (pipelines, root signatures, @@ -2313,6 +2317,7 @@ impl Deferred { impl Drop for Deferred { fn drop(&mut self) { + give_chunks(std::mem::take(&mut self.plane_uploads)); ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed); ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed); } @@ -2991,6 +2996,16 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op return Some(WHY_READ); } } + &Step::Plane((at, len), _) => { + if touches(written, at, at.saturating_add(len)) { + if count { + LATE_STATS[17].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + blame("a movie plane", written, at, len); + } + return Some(WHY_READ); + } + } Step::Run(_) => return Some(WHY_RUN), Step::Placed(p) => match p.waits(written) { place::Waits::No => {} @@ -7242,6 +7257,23 @@ impl HostList { self.deferred().copies.push(Step::Texture(staging)); } + /// A copy source owned exclusively by this list until reset after its + /// last execution. A different list can prepare its movie plane concurrently. + pub(crate) fn plane_upload( + &self, + size: u64, + read: (usize, usize), + fill: impl Fn(usize) + Send + 'static, + ) -> Option { + let chunk = take_chunk(host()?, size)?; + let source = chunk.buffer.clone(); + let destination = chunk.data; + let mut deferred = self.deferred(); + deferred.plane_uploads.push((chunk, size)); + deferred.copies.push(Step::Plane(read, Box::new(move || fill(destination)))); + Some(source) + } + /// Runs the list's submission-time steps; refreshes go into `batch` /// (the title's big buffers, a 174 MB one among them, are read by most /// lists of a submission, through many ranges). Copies and fills that @@ -7360,6 +7392,13 @@ impl HostList { } continue; } + Step::Plane((_, len), fill) => { + let started = std::time::Instant::now(); + fill(); + PREPARING[2].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + PREPARING[3].fetch_add(*len as u64, Ordering::Relaxed); + continue; + } }; us += started.elapsed(); bytes += copied as u64; diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 9ee1494..166addd 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -201,6 +201,7 @@ pub(super) fn copied_read(copies: &[Writer], runs: &[&HostList]) -> bool { .iter() .any(|w| w.from < *at + *len && *at < w.to && w.shadow.as_ref().is_none_or(|s| !Arc::ptr_eq(s, shadow))), Step::Host(_, (from, to)) => copies.iter().any(|w| w.from < *to && *from < w.to), + Step::Plane((at, len), _) => copies.iter().any(|w| w.from < at.saturating_add(*len) && *at < w.to), _ => false, }) }) @@ -440,6 +441,11 @@ fn does_of(written: &[(usize, usize)], runs: &[&HostList]) -> (Vec, Vec<(u asked: touches(written, at, at + len), } } + &Step::Plane((at, len), _) => Does::Read { + from: at, + to: at.saturating_add(len), + asked: touches(written, at, at.saturating_add(len)), + }, &Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false }, Step::Refresh(shadow, at, len) => Does::Refresh { shadow: Arc::as_ptr(shadow) as usize, diff --git a/crates/victory-gpu/src/host/place.rs b/crates/victory-gpu/src/host/place.rs index 9e815d4..b5a7bb7 100644 --- a/crates/victory-gpu/src/host/place.rs +++ b/crates/victory-gpu/src/host/place.rs @@ -119,6 +119,7 @@ pub(super) fn read_by(runs: &[&HostList], mut ranges: Vec<(usize, usize)>) -> bo let (at, len) = staging.memory(); touches(&ranges, at, at + len) } + &Step::Plane((at, len), _) => touches(&ranges, at, at.saturating_add(len)), Step::Host(_, (from, to)) => touches(&ranges, *from, *to), Step::Placed(p) => p.from.is_some() && touches(&ranges, p.src, p.src + p.len), _ => false, diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 5ade89f..5c61fc5 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -41,8 +41,63 @@ pub(crate) struct Pending { /// whether a draw or dispatch has requested it yet. key: String, used: AtomicBool, - /// A pass over the screen ([`GraphicsState::screen_pass`]). + /// A pass over the screen ([`GraphicsState::screen_pass`]) or a confirmed + /// opening-scene / bake producer that must never sit behind cold RT shaders. screen: bool, + /// Confirmed first-scene / bake producer prepared early even on a cold cache. + scene_input: bool, + /// Why this pipeline is intentionally skipped (e.g. RT resolve without BVH). + left_out: Option<&'static str>, +} + +fn named(shaders: &[Arc], name: &[u8]) -> bool { + shaders + .iter() + .any(|s| s.stage == "compute" && s.container.windows(name.len()).any(|w| w == name)) +} + +fn left_out(shaders: &[Arc]) -> Option<&'static str> { + static SKIP_RT_RESOLVE: OnceLock = OnceLock::new(); + let skip_rt = *SKIP_RT_RESOLVE.get_or_init(|| { + let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1"); + if builder { + return false; + } + // Without BVH, ~1,000 CS_RaytracingResolve shaders shade no hits while + // clogging the cold compiler queue; skip unless VICTORY_RT_RESOLVE=1. + std::env::var_os("VICTORY_RT_RESOLVE").is_none_or(|v| v == "0") + }); + if skip_rt && named(shaders, b"CS_RaytracingResolve") { + return Some("shades ray-tracing hits without BVH, left out"); + } + static SKIP_ACTIVATE_RAYS: OnceLock = OnceLock::new(); + let skip_activate = *SKIP_ACTIVATE_RAYS.get_or_init(|| { + let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1"); + if builder { + return std::env::var_os("VICTORY_ACTIVATE_RAYS").is_some_and(|v| v == "0"); + } + std::env::var_os("VICTORY_ACTIVATE_RAYS").is_none_or(|v| v == "0") + }); + if skip_activate && named(shaders, b"CS_ScreenProbes_ActivateRays") { + return Some("ray activation shader without BVH, left out"); + } + None +} + +/// Confirmed first-scene producers. Prepare these at creation even on a cold +/// launch so cutscene lighting, tiling, and bakes never miss their first frame. +fn scene_input(shaders: &[Arc]) -> bool { + shaders.iter().any(|s| { + matches!( + s.hash.as_str(), + "970c4fbb3b017c0e" + | "068c90badc86f1fd" + | "e4a7e088c7780ce8" + | "ebe4e53f031f5249" + | "2cc4c197ee29e291" + | "369cbe906ea72764" + ) || crate::draw::BAKE_PIXEL_SHADERS.contains(&s.hash.as_str()) + }) } // SAFETY: D3D12 objects are free-threaded; the graphics state (whose input @@ -59,8 +114,15 @@ impl Pending { key.update(s.hash.as_bytes()); } key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); + let scene_input = scene_input(&shaders); + let screen = (graphics.as_ref().is_some_and(|g| g.screen_pass()) + && shaders.iter().all(|s| s.stage != "mesh")) + || scene_input; + let left_out = left_out(&shaders); Pending { - screen: graphics.as_ref().is_some_and(|g| g.screen_pass()), + screen, + scene_input, + left_out, shaders, graphics, queue_state: AtomicU8::new(NOT_QUEUED), @@ -159,6 +221,9 @@ pub(crate) fn waiting() -> u64 { /// The host pipeline if it is made (or is made within the frame's budget); /// queues it on first use. pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { + if p.left_out.is_some() { + return None; + } // A still-pending pipeline was requested by the title too. Prewarm it // on the next launch, even if this run never got to use it. if !p.used.load(Ordering::Relaxed) && !p.used.swap(true, Ordering::Relaxed) { @@ -174,16 +239,23 @@ pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { /// Makes `p` on this thread if it is not made yet (waiting for a worker /// that is making it); whether it has a host pipeline. pub(crate) fn now(p: &Arc) -> bool { + if p.left_out.is_some() { + return false; + } p.make(); p.made.get().is_some_and(|made| made.is_some()) } /// At the title's creation of a pipeline: starts it at once if an earlier -/// run drew with it (during loading, so the world's first frames find it). +/// run drew with it (during loading, so the world's first frames find it), +/// or if it is a confirmed opening-scene / bake producer. pub(crate) fn early(p: &Arc) { - if !p.shaders.is_empty() && super::library::wanted_early(&p.key) { + if p.left_out.is_some() { + return; + } + if !p.shaders.is_empty() && (p.scene_input || super::library::wanted_early(&p.key)) { super::library::EARLY.fetch_add(1, Ordering::Relaxed); - start(p, EARLY); + start(p, if p.scene_input { REQUESTED } else { EARLY }); } } @@ -400,8 +472,13 @@ fn next(screens_only: bool) -> Arc { /// 64), else two thirds of the logical processors, 2 to 16. They run below the /// title's own threads, and a cold cache queues hundreds at once. fn worker_count(asked: Option, processors: usize) -> usize { + worker_count_for(asked, processors, false) +} + +fn worker_count_for(asked: Option, processors: usize, limited_ram: bool) -> usize { match asked { Some(n) => n.clamp(1, 64), + None if limited_ram => (processors * 3 / 4).clamp(2, 8), None => (processors * 2 / 3).clamp(2, 16), } } @@ -411,11 +488,12 @@ fn workers() -> bool { static RUNNING: OnceLock = OnceLock::new(); *RUNNING.get_or_init(|| { let mut running = false; - let workers = worker_count( + let workers = worker_count_for( std::env::var("VICTORY_PIPELINE_WORKERS") .ok() .and_then(|v| v.trim().parse().ok()), std::thread::available_parallelism().map_or(2, |n| n.get()), + crate::residency::limited_host_ram(), ); tracing::info!(workers, "pipeline workers"); let screens = if screens_first() { SCREEN_WORKERS } else { 0 }; @@ -488,6 +566,10 @@ mod tests { assert_eq!(worker_count(None, 64), 16); assert_eq!(worker_count(Some(0), 24), 1); assert_eq!(worker_count(Some(20), 24), 20); + assert_eq!(worker_count_for(None, 8, true), 6); + assert_eq!(worker_count_for(None, 16, true), 8); + assert_eq!(worker_count_for(None, 24, true), 8); + assert_eq!(worker_count_for(Some(12), 8, true), 12); } /// A first use queues the pipeline and, within the budget, gets the diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index e0cdf0c..61bd6bc 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -519,7 +519,7 @@ pub(crate) fn let_go_idle() { if map.is_empty() { return; } - let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + let idle_ms = crate::host::ram_idle_ms(crate::residency::headroom()); // A list that recorded an upload or a check holds the staging until it // is reset: one only the table holds is named by no list, recorded or // running. @@ -788,6 +788,25 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { } } } + // The video decoder cycles CPU-written linear plane buffers. Keep a + // dedicated per-list upload buffer through the list's GPU fence so + // concurrent frames never overwrite each other or stall on staging hashes. + if staging.movie_plane() { + let (at, len) = staging.memory(); + let footprint = staging.footprints[0].Footprint; + let pitch = footprint.RowPitch as usize; + let bytes = pitch * staging.rows[0] as usize; + let plane = staging.clone(); + let Some(source) = list.plane_upload(bytes as u64, (at, len), move |dst| { + fill_plane(&plane.layout, at, len, dst, bytes, pitch); + }) else { + once!("no upload buffer for a CPU-written movie plane"); + return; + }; + record_upload(list, resource, texture, &staging, &source, 0); + staging.uploaded.store(true, Relaxed); + return; + } // The host texture has the staging buffer's contents: only the check // at submission is left, and what it finds changed the next list that // samples the texture uploads (a frame late where every list of the @@ -807,77 +826,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { }; staging.expected.store(there, Relaxed); } - const COPY_DEST: u32 = 0x400; - // A texture cut from a block may lie where another did: what the card - // holds of that one is done with before the first upload into this one. - if crate::pool::on() && !staging.uploaded.load(Relaxed) { - let aliasing = D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, - Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, - Anonymous: D3D12_RESOURCE_BARRIER_0 { - Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { - pResourceBefore: std::mem::ManuallyDrop::new(None), - // SAFETY: a borrowed pointer the barrier never releases. - pResourceAfter: unsafe { std::mem::transmute_copy(texture) }, - }), - }, - }; - // SAFETY: an open list and a live texture. - unsafe { list.list.ResourceBarrier(&[aliasing]) }; - } - crate::list::ensure_state(list, resource, COPY_DEST); - // The staging buffer lives as long as `staging`, which the deferred - // refresh below holds until the list is reset. - for (i, footprint) in staging.footprints.iter().enumerate() { - #[cfg(feature = "diagnostics")] - { - let f = footprint.Footprint; - // SAFETY: live resources. - let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) }; - let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth); - list.note_read( - || { - format!( - "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", - d.Width, - d.Height, - d.DepthOrArraySize, - d.Format.0, - d.MipLevels, - staging.footprints.len(), - staging.size, - staging.base + footprint.Offset, - f.Width, - f.Height, - f.Depth, - f.RowPitch - ) - }, - (gpu + staging.base + footprint.Offset, len), - ); - } - let to = D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: a borrowed pointer the location never releases. - pResource: unsafe { std::mem::transmute_copy(texture) }, - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: staging.first - staging.level0 + i as u32, - }, - }; - let from = D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: as above. - pResource: unsafe { std::mem::transmute_copy(&staging.buffer) }, - Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { - Offset: staging.base + footprint.Offset, - ..*footprint - }, - }, - }; - // SAFETY: an open list; both locations name live resources. - unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; - } + record_upload(list, resource, texture, &staging, &staging.buffer, staging.base); // When the list is submitted, its copy takes what the staging buffer // holds by then: noted before the check below, which sets `dirty` // again if it detiles (the next list then uploads once more). @@ -921,6 +870,115 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { }); } +fn record_upload( + list: &HostList, + resource: This, + texture: &ID3D12Resource, + staging: &Staging, + source: &ID3D12Resource, + base: u64, +) { + use std::sync::atomic::Ordering::Relaxed; + const COPY_DEST: u32 = 0x400; + // A texture cut from a block may lie where another did: what the card + // holds of that one is done with before the first upload into this one. + if crate::pool::on() && !staging.uploaded.load(Relaxed) { + let aliasing = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::ManuallyDrop::new(None), + // SAFETY: a borrowed pointer the barrier never releases. + pResourceAfter: unsafe { std::mem::transmute_copy(texture) }, + }), + }, + }; + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[aliasing]) }; + } + crate::list::ensure_state(list, resource, COPY_DEST); + // The staging/plane upload buffer lives until the list is reset. + for (i, footprint) in staging.footprints.iter().enumerate() { + #[cfg(feature = "diagnostics")] + { + let f = footprint.Footprint; + // SAFETY: live resources. + let (gpu, d) = unsafe { (source.GetGPUVirtualAddress(), texture.GetDesc()) }; + let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth); + list.note_read( + || { + format!( + "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + d.Width, + d.Height, + d.DepthOrArraySize, + d.Format.0, + d.MipLevels, + staging.footprints.len(), + staging.size, + base + footprint.Offset, + f.Width, + f.Height, + f.Depth, + f.RowPitch + ) + }, + (gpu + base + footprint.Offset, len), + ); + } + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: staging.first - staging.level0 + i as u32, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(source) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: base + footprint.Offset, + ..*footprint + }, + }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } +} + +fn fill_plane( + layout: &victory_formats::texture::Layout, + at: usize, + len: usize, + dst: usize, + bytes: usize, + pitch: usize, +) { + let _pin = crate::watch::title_memory_reading(); + // SAFETY: the list owns this full upload allocation until its GPU work completes. + let out = unsafe { std::slice::from_raw_parts_mut(dst as *mut u8, bytes) }; + let mip = &layout.mips[0]; + if mip.offset == 0 + && mip.pitch as usize * layout.desc.element_bytes as usize == pitch + && bytes <= len + && crate::host::read_into(at as *const _, out) + { + return; + } + with_read(len, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), at as *const u8, len, false); + if let Err(error) = layout.detile(read, 0, 0, out, pitch, bytes) { + out.fill(0); + once!("could not copy the linear plane into the list's upload buffer: {error:?}"); + } + }); +} + /// Levels on demand: the levels a list claimed for its zeros /// (`crate::tiles::Tiled::claim`), held by the list's submission-time /// step. A list that is reset without having been submitted gives the @@ -1169,6 +1227,20 @@ impl Staging { preparing[3].fetch_add(read as u64, Relaxed); } + fn movie_plane(&self) -> bool { + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM; + let desc = &self.layout.desc; + !self.on_demand + && desc.dimension == victory_formats::texture::Dimension::Tex2d + && desc.swizzle.0 == 0 + && desc.depth == 1 + && desc.mips == 1 + && desc.samples == 1 + && self.footprints.len() == 1 + && self.footprints[0].Offset == 0 + && self.footprints[0].Footprint.Format == DXGI_FORMAT_R8_UNORM + } + /// Returns the bytes of title memory read. fn refresh_now(&self) -> usize { let whole = std::time::Instant::now(); diff --git a/crates/victory-gpu/src/texture/ahead.rs b/crates/victory-gpu/src/texture/ahead.rs index 4474435..e71b4e9 100644 --- a/crates/victory-gpu/src/texture/ahead.rs +++ b/crates/victory-gpu/src/texture/ahead.rs @@ -103,7 +103,9 @@ fn claim(resource: This, first: u32, there: u64) -> Option { let way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone())); } - if BYTES.load(Relaxed) >= MOST + let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST }; + if crate::residency::pressured() + || BYTES.load(Relaxed) >= most || copy.flags() & 0x7 != 0 || copy.state.load(Relaxed) != 0 || copy.grown.load(Relaxed) diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 8da3346..0951144 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -517,7 +517,16 @@ fn pump(context: Context, voice: &mut Voice) { return; } while context.field(1, 31, 1) == 1 { - if voice.pcm.len() < SAMPLES_PER_BLOCK && !decode(context, voice) { + // A skipped frame or an input boundary can advance the decoder without + // producing samples. Publish only complete blocks, except the final + // padded tail. Limit empty steps so a broken looping voice cannot hold + // its lock or stall other voices for the whole decoding pass. + for _ in 0..8 { + if voice.pcm.len() >= SAMPLES_PER_BLOCK || !decode(context, voice) { + break; + } + } + if voice.pcm.is_empty() || (voice.pcm.len() < SAMPLES_PER_BLOCK && !voice.ended) { return; } // The write block is the title's too: taken modulo the ring before @@ -549,12 +558,21 @@ fn pump(context: Context, voice: &mut Voice) { /// Decodes the next frame of the current input into `voice.pcm`; false /// when there is nothing left to decode. fn decode(context: Context, voice: &mut Voice) -> bool { + let valid = context.field(0, 20, 2); if voice.ended { - return false; + // The title can refill either input while the context stays enabled. + // Flush the previous tail once and leave the ring idle until a valid + // buffer is published. The decoder resets its overlap when flushed. + if valid == 0 { + return false; + } + voice.ended = false; + if context.field(2, 26, 5) == INPUT_INVALID { + context.set_field(2, 26, 6, 0); + } } let channels = context.channels(); let mut current = context.field(4, 31, 1); - let valid = context.field(0, 20, 2); if valid & (1 << current) == 0 { if valid & (1 << (1 - current)) == 0 { // Out of input: the overlap tail, then nothing. diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1dc305a..7f3b8f7 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -423,6 +423,7 @@ enum MaskData { /// What a value holding a lane mask read as a number stops with. pub(super) const LANE_MASK: Why = "a lane mask read as data"; +pub(super) const DIVERGENT_MASK_EXCHANGE: Why = "a lane mask exchanged where not every lane runs"; /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that /// run that block are not all of the wave. pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; @@ -546,7 +547,7 @@ fn need(block: usize) { /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. /// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes /// run (no lane branch can have split the arriving lanes); loop-carried values never do. -fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { +fn lane_uniform(p: &Program, st: &Structured, all: &[bool], ordered_lds: bool) -> HashSet { let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); let mut same: HashSet = HashSet::new(); for b in crate::ir::reverse_postorder(&p.blocks) { @@ -559,6 +560,9 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { } for (i, inst) in block.insts.iter().enumerate() { let name = inst.name(); + if st.guards[b][i].is_some() { + continue; // lanes outside EXEC keep another value + } let ops: Vec = match &inst.fields { Fields::Valu(v) if v.dpp.is_none() @@ -569,11 +573,18 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { { v.src.clone() } + Fields::Ds { + addr: Some(Operand::Vector { reg, dwords: 1 }), + gds: false, + .. + } if ordered_lds && name == "ds_read_b32" => { + if inst.read(Reg::V(*reg)).is_some_and(|a| same.contains(&a)) { + same.extend(inst.writes.iter().map(|w| w.1)); + } + continue; + } _ => continue, }; - if st.guards[b][i].is_some() { - continue; // lanes outside EXEC keep another value - } let alike = ops.iter().all(|op| match *op { Operand::Vector { reg, .. } => { // every dword of the operand the instruction reads from that register on @@ -1175,6 +1186,13 @@ thread_local! { } pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { + // A scalar select uses the condition of the whole guest wave, even + // when the preceding mask operation has no scalar-dword consumers. + if matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_)) + && i.read(Reg::Scc).is_some_and(|s| st.scc_some.contains_key(&s)) + { + return true; + } let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); let ops: Vec<&Operand> = match &i.fields { // A mask operation (its result a mask) is no data use. @@ -1678,7 +1696,9 @@ impl<'a> Lower<'a> { local_ok: false, local_any: LOCAL_ANY.get(), uniform: match &exchange { - Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all), + Some((_, false, all)) if !LOCAL_WAVES.get() => { + lane_uniform(p, x.st, all, split_lds && super::group_sync() != 0) + } _ => HashSet::new(), }, own_bits: match &exchange { @@ -3526,7 +3546,7 @@ impl<'a> Lower<'a> { } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) { // (a group of 32 or fewer has no other half to exchange with) need(b.unwrap_or(0)); - return Err("a lane mask exchanged where not every lane runs"); + return Err(DIVERGENT_MASK_EXCHANGE); } xy = self.exchange_halves(at, xy.0); } @@ -4227,7 +4247,7 @@ impl<'a> Lower<'a> { } if !made.is_none_or(|b| self.all_lanes(b)) { need(made.unwrap_or(0)); - return Err("a lane mask exchanged where not every lane runs"); + return Err(DIVERGENT_MASK_EXCHANGE); } let some = self.s.m.cast(at, Cast::ZExt, some, i32t); let (lo, hi) = self.exchange_halves(at, some); @@ -6026,6 +6046,13 @@ impl<'a> Lower<'a> { fn scc_in(&mut self, inst: &Inst) -> Result { let v = inst.read(Reg::Scc).ok_or("an unread SCC")?; + if self.x.st.scc_some.contains_key(&v) + && matches!(self.vals.get(&v), None | Some(Val::Missing(_))) + { + let x = self.scc_some(v)?; + self.vals.insert(v, Val::Bit(x)); + return Ok(x); + } match self.get(v) { Ok(Val::Bit(x)) => Ok(x), Ok(_) => Err("SCC without a value"), @@ -7694,6 +7721,15 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); + if let Some(&source) = self.x.res.restored_lanes.get(&(b, i)) { + // This lane was overwritten by a uniform scalar. The previous + // contents of other lanes can be unknown (a reduction scratch). + let word = match source { + crate::resource::Moved::Value(v) => self.i32_of(v)?, + crate::resource::Moved::Const(k) => self.s.m.i32(k), + }; + return self.write_i(inst, word, None); + } if self.x.res.waterfall.compares.contains(&(b, i)) { // The first lane's dwords of a waterfall loop are each lane's // own (see `resource::Waterfall`). diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index baf9226..356bc49 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -511,7 +511,24 @@ pub fn emit( // lost the card in a submission of two programs that had just moved to it // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which // has no barrier, stays on. - let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1"); + let wide_option = std::env::var_os("VICTORY_WAVE_WIDE"); + // Both archived kernels use one logical wave per group and have + // validated wave32 PSOs on RTX. Explicit policy wins. + let scene_kernel = matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::() == 64) + && matches!( + c.digest, + [0x58, 0x1d, 0xab, 0x2c, 0xd8, 0xbc, 0xf2, 0x2e, 0x5c, 0x96, 0x4b, 0x98, 0xe9, 0x03, 0x48, 0xd1] + | [0x24, 0x31, 0xbb, 0xe7, 0xdc, 0x15, 0x4a, 0xd7, 0x59, 0xd2, 0x0b, 0xc9, 0x54, 0x82, 0x9c, 0x1c] + ); + let wide_on = wide_option.as_ref().map_or(scene_kernel, |v| v == "1"); + // A single guest wave can iterate an active-lane loop until both host + // halves have finished. The precise latch and convergence conditions + // for the driver compute route are checked by widen(). + let driver_loop = wide_option.is_none() + && c.part(FourCC::DXIL).is_none() + && c.part(FourCC::ACCC).is_some() + && matches!(&original, Err(ShaderError::Unsupported { what, .. }) + if *what == lower::DIVERGENT_MASK_EXCHANGE); // exact first: each host wave on its own where that is exact (the idiom, every // form; no barriers), then the other exact forms; then approximate for exact in [true, false] { @@ -533,7 +550,7 @@ pub fn emit( // Still stopped where not every lane runs: the per-lane branches around // those places taken as the console takes them, by the whole wave at once // ([`widen`]), at two group barriers per such branch. - if wide_on { + if wide_on || driver_loop { let bases = [ deep.as_ref().map(|f| &f.0), forms[1].1.as_ref().map(|f| &f.0), @@ -541,7 +558,7 @@ pub fn emit( Some(p), ]; if let Some(base) = bases.into_iter().flatten().next() { - let again = widen(c, native, base, why); + let again = widen(c, native, base, why, driver_loop); report("wave-wide branches", &again); if done(&again) { return again.map(|(shader, _)| shader); @@ -603,7 +620,7 @@ pub fn emit( && what == lower::LANE_MASK && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") => { - let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some()); + let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some(), false); match again { Ok(_) => again, Err(_) => emit_program(c, native, p, st, io, res), @@ -611,7 +628,17 @@ pub fn emit( } other => other, }; - let original = original.map(|(shader, _)| shader); + let supported = |(shader, wave): (HostShader, Option)| { + if wave == Some(64) && lower::host_max_wave() == 32 { + Err(ShaderError::Unsupported { + offset: 0, + what: "no wave32 lowering for this wave64 program", + }) + } else { + Ok(shader) + } + }; + let original = original.and_then(supported); // Retry unsupported programs only. Threading can separate an unknown // register value from its apparent use on a mutually exclusive path. if !matches!(original, Err(ShaderError::Unsupported { .. })) { @@ -625,7 +652,7 @@ pub fn emit( let st = structure::structure(&p)?; let io = io::raise(&p, native)?; let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) + emit_program(c, native, &p, &st, &io, &res).and_then(supported) } /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane @@ -640,6 +667,7 @@ fn widen( native: &NativeProgram, p: &ir::Program, why: bool, + active_loop_only: bool, ) -> Result<(HostShader, Option), ShaderError> { const NOT: ShaderError = ShaderError::Unsupported { offset: 0, @@ -687,6 +715,30 @@ fn widen( } return r; } + if active_loop_only { + // Only a single backward branch on the SCC just set by + // s_andn2_wrexec_b64. This instruction restricts EXEC to the + // unfinished lanes. The guest repeats the loop if *either* + // half still has work, while individual vector writes retain + // their EXEC predicates. + let [latch] = more.as_slice() else { + return r; + }; + let block = &p.blocks[*latch]; + let [.., update, branch] = block.insts.as_slice() else { + return r; + }; + if !wide.is_empty() + || update.name() != "s_andn2_wrexec_b64" + || branch.name() != "s_cbranch_scc1" + || !matches!( + block.exit, + ir::Exit::Branch { taken, not_taken } if taken <= *latch && not_taken > *latch + ) + { + return r; + } + } wide.extend(more); } } diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 835c067..6b7f861 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -138,6 +138,9 @@ pub struct RootIndexedView { #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Resources { + /// Scalar values saved to a constant VGPR lane and restored within one + /// block, even if that VGPR is also used in ordinary vector operations. + pub(crate) restored_lanes: std::collections::HashMap, /// Every scalar memory access by address (`s_load_*`, `s_store_*`), and /// every global memory access (`global_*`, the dynamic term per lane). pub scalar: Vec<(Site, Address)>, @@ -227,6 +230,9 @@ pub fn track( t.at.set(Some(b)); for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); + if let Some(value) = t.restored(inst, Some(b)) { + out.restored_lanes.insert(site, value); + } let fail = |what| ShaderError::Unsupported { offset: inst.machine.offset, what, @@ -514,7 +520,7 @@ impl<'a> Tracer<'a> { } for inst in &block.insts { for (k, &(_, v)) in inst.writes.iter().enumerate() { - let new = match copy_source(inst, k).or_else(|| self.restored(inst)) { + let new = match copy_source(inst, k).or_else(|| self.restored(inst, None)) { Some(Moved::Const(c)) => Some(Term::Const(c)), Some(Moved::Value(s)) => o[s.0 as usize], None => Some(Term::Value(v)), @@ -2292,41 +2298,64 @@ impl<'a> Tracer<'a> { } } -#[derive(Clone, Copy, PartialEq, Eq)] -enum Moved { +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Moved { Const(u32), Value(Value), } +fn plain_lane(v: &crate::gfx10::Valu) -> bool { + v.abs == 0 + && v.neg == 0 + && v.opsel == 0 + && !v.clamp + && v.omod == 0 + && v.sdwa.is_none() + && v.dpp.is_none() +} + impl Tracer<'_> { /// For `v_readlane_b32` of a constant lane: the SGPR spilled to that /// lane, found by following the VGPR's `v_writelane_b32` writes. - fn restored(&self, inst: &Inst) -> Option { + fn restored(&self, inst: &Inst, block: Option) -> Option { let Fields::Valu(v) = &inst.fields else { return None; }; - if inst.name() != "v_readlane_b32" { + if inst.name() != "v_readlane_b32" || !plain_lane(v) { return None; } let [Operand::Vector { reg, .. }, lane] = v.src[..] else { return None; }; - self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new()) + let lane = lane_of(lane)?; + if lane >= if self.p.wave64 { 64 } else { 32 } { + return None; + } + self.spilled(inst.read(Reg::V(reg))?, lane, block, &mut Vec::new()) .ok() .flatten() } /// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in /// `seen` (already being resolved), `Err` if not a spilled SGPR. - fn spilled(&self, v: Value, lane: u32, seen: &mut Vec) -> Result, ()> { + fn spilled( + &self, + v: Value, + lane: u32, + block: Option, + seen: &mut Vec, + ) -> Result, ()> { if let Some((b, i)) = self.phis[v.0 as usize] { + if block.is_some() { + return Err(()); + } if seen.contains(&v) { return Ok(None); } seen.push(v); let mut found = None; for &a in &self.p.blocks[b].phis[i].args { - if let Some(m) = self.spilled(a, lane, seen)? { + if let Some(m) = self.spilled(a, lane, block, seen)? { if found.is_some_and(|f| f != m) { return Err(()); } @@ -2335,18 +2364,26 @@ impl Tracer<'_> { } return Ok(found); } - let inst = self.def(v).ok_or(())?; + let site = self.defs[v.0 as usize].ok_or(())?; + if block.is_some_and(|b| site.0 != b) { + return Err(()); + } + let inst = self.inst(site); let Fields::Valu(w) = &inst.fields else { return Err(()); }; let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else { return Err(()); }; - if inst.name() != "v_writelane_b32" { + if inst.name() != "v_writelane_b32" || !plain_lane(w) { return Err(()); } - if lane_of(*at).ok_or(())? != lane { - return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen); + let written = lane_of(*at).ok_or(())?; + if written >= if self.p.wave64 { 64 } else { 32 } { + return Err(()); + } + if written != lane { + return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, block, seen); } match *value { Operand::Scalar { code, .. } if code != NULL => {