From bbf3c1b27cda8c65020ac87a1e7697174354ee66 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 15:46:48 +0000 Subject: [PATCH 01/11] watch: under Wine, ask about whole allocations, cached (re-port #47) Under Wine each GetWriteWatch costs about 1 ms whatever the range (contention on Wine's virtual-memory lock with the title's write faults). Allocations are walked once and cached by base, a watched allocation is asked about whole so the submission's other buffers in it answer from the journal, and file views (xmem's physical pages) skip the watch question entirely and go straight to their guards. Region entries drop on remap, rewrite and failed whole askings. Re-applied onto the round-2 watch: known_view composes with the mapped shortcut, guard() takes the known_mapped hint as in the original port. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/watch.rs | 248 +++++++++++++++++++++++++------- 1 file changed, 194 insertions(+), 54 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 12d1998..6276eb2 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -81,6 +81,113 @@ static JOURNAL: Mutex = Mutex::new(Journal { kept: false, }); +/// Whether we run under Wine (its ntdll exports `wine_get_version`). +fn on_wine() -> bool { + static WINE: std::sync::LazyLock = std::sync::LazyLock::new(|| { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + // SAFETY: plain lookups in ntdll, always loaded. + unsafe { + let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); + !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() + } + }); + *WINE +} + +/// A title allocation as Wine reports it, in [`PAGE`] units. +#[derive(Clone, Copy)] +struct Region { + /// The allocation base, for dropping stale entries. + base: usize, + first: usize, + last: usize, + /// A file view (xmem's physical pages): not write-watched. + mapped: bool, + /// Small enough (4 GiB at most) to be asked about whole. + whole: bool, +} + +/// Allocations seen by [`allocation`], by first page. Remaps (xmem's views) +/// and failed askings drop entries. +static REGIONS: Mutex> = Mutex::new(BTreeMap::new()); + +fn forget_region(base: usize) { + REGIONS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|_, r| r.base != base); +} + +/// The allocation holding `at`, cached by allocation base (walking an +/// allocation's regions under Wine costs one VirtualQuery each). Those +/// above 4 GiB are not asked about whole. +fn allocation(at: usize) -> Option { + use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery}; + let page = at / PAGE; + // Known allocations first: under Wine VirtualQuery takes the same lock + // the title's write faults do. + if let Some((_, &r)) = REGIONS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .range(..=page) + .next_back() + && page < r.last + { + return Some(r); + } + let query = |p: usize| { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + (n != 0).then_some(info) + }; + let info = query(at)?; + let base = info.AllocationBase as usize; + if base == 0 { + return None; + } + // Walk the allocation's regions (Wine splits it by protection, one + // region per run of pages); a long walk stops, and the allocation is + // then only remembered as far as it went, never asked about whole. + let mut end = base; + let mut done = false; + for _ in 0..256 { + let Some(i) = query(end) else { + done = true; + break; + }; + if i.AllocationBase as usize != base { + done = true; + break; + } + end = i.BaseAddress as usize + i.RegionSize; + } + if !done { + // At least past `at`, so the next asking here is a cache hit. + end = end.max((at / PAGE + 1) * PAGE).max(at + (256 << 20)); + } + if end <= at { + return None; + } + let r = Region { + base, + first: base.div_ceil(PAGE), + last: end / PAGE, + mapped: info.Type == MEM_MAPPED, + whole: done && end - base <= (4usize << 30), + }; + if r.first * PAGE > at || r.last <= r.first { + return None; + } + let mut regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + // An allocation that replaced older ones in its range. + regions.retain(|_, o| o.last <= r.first || o.first >= r.last); + regions.insert(r.first, r); + Some(r) +} + + /// Ranges of one submission closer than this are asked about together: /// walking the pages between them costs less than another kernel call (a /// call that resets written pages costs 30-70 microseconds whatever the @@ -400,27 +507,57 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve .collect(), )); } - let mut count = (last - first) * PAGE / KERNEL_PAGE; - j.found.resize(count.max(j.found.len()), 0); - let mut granularity = 0; + // Under Wine: view memory cannot be watched (straight to its guards), + // and watched memory is asked about whole allocations at a time, so the + // other buffers in one are answered from the journal for the rest of + // the submission — one GetWriteWatch costs about 1 ms there whatever + // the range (contention on Wine's virtual-memory lock with the title's + // write faults), and the world's copies ask about the same big buffers + // dozens of times per submission. + let region = if on_wine() { allocation(start) } else { None }; + let mapped = region.is_some_and(|r| r.mapped); + let (kfirst, klast) = match region { + Some(r) if !r.mapped && r.whole && r.first <= first && last <= r.last => (r.first, r.last), + _ => (first, last), + }; #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); // View memory the guards already hold cannot be write-watched: the // kernel asking would only fail. Copies of it are flushed many times a // frame, each time paying that failed call before the guards answer. - let known_view = guarded && known_view(first * PAGE); - // SAFETY: the answer buffer holds `count` entries. - let failed = known_view - || unsafe { + let known_view = (guarded && known_view(first * PAGE)) || mapped; + let mut granularity = 0; + let mut ask = |j: &mut Journal, kfirst: usize, klast: usize| -> Option { + let mut count = (klast - kfirst) * PAGE / KERNEL_PAGE; + j.found.resize(count.max(j.found.len()), 0); + // SAFETY: the answer buffer holds `count` entries. + let ok = unsafe { GetWriteWatch( WRITE_WATCH_FLAG_RESET, - (first * PAGE) as *const _, - (last - first) * PAGE, + (kfirst * PAGE) as *const _, + (klast - kfirst) * PAGE, j.found.as_mut_ptr().cast(), &mut count, &mut granularity, ) - } != 0; + } == 0; + ok.then_some(count) + }; + let mut answer = if known_view { + None + } else { + ask(j, kfirst, klast) + }; + if answer.is_none() && !known_view && (kfirst, klast) != (first, last) { + // The allocation was not one watched range after all (or is gone): + // just ours, and look it up again next time. + if let Some(r) = region { + forget_region(r.base); + } + answer = ask(j, first, last); + } + let mut count = answer.unwrap_or(0); + let failed = answer.is_none(); #[cfg(feature = "diagnostics")] crate::copystat::add( if known_view { @@ -437,7 +574,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve } #[cfg(feature = "diagnostics")] let guarding = std::time::Instant::now(); - let written = guard(first * PAGE, last * PAGE); + let written = guard(first * PAGE, last * PAGE, mapped); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64); written? @@ -574,7 +711,7 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { /// For view memory: the pages of `[start, end)`'s blocks written since /// they were last guarded (all of a block's pages), guarding them again /// before the caller copies them. `None` if the memory is not a view. -fn guard(start: usize, end: usize) -> Option> { +fn guard(start: usize, end: usize, known_mapped: bool) -> Option> { // A range whose first block the guards hold already (read-only by our // hand, or noted absent) is a view: no question to Windows. The // question walks the page tables to the end of the pages that share the @@ -583,11 +720,12 @@ fn guard(start: usize, end: usize) -> Option> { // of the 68 ms a frame of "guards" (run 58). // `VICTORY_GUARD_ASK=1` asks every time, as before. static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); - let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { - let g = guards(); - let first = start / BLOCK; - g.protected.contains(&first) || g.absent.contains(&first) || (view_known() && g.viewed.contains(&first)) - }; + let known = known_mapped + || !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { + let g = guards(); + let first = start / BLOCK; + g.protected.contains(&first) || g.absent.contains(&first) || (view_known() && g.viewed.contains(&first)) + }; if !known && !is_view(start, end) { return None; } @@ -860,6 +998,7 @@ fn open_here(g: &mut Guards, start: usize, end: usize) -> bool { pub fn writing(at: usize, len: usize) { // The length is the title's (`fread`'s size times count, saturated). open(&mut guards(), at, at.saturating_add(len)); + forget_region(at); // A placed texture there changes with no descriptor written. crate::descriptor::host::remapped(at, len); } @@ -1026,6 +1165,7 @@ pub fn title_memory_reading_now() -> Option { /// shows is new and read-write, so it is no longer guarded (nor known /// unmapped). pub fn title_memory_remapped(at: usize, len: usize) { + REGIONS.lock().unwrap_or_else(|e| e.into_inner()).clear(); // A placed texture there arrives, goes or changes with no descriptor // written. crate::descriptor::host::remapped(at, len); @@ -1175,7 +1315,7 @@ mod tests { MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize }; assert_ne!(view, 0); - assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only + assert!(guard(view, view + 2 * BLOCK, false).is_some()); // now read-only let mut file = tempfile::tempfile().unwrap(); file.write_all(b"from the disk").unwrap(); // `ReadFile` inside: the kernel writes the view. @@ -1195,7 +1335,7 @@ mod tests { let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }; assert_eq!(landed, b"from the disk"); assert_eq!( - guard(view, view + 2 * BLOCK), + guard(view, view + 2 * BLOCK, false), Some((view / PAGE..view / PAGE + 1).collect()) ); // SAFETY: our view. @@ -1253,7 +1393,7 @@ mod tests { let late = start + 2 * BLOCK + 3 * KERNEL_PAGE; commit(start, BLOCK); commit(early, KERNEL_PAGE); - let refresh = || guard(start, start + SIZE).unwrap(); + let refresh = || guard(start, start + SIZE, false).unwrap(); assert_eq!(refresh(), [start / PAGE, early / PAGE, late / PAGE]); // The last block is still entirely reserved. assert!(!refresh().contains(&(late / PAGE))); @@ -1334,15 +1474,15 @@ mod tests { title_memory_remapped(p + BLOCK, BLOCK); // The range begins in the placeholder, its middle block is a view. assert!(is_view(p, p + 3 * BLOCK)); - assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); - assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since"); + assert_eq!(guard(p, p + 3 * BLOCK, false), Some(all)); + assert_eq!(guard(p, p + 3 * BLOCK, false), Some(Vec::new()), "nothing written since"); // SAFETY: inside the mapped middle block. unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) }; - assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); + assert_eq!(guard(p, p + 3 * BLOCK, false), Some(pages(1).collect())); let first = map(0); title_memory_remapped(p, BLOCK); - assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(0).collect())); - assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + assert_eq!(guard(p, p + 3 * BLOCK, false), Some(pages(0).collect())); + assert_eq!(guard(p, p + 3 * BLOCK, false), Some(Vec::new())); // Memory of ours that is no view stays none. let mut local = [0u8; 16]; let at = local.as_mut_ptr() as usize; @@ -1421,16 +1561,16 @@ mod tests { let first = map(0); let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; let all: Vec = (0..3).flat_map(pages).collect(); - assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); + assert_eq!(guard(p, p + 3 * BLOCK, false), Some(all)); assert_eq!( - guard(p, p + 3 * BLOCK), + guard(p, p + 3 * BLOCK, false), Some(Vec::new()), "nothing written since" ); let second = map(1); title_memory_remapped(p + BLOCK, BLOCK); - assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); - assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + assert_eq!(guard(p, p + 3 * BLOCK, false), Some(pages(1).collect())); + assert_eq!(guard(p, p + 3 * BLOCK, false), Some(Vec::new())); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -1500,14 +1640,14 @@ mod tests { let (section, guarded, other) = two_views(SIZE); let pages = |block: usize| (guarded + block * BLOCK) / PAGE; // The first check takes it in (and every view of its pages). - assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); - assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(Vec::new()), "nothing written yet"); // Writing through the other view faults into the handler, which // opens that view and the guarded one: the next check sees it. // SAFETY: the second view, read-write once the handler has opened it. unsafe { ((other + BLOCK + 8) as *mut u8).write(1) }; - assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)])); - assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(Vec::new())); drop_views(section, &[guarded, other], SIZE); } @@ -1518,12 +1658,12 @@ mod tests { const SIZE: usize = 2 * BLOCK; let (section, guarded, other) = two_views(SIZE); let pages = |block: usize| (guarded + block * BLOCK) / PAGE; - assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); - assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(Vec::new()), "nothing written yet"); title_memory_remapped(other, SIZE); crate::inplace::title_memory_view(other, SIZE, section, 0); - assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); - assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(Vec::new())); drop_views(section, &[guarded, other], SIZE); } @@ -1534,14 +1674,14 @@ mod tests { const SIZE: usize = 2 * BLOCK; let (section, guarded, other) = two_views(SIZE); let pages = |block: usize| (guarded + block * BLOCK) / PAGE; - assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); - assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(Vec::new()), "nothing written yet"); writing(other + BLOCK, BLOCK); - assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)])); - assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(Vec::new())); // Half a page and the next: both blocks, not just the first's. writing(other + BLOCK / 2, BLOCK); - assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(0), pages(1)])); drop_views(section, &[guarded, other], SIZE); } @@ -1556,20 +1696,20 @@ mod tests { const SIZE: usize = 2 * BLOCK; let (section, one, two) = two_views(SIZE); let pages = |view: usize, block: usize| (view + block * BLOCK) / PAGE; - assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0), pages(one, 1)])); - assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0), pages(two, 1)]), "the second view's first check"); - assert_eq!(guard(one, one + SIZE), Some(Vec::new()), "nothing written yet"); - assert_eq!(guard(two, two + SIZE), Some(Vec::new()), "nothing written yet"); + assert_eq!(guard(one, one + SIZE, false), Some(vec![pages(one, 0), pages(one, 1)])); + assert_eq!(guard(two, two + SIZE, false), Some(vec![pages(two, 0), pages(two, 1)]), "the second view's first check"); + assert_eq!(guard(one, one + SIZE, false), Some(Vec::new()), "nothing written yet"); + assert_eq!(guard(two, two + SIZE, false), Some(Vec::new()), "nothing written yet"); // SAFETY: the second view, read-write once the handler has opened it. unsafe { ((two + BLOCK + 8) as *mut u8).write(1) }; - assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 1)])); - assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 1)]), "written through this view, checked second"); + assert_eq!(guard(one, one + SIZE, false), Some(vec![pages(one, 1)])); + assert_eq!(guard(two, two + SIZE, false), Some(vec![pages(two, 1)]), "written through this view, checked second"); // SAFETY: the first view, as above. unsafe { ((one + 8) as *mut u8).write(1) }; - assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0)])); - assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0)]), "written through this view, checked second"); - assert_eq!(guard(one, one + SIZE), Some(Vec::new())); - assert_eq!(guard(two, two + SIZE), Some(Vec::new())); + assert_eq!(guard(two, two + SIZE, false), Some(vec![pages(two, 0)])); + assert_eq!(guard(one, one + SIZE, false), Some(vec![pages(one, 0)]), "written through this view, checked second"); + assert_eq!(guard(one, one + SIZE, false), Some(Vec::new())); + assert_eq!(guard(two, two + SIZE, false), Some(Vec::new())); drop_views(section, &[one, two], SIZE); } @@ -1582,11 +1722,11 @@ mod tests { for n in 0..MANY_VIEWS { crate::inplace::title_memory_view(filler + n * BLOCK, BLOCK, section, 0); } - assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE])); + assert_eq!(guard(one, one + BLOCK, false), Some(vec![one / PAGE])); assert!(writable(two), "another view of it is left alone"); // SAFETY: the guarded view, opened by the handler. unsafe { ((one + 8) as *mut u8).write(1) }; - assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE])); + assert_eq!(guard(one, one + BLOCK, false), Some(vec![one / PAGE])); title_memory_remapped(filler, MANY_VIEWS * BLOCK); drop_views(section, &[one, two], BLOCK); } From 0e4a9ef721e1ca5dca38d474ae1e9aaedb59a217 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 15:47:36 +0000 Subject: [PATCH 02/11] gpu: a failed cache write does not drop the translated shader The disk error path returned the translation as an error, and Shader::translated remembers failures for the rest of the run: a full or read-only cache directory cost every draw of the program. The shader is now returned uncached (the same work the converter just did). Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/shader_cache.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 9e06221..1cea1a4 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -147,9 +147,18 @@ fn cached( ran: AtomicBool::new(false), }; for _ in 0..2 { - let path = cache - .get_or_convert(&converter, &input) - .map_err(|e| format!("{e:#}"))?; + let path = match cache.get_or_convert(&converter, &input) { + Ok(path) => path, + Err(e) => { + // A cache that cannot write (a full or read-only disk) must + // not cost the shader: the translation is the same work the + // converter just did, returned uncached instead of dropping + // every draw of the program for the rest of the run. + tracing::debug!("shader cache write failed ({e:#}); the shader is not cached"); + MISSES.fetch_add(1, Ordering::Relaxed); + return (converter.translate)(container); + } + }; if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) { let (counter, what) = if converter.ran.load(Ordering::Relaxed) { (&MISSES, "translated and cached") From 6a02d65a508085fdc16fd3b9b87b4d22e0361932 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 15:49:00 +0000 Subject: [PATCH 03/11] gpu: warm up in the host's mesh mode; stop scanning past the warm deadline Warm-up wrote only native-mesh cache entries while emulation hardware keys by the emulation mode, so mesh programs still translated on first use there. The mode now follows the machine's mesh support. And once VICTORY_WARM_SECONDS expires, the walk stops opening assets instead of scanning every remaining one for workers that break out at once. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/victory/src/translate.rs | 5 +++++ crates/victory-gpu/src/shader_cache.rs | 12 ++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index bb0835d..d791bb2 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -200,6 +200,11 @@ pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { continue; } + // Past the deadline the workers break out at once: opening and + // reading the rest of the assets would only scan for nothing. + if limit.is_some_and(|n| began.elapsed().as_secs() >= n) { + break; + } let Ok(data) = std::fs::read(entry.path()) else { continue; }; diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 1cea1a4..ae8307c 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -88,11 +88,19 @@ fn build() -> [u8; 32] { pub fn warm(container: &[u8]) -> Result { let cache = CACHE.get().ok_or("no shader cache")?; let ran = AtomicBool::new(false); + // The mode the runtime translates with on this machine: an emulated + // mesh shader's cache entry is another key than the native one's, so a + // warm-up in only the native mode left emulation hardware (no mesh + // shader support) to translate every mesh program on first use. + let mesh = match crate::host::host() { + Some(h) if h.emulate_mesh_shaders() => MeshMode::Emulate, + _ => MeshMode::Native, + }; let translate = |c: &[u8]| { ran.store(true, Ordering::Relaxed); - victory_shader::emit::translate(c).map_err(|e| e.to_string()) + victory_shader::emit::translate_with(c, mesh).map_err(|e| e.to_string()) }; - cached(cache, &build(), MeshMode::Native, container, translate).map(|_| ran.load(Ordering::Relaxed)) + cached(cache, &build(), mesh, container, translate).map(|_| ran.load(Ordering::Relaxed)) } /// The translation of a console shader container, from the cache when From 4df9fdada80e0fad2477d5a882ce695e72bcd41c Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 15:51:13 +0000 Subject: [PATCH 04/11] watch: a whole-asked allocation answers from the journal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit writes never marked the allocation as covered, so even disjoint buffers in one watched allocation repeated the whole scan once a flush each — under Wine, about 1 ms a scan. The covered range joins the submission's ahead askings; the coverage ends with the submission as the batch's does. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/watch.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 6276eb2..17d30ea 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -594,6 +594,13 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve for page in pages.collect::>() { j.written.insert(page, now); } + if answer.is_some() && (kfirst, klast) != (first, last) { + // A whole allocation asked: its other buffers answer from the + // journal for the rest of the submission instead of scanning it + // whole once a flush each (under Wine, about 1 ms a scan). + j.ahead.push((kfirst, klast)); + j.ahead_asked = now; + } Some(( now, j.written From 2b3ab3446a89142c54e02883ca4c6331f47f0e5c Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 15:51:55 +0000 Subject: [PATCH 05/11] watch: region cache correctness: unverified walks, interior writes, ask switches An entry the region walk did not complete no longer types unverified pages as file views; a write into the middle of an allocation drops its entry (not only one at the base); and the mapped shortcut honors VICTORY_VIEW_ASK/VICTORY_GUARD_ASK like the guards' own fast paths. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/watch.rs | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 17d30ea..75b09a0 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -111,11 +111,14 @@ struct Region { /// and failed askings drop entries. static REGIONS: Mutex> = Mutex::new(BTreeMap::new()); -fn forget_region(base: usize) { +fn forget_region(at: usize) { + // Interior writes count as much as ones at the base: any entry covering + // the write is stale. + let page = at / PAGE; REGIONS .lock() .unwrap_or_else(|e| e.into_inner()) - .retain(|_, r| r.base != base); + .retain(|_, r| !(r.first <= page && page < r.last)); } /// The allocation holding `at`, cached by allocation base (walking an @@ -174,7 +177,9 @@ fn allocation(at: usize) -> Option { base, first: base.div_ceil(PAGE), last: end / PAGE, - mapped: info.Type == MEM_MAPPED, + // An entry the walk did not complete covers unverified pages: + // they are not one memory type, so nothing is skipped for them. + mapped: done && info.Type == MEM_MAPPED, whole: done && end - base <= (4usize << 30), }; if r.first * PAGE > at || r.last <= r.first { @@ -515,7 +520,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve // write faults), and the world's copies ask about the same big buffers // dozens of times per submission. let region = if on_wine() { allocation(start) } else { None }; - let mapped = region.is_some_and(|r| r.mapped); + let mapped = region.is_some_and(|r| r.mapped) && !ask_anyway(); let (kfirst, klast) = match region { Some(r) if !r.mapped && r.whole && r.first <= first && last <= r.last => (r.first, r.last), _ => (first, last), @@ -649,6 +654,18 @@ impl Tracked { /// Guarded blocks of view memory. const BLOCK: usize = PAGE; + +/// Whether the diagnostic switches ask the kernel even for memory known to +/// be unwatchable (`VICTORY_VIEW_ASK=1` or `VICTORY_GUARD_ASK=1`). +fn ask_anyway() -> bool { + static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); + *ASK.get_or_init(|| { + ["VICTORY_VIEW_ASK", "VICTORY_GUARD_ASK"] + .iter() + .any(|n| std::env::var_os(n).is_some_and(|v| v == "1")) + }) +} + /// Whether the block holding `start` is view memory the guards already /// hold (read-only by our hand, or noted absent): asking the kernel's write /// watch about it can only fail. `VICTORY_VIEW_ASK=1` (or @@ -727,7 +744,7 @@ fn guard(start: usize, end: usize, known_mapped: bool) -> Option> { // of the 68 ms a frame of "guards" (run 58). // `VICTORY_GUARD_ASK=1` asks every time, as before. static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); - let known = known_mapped + let known = (known_mapped && !ask_anyway()) || !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { let g = guards(); let first = start / BLOCK; From b60cb657c7f22051a8ef0ce06a4f1e8ece1f6317 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 15:53:34 +0000 Subject: [PATCH 06/11] GPU: skip pipeline demand for empty compute dispatches Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/draw.rs | 5 ++++ crates/victory-gpu/src/pipeline/make.rs | 36 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 461ba95..9ece2e9 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2191,6 +2191,11 @@ impl State { /// Runs a dispatch on the host. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) { + // A zero-sized grid has no shader work: do not demand or wait for + // its pipeline. + if x == 0 || y == 0 || z == 0 { + return; + } // It may write the arguments a window holds clamped. self.window = None; #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index b21b716..199c495 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -397,4 +397,40 @@ mod tests { assert!(Arc::ptr_eq(&queue.pop().unwrap(), &earlier)); assert!(queue.pop().is_none()); } + + #[test] + fn zero_group_dispatches_do_not_request_a_pipeline() { + use crate::object::{S_OK, slot}; + + let Some(host) = crate::host::host() else { + return; + }; + let list = host.new_list().unwrap(); + // A pending pipeline that cannot translate makes any accidental + // demand observable without depending on a shader's build time. + let mut title = std::ptr::null(); + assert_eq!( + crate::pipeline::hand_out( + Vec::new(), + None, + &crate::pipeline::PIPELINE_IIDS[0], + &mut title, + ), + S_OK + ); + let pending = &crate::pipeline::pipeline(title).host; + let mut state = crate::draw::State::default(); + state.set_pipeline(title); + let zero_demands = [(0, 1, 1), (1, 0, 1), (1, 1, 0)].map(|(x, y, z)| { + state.dispatch(&list, x, y, z); + pending.used.load(Ordering::Relaxed) + }); + state.dispatch(&list, 1, 1, 1); + let nonempty_demand = pending.used.load(Ordering::Relaxed); + list.close(); + slot:: u32>(title, 0x10)(title); + assert_eq!(zero_demands, [false; 3]); + assert!(nonempty_demand); + } + } From 47aabac2664e74f093d18ed7f280d4c8cc505e99 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 15:53:51 +0000 Subject: [PATCH 07/11] gpu: warm keys by the container's stage; probe the view limit; deadline first Only a mesh program's container keys by the mesh mode at runtime: warming every container in the emulation mode on emulation hardware left vertex, pixel and compute shaders uncached there. The mode now follows the container's own stage. Warm-up also probes the view-index cap as runtime translation does, and the deadline check leads the entry loop so later roots are not walked for nothing. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/victory/src/translate.rs | 10 ++++----- crates/victory-gpu/src/shader_cache.rs | 29 ++++++++++++++++++++++---- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index d791bb2..2e12ae9 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -197,14 +197,14 @@ pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> let counts = [const { AtomicUsize::new(0) }; 5]; for root in &paths { for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) { - if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { - continue; - } - // Past the deadline the workers break out at once: opening and - // reading the rest of the assets would only scan for nothing. + // Past the deadline the workers break out at once: walking and + // opening the rest of the assets would only scan for nothing. if limit.is_some_and(|n| began.elapsed().as_secs() >= n) { break; } + if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { + continue; + } let Ok(data) = std::fs::read(entry.path()) else { continue; }; diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index ae8307c..995b58f 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -87,14 +87,21 @@ fn build() -> [u8; 32] { /// the run will have (`victory_shader::emit::translation_fingerprint`). pub fn warm(container: &[u8]) -> Result { let cache = CACHE.get().ok_or("no shader cache")?; + // The translation depends on the view-index cap as at runtime. + crate::descriptor::host::probe_view_limit(); let ran = AtomicBool::new(false); // The mode the runtime translates with on this machine: an emulated // mesh shader's cache entry is another key than the native one's, so a // warm-up in only the native mode left emulation hardware (no mesh - // shader support) to translate every mesh program on first use. - let mesh = match crate::host::host() { - Some(h) if h.emulate_mesh_shaders() => MeshMode::Emulate, - _ => MeshMode::Native, + // shader support) to translate every mesh program on first use. Only a + // mesh program's container keys by it: everything else translates in + // the native mode whatever the host (`pipeline::translate`). + let mesh = if container_is_mesh(container) + && crate::host::host().is_some_and(crate::host::Host::emulate_mesh_shaders) + { + MeshMode::Emulate + } else { + MeshMode::Native }; let translate = |c: &[u8]| { ran.store(true, Ordering::Relaxed); @@ -103,6 +110,20 @@ pub fn warm(container: &[u8]) -> Result { cached(cache, &build(), mesh, container, translate).map(|_| ran.load(Ordering::Relaxed)) } +/// Whether the container's program is a mesh program: the only stage the +/// mesh mode keys and translates differently. +fn container_is_mesh(container: &[u8]) -> bool { + let Ok(c) = victory_shader::Container::parse(container) else { + return false; + }; + let Some(dxil) = c.part(victory_shader::FourCC::DXIL) else { + return false; + }; + victory_shader::native_programs(dxil.data) + .map(|ps| ps.iter().any(|p| p.stage == victory_shader::HwStage::Ms)) + .unwrap_or(false) +} + /// The translation of a console shader container, from the cache when /// there is one. pub(crate) fn host_shader(container: &[u8], mesh: MeshMode) -> Result { From d510528b4ed2645e9e4b2e2068afbc645e4cd117 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 15:55:33 +0000 Subject: [PATCH 08/11] GPU: document empty dispatches keeping indirect windows Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/draw.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 9ece2e9..e8efb2a 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -167,7 +167,7 @@ const WINDOW_MOST: u64 = 64; /// the list's scratch buffer in one pass, and the draws that follow read /// their record there with no pass of ours and no barrier (the scratch /// buffer stays readable as arguments until the next clamp), until one of -/// these: a compute +/// these: a nonempty compute /// dispatch, a direct draw, an indirect call with a count buffer or more /// than one record, a draw whose shaders can store to buffers, a record /// outside the window, another host list. From 455e3b17cf7d8aba3fb6a3c50f998f3a6ac4ada9 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 15:56:12 +0000 Subject: [PATCH 09/11] watch: ahead coverage only from the wide asking, only inside the batch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two corrections to the coverage registration: the narrow retry's answer covers only the range asked, so a failed whole scan followed by a good narrow one no longer claims the allocation; and the entry is registered only while a submission's batch asking stands, because outside one nothing ends it — a heap created there would otherwise answer from a stale snapshot for the rest of the run. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/watch.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 75b09a0..2442bc1 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -553,6 +553,9 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve } else { ask(j, kfirst, klast) }; + // The wide asking answered: the whole allocation is covered. The narrow + // retry's answer covers only the range asked. + let wide = answer.is_some() && (kfirst, klast) != (first, last); if answer.is_none() && !known_view && (kfirst, klast) != (first, last) { // The allocation was not one watched range after all (or is gone): // just ours, and look it up again next time. @@ -599,10 +602,13 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve for page in pages.collect::>() { j.written.insert(page, now); } - if answer.is_some() && (kfirst, klast) != (first, last) { - // A whole allocation asked: its other buffers answer from the - // journal for the rest of the submission instead of scanning it - // whole once a flush each (under Wine, about 1 ms a scan). + if wide && j.kept { + // A whole allocation asked while a submission's batch asking + // stands: its other buffers answer from the journal for the rest of + // the submission instead of scanning it whole once a flush each + // (under Wine, about 1 ms a scan). Only then: the coverage dies with + // the batch at `ask_once_end` — outside a submission it would go + // stale with nothing to end it. j.ahead.push((kfirst, klast)); j.ahead_asked = now; } From 9f7f2b8fb2b195dc3dfea83241038dc86ba72643 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 16:04:18 +0000 Subject: [PATCH 10/11] GPU: spread texture refreshes across wide workers Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/host.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 129ebd9..0264bba 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -7100,7 +7100,31 @@ impl HostList { fn run_deferred(&self, batch: &mut Batch) { #[cfg(feature = "diagnostics")] use crate::copystat::{C, add}; + // Texture refreshes only read title memory and write each staging + // buffer's own memory. Consecutive ones can therefore run together; + // the group is still finished before the next step that writes title + // memory, preserving submission ordering. + let mut textures = Vec::new(); + let run_textures = |textures: &mut Vec>| { + if textures.is_empty() { + return; + } + if wide_refresh() && textures.len() >= 4 { + let jobs: Vec> = textures + .drain(..) + .map(|staging| Box::new(move || staging.refresh()) as Box) + .collect(); + crate::shadow::wide_run(jobs); + } else { + for staging in textures.drain(..) { + staging.refresh(); + } + } + }; for step in &self.deferred().copies { + if !matches!(step, Step::Texture(_)) { + run_textures(&mut textures); + } let started = std::time::Instant::now(); let copied = match step { &Step::Copy(dst, src, len) => { @@ -7172,7 +7196,7 @@ impl HostList { } Step::Texture(staging) => { if batch.texture_due(staging) { - staging.refresh(); + textures.push(staging.clone()); } continue; } @@ -7180,6 +7204,7 @@ impl HostList { preparing(0, started.elapsed().as_micros() as u64); preparing(1, copied as u64); } + run_textures(&mut textures); } } From 139d96559569c7ad8d885669f1a9d7aa698379bc Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 15:56:36 +0000 Subject: [PATCH 11/11] GPU: synchronize frame interval resets with tick reservations Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/frame.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 468812c..90aa13b 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -55,12 +55,15 @@ pub(crate) extern "system" fn set_interval( }; tracing::info!(?interval, "frame interval"); // A new interval starts from now, after the last tick handed out. + // Read it under the lock `next_tick` uses, so a concurrent wait cannot + // reserve a newer tick between the read and the clock replacement. + let mut clock = clock(); let first = LAST .iter() .map(|t| t.load(Ordering::Relaxed)) .max() .unwrap_or(0); - *clock() = Some(Clock { + *clock = Some(Clock { start: Instant::now(), interval, first,