diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index 2b78b53..e6e7860 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -165,6 +165,26 @@ pub(crate) struct Replay { /// The last command that runs, `:`; after it only barriers. #[arg(long)] until: Option, + /// Say which commands change the pixel: `,` of the presented + /// picture, or `[.]:,` of a texture + /// (repeatable). With --lists, only those are looked into. + #[arg(long)] + pixel: Vec, + /// With --pixel: the size of the picture the points are of (`1280x720`), + /// if it is another than the presented one's. + #[arg(long)] + of: Option, + /// With --pixel: depth targets too. + #[arg(long)] + depth: bool, + /// With --pixel: leave out textures that shaders may write (unordered + /// access). + #[arg(long)] + targets_only: bool, + /// With --pixel: indirect calls whose draws are run one by one: + /// `:` (repeatable). + #[arg(long)] + split: Vec, /// Use the D3D12 debug layer (slow). #[arg(long)] debug_layer: bool, @@ -178,6 +198,12 @@ fn range(text: &str) -> Option<(u32, u32)> { } } +/// Two numbers with `by` between them. +fn pair(text: &str, by: char) -> Option<(u32, u32)> { + let (a, b) = text.split_once(by)?; + Some((a.trim().parse().ok()?, b.trim().parse().ok()?)) +} + pub(crate) fn run(r: Replay) -> Result<()> { if let Some(text) = &r.dump { for line in play::dump(&r.folder, text)? { @@ -260,6 +286,47 @@ pub(crate) fn run(r: Replay) -> Result<()> { let mut player = play::Player::load(&r.folder, &options)?; return player.images(&options, &images, &mut |line| println!("{line}")); } + if !r.pixel.is_empty() { + let mut player = play::Player::load(&r.folder, &options)?; + let mut pixels = play::pixel::Pixels { + depth: r.depth, + written: !r.targets_only, + ..Default::default() + }; + if let Some(text) = &r.lists { + pixels.lists = Some(range(text).with_context(|| format!("--lists {text}"))?); + } + let of = match &r.of { + Some(text) => Some(pair(text, 'x').with_context(|| format!("--of {text}"))?), + None => None, + }; + for text in &r.pixel { + let bad = || format!("--pixel {text}"); + match text.split_once(':') { + Some((what, at)) => { + let (id, sub) = what.split_once('.').unwrap_or((what, "0")); + let (x, y) = pair(at, ',').with_context(bad)?; + let id = id.parse().with_context(bad)?; + let sub = sub.parse().with_context(bad)?; + pixels.texels.push((id, sub, x, y)); + } + None => { + let (mut x, mut y) = pair(text, ',').with_context(bad)?; + if let (Some((w, h)), Some((pw, ph))) = (of, player.picture_size()) { + x = x * pw / w.max(1); + y = y * ph / h.max(1); + } + pixels.points.push((x, y)); + } + } + } + for text in &r.split { + pixels + .split + .push(pair(text, ':').with_context(|| format!("--split {text}"))?); + } + return player.pixel(&options, &pixels, &mut |line| println!("{line}")); + } if r.check_written { let mut player = play::Player::load(&r.folder, &options)?; return player.check_written(&mut |line| println!("{line}")); @@ -336,6 +403,8 @@ mod tests { assert_eq!(super::range("3..7"), Some((3, 7))); assert_eq!(super::range("5"), Some((5, 5))); assert_eq!(super::range("x"), None); + assert_eq!(super::pair("12,7", ','), Some((12, 7))); + assert_eq!(super::pair("12", ','), None); assert_eq!(super::range("1..x"), None); } } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index dbc9def..7b714c8 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -861,12 +861,16 @@ impl HostHeap { let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed); let n = n as usize; - // Search from `next` on, then from the start. - let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize); + // Search from `next` on, then from the start (extending past cursor by + // n - 1 so contiguous runs crossing the cursor are not missed). + let cursor = *next as usize; + let end = self.dynamic as usize; + let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end); + let starts = (cursor..end).chain(0..second_end); let mut run = 0; let mut found = None; let mut last = usize::MAX; - for at in starts.take(if enough { DYNAMIC as usize } else { 0 }) { + for at in starts.take(if enough { usize::MAX } else { 0 }) { // A run cannot wrap past the end. if at != last.wrapping_add(1) { run = 0; @@ -2850,4 +2854,31 @@ mod tests { assert_eq!(heap.dynamic(50), Some(4)); assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } + + #[test] + fn dynamic_search_can_find_a_run_across_the_cursor() { + let Some(heap) = HostHeap::new(false, 4) else { + eprintln!("no host descriptor heap; skipped"); + return; + }; + let first = heap.dynamic(1).unwrap(); + let left = heap.dynamic(2).unwrap(); + let right = heap.dynamic(2).unwrap(); + let rest = heap.dynamic(heap.dynamic - 5).unwrap(); + assert_eq!((first, left, right, rest), (4, 5, 7, 9)); + + // Reallocating the left half puts the cursor back in the middle. + heap.release(left, 2); + assert_eq!(heap.dynamic(2), Some(left)); + heap.release(left, 2); + heap.release(right, 2); + assert_eq!(heap.dynamic(4), Some(left)); + assert_eq!(heap.dynamic(1), None); + + // A free slot at each physical end does not form a two-slot range. + heap.release(first, 1); + let last = first + heap.dynamic - 1; + heap.release(last, 1); + assert_eq!(heap.dynamic(2), None); + } } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 88bcd33..1694324 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1718,6 +1718,7 @@ impl State { } #[cfg(feature = "diagnostics")] let refreshed = std::time::Instant::now(); + crate::watch::look_at_holes(); self.heap_textures(list, heap, host); #[cfg(feature = "diagnostics")] for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) { diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 44ebe21..e9da52c 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -214,7 +214,8 @@ mod tests { let mut second = 0; assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK); assert!(second > first); - assert!(before.elapsed() <= Duration::from_millis(50)); + // At the tick, not at the time-out (a busy PC may wake it late). + assert!(before.elapsed() <= Duration::from_millis(500)); assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT); // Tokens count frames, a frame started early on a time-out too. let mut early = 0; diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b8d9c1a..c305534 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -704,6 +704,22 @@ fn warp_adapter() -> windows::core::Result { #[cfg(test)] mod tests { + /// Zeros for a title destination that went meanwhile are no fault. + #[test] + fn zeros_where_nothing_is_are_lost() { + use windows_sys::Win32::System::Memory::*; + // SAFETY: a reservation of ours, its first page committed. + unsafe { + let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null()); + at.write_bytes(7, 4096); + super::zero(at, 4096); + assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0)); + super::zero(at.add(4096), 4096); + VirtualFree(at.cast(), 0, MEM_RELEASE); + } + } + #[test] fn sparse_copies_preserve_islands_and_observe_remaps() { use windows_sys::Win32::System::Memory::*; @@ -4709,7 +4725,7 @@ impl Host { for list in runs { for step in &list.deferred().copies { if let Step::Refresh(shadow, address, len) = step - && !shadow.unwatched() + && shadow.asked_ahead() { let span = spans .entry(std::sync::Arc::as_ptr(shadow) as usize) @@ -4719,6 +4735,8 @@ impl Host { } } let ranges: Vec<(usize, usize)> = spans.into_values().collect(); + #[cfg(feature = "diagnostics")] + SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed); crate::watch::ask_once(&ranges); #[cfg(feature = "diagnostics")] split.part(0); @@ -6215,9 +6233,11 @@ impl std::hash::Hasher for AddressHash { /// in under flights' writes; the lists' steps, the refreshes among them; the /// snapshots; what goes to copies in the card's memory; the lists sent; and /// of the steps: the refreshes, and the copies and fills (those with the -/// refreshes a copy of title memory flushes). +/// refreshes a copy of title memory flushes). Of the asking, which ranges it +/// is of. Of the refreshes, those before ranges are given to shaders, one +/// copy at a time: nanoseconds, and how many. #[cfg(feature = "diagnostics")] -static SPLIT: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; +static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; /// Since the last frame-rate line: flushes of refreshes, their refreshes, /// those known to copy nothing, and those done on several threads. @@ -6234,6 +6254,11 @@ impl Split { Split(std::cell::Cell::new(std::time::Instant::now())) } + /// Nanoseconds since the last part. + fn so_far(&self) -> u64 { + self.0.get().elapsed().as_nanos() as u64 + } + /// What came since the last part was part `i`. fn part(&self, i: usize) { let now = std::time::Instant::now(); @@ -6248,13 +6273,14 @@ fn split_line(frames: f64) { let f: Vec = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); let a: Vec = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect(); let h: Vec = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); - let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / (1 << 20) as f64 / frames).collect(); + let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect(); tracing::info!( - "preparing per frame, the submitting thread: {:.1} ms asking the write watch, {:.1} putting the title's bytes under flights' \ + "preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \ writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \ - several threads; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ + several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})", ms[0], + ms[8], ms[1], ms[2], ms[6], @@ -6262,6 +6288,8 @@ fn split_line(frames: f64) { f[1], f[2], f[3], + ms[9], + ms[10] * 1e6, ms[7], ms[3], ms[4], @@ -6269,12 +6297,17 @@ fn split_line(frames: f64) { if crate::watch::light() { "on" } else { "off" }, ); tracing::info!( - "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB; view ranges: {:.0} answered by their \ + "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \ + written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \ bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \ - waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \ - as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)", + waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \ + as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)", a[0], a[1] / 1024.0, + a[11] / 1e6, + a[12], + a[10], + a[9], a[2], a[3], a[4], @@ -6282,9 +6315,10 @@ fn split_line(frames: f64) { a[6], a[7] / 1e6, a[8] / 1e6, - s[0], - s[1], - s[2], + s[0] / 1048576.0, + s[1] / 1048576.0, + s[2] / 1048576.0, + s[3], ); tracing::info!( "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures", @@ -6414,7 +6448,12 @@ impl Batch { Self::update(&shadow, from, to); } #[cfg(feature = "diagnostics")] - SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + { + let ns = started.elapsed().as_nanos() as u64; + SPLIT[6].fetch_add(ns, Ordering::Relaxed); + SPLIT[9].fetch_add(ns, Ordering::Relaxed); + SPLIT[10].fetch_add(1, Ordering::Relaxed); + } } /// Brings `[from, to)` of a copy up to date, timed. @@ -6497,7 +6536,7 @@ impl Batch { let ranges: Vec<(usize, usize)> = self .refreshes .iter() - .filter(|r| !r.0.unwatched()) + .filter(|r| r.0.asked_ahead()) .map(|r| (r.1, r.2)) .collect(); crate::watch::ask_ahead(&ranges); @@ -6586,7 +6625,10 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b } #[cfg(feature = "diagnostics")] let moved = std::time::Instant::now(); - let whole = read(src, dst, len); + let since = crate::watch::changes(); + // (A title destination that is away only while the runtime changes a + // mapping beside it is written when that is done.) + let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len)); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64); if whole { @@ -6596,6 +6638,7 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b // not all mapped. Then the destination stays as it is (the kernel may // have written its first pages). if title_dst && !ask_first && !crate::texture::committed(dst, len) { + crate::watch::lost("a copy of the title's", dst as usize, len); return; } #[cfg(feature = "diagnostics")] @@ -6655,14 +6698,29 @@ fn read_pieces(src: *const u8, dst: *mut u8, len: usize) { if !read(at as *const u8, to, n) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Unmapped, n as u64); - // SAFETY: inside the destination, which is mapped. - unsafe { to.write_bytes(0, n) }; + zero(to, n); } }); } }); } +/// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the +/// destination of a title's copy), which can go between the question whether +/// it is there and this. +fn zero(to: *mut u8, n: usize) { + static ZEROS: [u8; 4096] = [0; 4096]; + if n <= ZEROS.len() && crate::safecopy::on() { + // SAFETY: a destination that is not there fails the copy. + if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } { + crate::watch::lost("zeros", to as usize, n); + } + return; + } + // SAFETY: inside the destination, which is mapped. + unsafe { to.write_bytes(0, n) }; +} + /// Reads title memory at `src` into `dst`; false if a page of it is not /// readable. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { @@ -6716,6 +6774,7 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; let direct = direct_writes(); + let since = crate::watch::changes(); let write = |at: usize, n: usize| { let from = src.wrapping_add(at - dst as usize); if crate::safecopy::on() { @@ -6742,7 +6801,16 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { for_pieces(dst as usize, len, 64 << 10, |at, n| { if !write(at, n) { for_pieces(at, n, 4 << 10, |at, n| { - write(at, n); + if write(at, n) { + return; + } + // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a + // refresh guarded the block again since the caller opened + // it; and any where the runtime was changing a mapping. + crate::watch::writing(at, n); + if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) { + crate::watch::lost("a host copy's bytes", at, n); + } }); } }); @@ -7795,6 +7863,50 @@ mod refresh_tests { at } + /// Title memory of `blocks` pages in a placeholder, one view to a page, + /// and every fourth page not there: as a title that streams has it. + fn with_holes(blocks: usize) -> usize { + use windows_sys::Win32::System::Memory::{ + MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, + VirtualAlloc2, VirtualFree, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a placeholder and a section of our own. + unsafe { + let at = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + blocks * PAGE, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(at, 0); + let len = blocks * PAGE; + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null()); + for block in (0..blocks).filter(|b| b % 4 != 3) { + let to = at + block * PAGE; + VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER); + let view = MapViewOfFile3( + section, + GetCurrentProcess(), + to as *const _, + (block * PAGE) as u64, + PAGE, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ); + assert_eq!(view.Value as usize, to); + crate::title_memory_remapped(to, PAGE); + } + at + } + } + fn memory(len: usize) -> *mut u8 { // SAFETY: a plain allocation. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() } @@ -7946,6 +8058,10 @@ mod refresh_tests { /// card's side of those that have one, hold what title memory holds, and /// title memory what was written last. /// + /// Into the first copy shaders write besides through a view nobody + /// declared, words the title does not write: nothing that goes up ever + /// puts an older value over those. + /// /// (It fails in the first rounds if `landed_beside` notes nothing, or /// only takes the block out of the guards' clean ones and leaves its bit, /// or if a fault leaves the bit; in some thousand rounds, @@ -7964,6 +8080,9 @@ mod refresh_tests { let data = memory(len); (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize) }; + // What was last written so, by offset. + let mut undeclared = std::collections::HashMap::new(); + let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0"); let stop = AtomicBool::new(false); // Also when an assertion fails on one of the threads. struct Stop<'a>(&'a AtomicBool); @@ -8068,6 +8187,16 @@ mod refresh_tests { let mut value = 1u32; for round in 0..rounds { check(round, &mut random, false); + if exact { + let c = &carded[0]; + let mut card = c.card.lock().unwrap(); + for _ in 0..40 { + value += 1; + let at = random.below(LEN / 32) * 32 + 4 * 6; + card.2[at..at + 4].copy_from_slice(&value.to_le_bytes()); + undeclared.insert(at, value); + } + } // The flight of this submission: its shaders' writes. for (which, c) in carded.iter().enumerate() { if c.flying.swap(true, Ordering::Acquire) { @@ -8113,7 +8242,17 @@ mod refresh_tests { let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len)); assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class); let card = c.card.lock().unwrap(); - assert_eq!(first(&card.2, there), None, "round {round}: a card copy's card side (class {})", c.class); + let mut side = card.2.clone(); + if c.class == carded[0].class { + // (They may have been landed meanwhile, by a flight + // that declared their range, and may not.) + for (&at, &value) in &undeclared { + let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap()); + assert_eq!(on_card, value, "round {round}: an older value at {at:#x}"); + side[at..at + 4].copy_from_slice(&there[at..at + 4]); + } + } + assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class); } assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy"); } @@ -8197,8 +8336,9 @@ mod refresh_tests { } } - /// A part of a copy in the card's memory taken again goes up only if it - /// differs (with `VICTORY_SEND_CHANGED=1`), whole when never taken. + /// Of a copy in the card's memory only the dwords title memory changed go + /// up, and none beside them, not even between two in 64 bytes; a page + /// never taken goes up whole. #[test] fn only_what_differs_goes_up() { let region = title(4 * PAGE, true); @@ -8217,18 +8357,24 @@ mod refresh_tests { copy.update(region, 4 * PAGE); let again = copy.take_dirty(); // SAFETY: as above. - unsafe { ((region + 2 * PAGE + 128) as *mut u8).write_volatile(9) }; + unsafe { + ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9); + ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9); + ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9); + // The value that was there. + ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0); + } copy.update(region, 4 * PAGE); let written = copy.take_dirty(); - if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") { + if std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0") { assert_eq!(again, []); - assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 192)]); + assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]); } else { assert_eq!(again, [(PAGE, 2 * PAGE)]); assert_eq!(written, [(2 * PAGE, 3 * PAGE)]); } // SAFETY: as above. - assert_eq!(unsafe { data.add(2 * PAGE + 128).read() }, 9); + assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9); } /// The refreshes of a frame as run record-1 had them: 30 submissions, the @@ -8243,12 +8389,17 @@ mod refresh_tests { const EACH: usize = 224 << 10; const BIG: usize = 174 << 20; let watched = title(3000 * EACH, false); - let views = title(1400 * EACH, true); + // `VICTORY_BENCH_HOLES=0`: views without holes. + let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0"); + let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) }; + let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3; let big = title(BIG, true); // SAFETY: the test's own memory. unsafe { std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH); - std::ptr::write_bytes(views as *mut u8, 1, 1400 * EACH); + for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) { + std::ptr::write_bytes(at as *mut u8, 1, PAGE); + } std::ptr::write_bytes(big as *mut u8, 1, BIG); } let mut small = Vec::new(); @@ -8271,8 +8422,10 @@ mod refresh_tests { // The title's writes, and the relay's beside the submission. for _ in 0..9 { let at = views + random.below(1400 * EACH / 8) * 8; - // SAFETY: the test's own memory. - unsafe { (at as *mut u64).write_volatile(frame as u64) }; + if there(at) { + // SAFETY: the test's own memory. + unsafe { (at as *mut u64).write_volatile(frame as u64) }; + } } for _ in 0..60 { let at = watched + random.below(3000 * EACH / 8) * 8; diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index a4fa155..7d044ab 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -29,7 +29,7 @@ //! garbage records cannot run for seconds either. //! //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 -//! groups per dimension and 2^20 per dispatch, one-dimensional mesh +//! groups per dimension, in x 2^20 ([`widest`]), and 2^20 per dispatch, one-dimensional mesh //! dispatches, the budget) cut legitimate work beyond them; raise them if //! the title needs more. @@ -107,9 +107,11 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { cost = count * instances; draw_counts = uint2(count, instances); } else if (active && kind == 2) { - uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); - // x * y fits 32 bits; the whole count may not. - if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + uint3 g = src_args.Load3(src_at); + // Up to WIDEST groups in x run as asked (`widest`). + g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u)); + // x * y fits 32 bits where it is looked at; the whole count may not. + if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) { g = uint3(0, 0, 0); } cost = g.x * g.y * g.z * 64u; @@ -237,9 +239,42 @@ fn make_for(device: &ID3D12Device) -> windows::core::Result { make_from(device, SOURCE) } +/// The most groups in x that an indirect dispatch runs as the title asks: +/// 65,535 is the most D3D12 names for a dispatch, 2^20 ([`SOURCE`]'s GROUPS) +/// what is bounded here anyway (`VICTORY_INDIRECT_WIDE=0`: 65,535; a record +/// that asks for more still runs 65,535). +/// +/// The title's tile lists are dispatches of one group per tile, and two of +/// them are classes of the picture's 8x4 tiles, 115,200 in all at +/// 2560x1440: in a captured frame 67,440 and 47,760 (the program +/// 2dc364df5d3278b8 and 940c2635dc1312f4). Cut to 65,535 the first list lost +/// its last 1,905 tiles, the lowest of the picture. The console runs what it +/// is asked (its dispatch counts are 32 bits), and so does an AMD card, whose +/// dispatch packets and group numbers are the same; D3D12 does not look at +/// indirect counts. Other cards stay at 65,535. +fn widest(amd: bool) -> u32 { + let on = std::env::var_os("VICTORY_INDIRECT_WIDE").is_none_or(|v| v != "0"); + if amd && on { 1 << 20 } else { 65_535 } +} + +/// Whether `device` is an AMD card's. +fn amd(device: &ID3D12Device) -> bool { + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory4}; + // SAFETY: plain queries. + unsafe { + CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::(device.GetAdapterLuid())) + .and_then(|a| a.GetDesc1()) + .is_ok_and(|d| d.VendorId == 0x1002) + } +} + /// The clamp compiled from `source` (ours, or in the benchmark the one it /// replaced). fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result { + #[cfg(feature = "diagnostics")] + let batched = source == batch::SOURCE; + let source = &format!("#define WIDEST {}u\n{source}", widest(amd(device))); let mut code: Option = None; let mut errors: Option = None; // SAFETY: the source and names live through the call; out pointers ours. @@ -1027,11 +1062,11 @@ void main() { 1, [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC], ); - // Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1). + // Record 2 exceeds what any card runs in X -> clamped to (65535, 1, 1). write_record( &mut initial_src, 2, - [100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567], + [(1 << 20) + 1, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567], ); for slot in 3..MAX as usize { // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups @@ -1832,6 +1867,75 @@ void main() { sig.unwrap() } + /// An AMD card runs every group of an indirect dispatch of more than + /// 65,535, each under its own number: the title's tile lists + /// ([`widest`]), clamped one by one and in a batch. Others are not asked. + #[test] + fn card_runs_wide_indirect_dispatches() { + const CS: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer seen : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { + uint was; + seen.InterlockedAdd(0, 1, was); + seen.InterlockedMax(4, group.x, was); + seen.InterlockedMax(8, thread.x, was); + seen.InterlockedAdd(16 + group.x * 4, 1, was); +} +"#; + let Some(mut gpu) = WarpHarness::on(false) else { + return; + }; + if !amd(&gpu.device) || widest(true) == 65_535 { + return; + } + let worker = compile_cs(&gpu.device, CS).expect("the worker must compile"); + let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile"); + let sig = gpu.signature(2, 12); + for asked in [67_440u32, 115_200, 1 << 20, (1 << 20) + 1] { + let runs = if asked > 1 << 20 { 65_535 } else { asked }; + for batched in [false, true] { + let (src, src_ptr, src_gpu) = gpu.shared_buffer(1024); + let (_budget, budget_ptr, budget_gpu) = gpu.shared_buffer(256); + let (_table, table_ptr, table_gpu) = gpu.shared_buffer(batch::TABLE); + let size = 16 + (4 << 20) + 16; + let seen = gpu.default_uav(size); + let (back, back_ptr, _) = gpu.shared_buffer(size); + let dst = gpu.default_uav(64 << 10); + // SAFETY: mapped buffers, which nothing reads yet; an open + // list and live buffers. + unsafe { + std::ptr::write_bytes(budget_ptr, 0, 256); + for (w, word) in [asked, 1, 1].into_iter().enumerate() { + src_ptr.cast::().add(w).write_volatile(word); + } + if batched { + batch::record(&pass, &gpu.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu; 4], table_gpu); + assert_eq!(batch::Table::new(table_ptr, 0, [1, 0, 0, 0]).place(1, 0, 2), Some(0)); + } else { + let to = (&dst, D3D12_RESOURCE_STATE_COMMON); + assert!(record_clamp_as(&gpu.clamp, &gpu.list, to, budget_gpu, (&src, 0), None, (2, 12, 1), false)); + } + gpu.list.SetComputeRootSignature(&worker.root); + gpu.list.SetPipelineState(&worker.pso); + gpu.list.SetComputeRootUnorderedAccessView(0, seen.GetGPUVirtualAddress()); + gpu.list.ExecuteIndirect(&sig, 1, &dst, 0, None, 0); + gpu.list.ResourceBarrier(&[uav_barrier()]); + gpu.list.ResourceBarrier(&[transition(&seen, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + gpu.list.CopyBufferRegion(&back, 0, &seen, 0, size); + } + gpu.submit_and_wait(); + // SAFETY: the list has run; mapped words. + let word = |i: usize| unsafe { back_ptr.cast::().add(i).read_volatile() }; + assert_eq!([word(0), word(1), word(2)], [runs, runs - 1, runs - 1], "asked for {asked}, batched {batched}"); + let wrong = (0..runs as usize).find(|&g| word(4 + g) != 1); + assert_eq!((wrong, word(4 + runs as usize)), (None, 0), "every group once, asked for {asked}"); + } + } + } + /// What a batch's table says of records added to it: one job per /// record, charged for every execution that reads it, and none for what /// the pass cannot read. diff --git a/crates/victory-gpu/src/indirect/batch.rs b/crates/victory-gpu/src/indirect/batch.rs index 1f65388..ed25aa5 100644 --- a/crates/victory-gpu/src/indirect/batch.rs +++ b/crates/victory-gpu/src/indirect/batch.rs @@ -81,8 +81,9 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { record[1] = min(record[1], (1u << 26) / max(record[0], 1u)); cost = record[0] * record[1]; } else if (kind == 2) { - uint3 g = min(uint3(record[0], record[1], record[2]), uint3(65535u, 65535u, 65535u)); - if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + uint3 g = uint3(record[0], record[1], record[2]); + g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u)); + if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) { g = uint3(0, 0, 0); } cost = g.x * g.y * g.z * 64u; diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 56a883b..c9df9c1 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -329,6 +329,26 @@ pub(crate) fn views_gone(at: usize, len: usize) { } } +/// How many bytes of `[at, at + len)` views of physical pages show; `None` +/// if no view touches it (nothing is mapped there, or memory of another +/// kind). The runtime's own record of what it mapped: no question to the +/// host. +pub(crate) fn shown_bytes(at: usize, len: usize) -> Option { + let end = at.saturating_add(len); + let v = views(); + let first = v.views.range(..=at).next_back(); + let rest = v.views.range(at.saturating_add(1)..end.max(at.saturating_add(1))); + let (mut there, mut any) = (0u64, false); + for (&base, view) in first.into_iter().chain(rest) { + let (from, to) = (base.max(at), base.saturating_add(view.0).min(end)); + if from < to { + there += (to - from) as u64; + any = true; + } + } + any.then_some(there) +} + /// How the views cover `[at, at + len)`. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub(crate) enum Cover { @@ -1074,6 +1094,27 @@ mod tests { /// Views as the runtime tells them: a range inside one view, or over /// views that continue each other in one section, is one run; over /// views from elsewhere it is scattered; over a gap it has holes. + #[test] + fn the_views_say_how_much_of_a_range_is_there() { + const K64: usize = 64 << 10; + // Addresses nothing has: only the record is asked. + let at = 0x7ff1_0000_0000_usize; + for (block, blocks) in [(0, 1), (1, 1), (4, 2)] { + super::title_memory_view(at + block * K64, blocks * K64, 7, 0); + } + let shown = |from: usize, len: usize| super::shown_bytes(at + from, len); + assert_eq!(shown(0, 8 * K64), Some(4 * K64 as u64)); + assert_eq!(shown(100, K64), Some(K64 as u64)); + assert_eq!(shown(K64 + 100, 2 * K64), Some(K64 as u64 - 100)); + assert_eq!(shown(5 * K64 + 1, 10), Some(10)); + assert_eq!(shown(2 * K64, 2 * K64), None); + assert_eq!(shown(6 * K64, 2 * K64), None); + super::views_gone(at + K64, K64); + assert_eq!(shown(0, 2 * K64), Some(K64 as u64)); + super::views_gone(at, 8 * K64); + assert_eq!(shown(0, 8 * K64), None); + } + #[test] fn views_say_what_one_placed_buffer_could_show() { let mut views = BTreeMap::new(); diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 67ae9cd..f8d1cf9 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -133,6 +133,16 @@ pub(crate) fn spent(which: usize, from: std::time::Instant) -> std::time::Instan /// For the frame-rate line: where landing went, per frame. pub(crate) fn log(frames: f64) { + let t: Vec = TAKEN.iter().map(|t| t.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if t[0] > 0.0 { + tracing::info!( + "blocks landed in beside the guards per frame: {:.0}, {:.0} of them held by the copy they were landed through, which takes \ + them no more (VICTORY_LAND_TAKEN={})", + t[0], + t[1], + u8::from(taken()), + ); + } let s: Vec = STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); if s[stat::PIECES] == 0.0 && s[stat::REST] == 0.0 { return; @@ -416,8 +426,39 @@ pub(crate) struct Notes { pages: Vec, /// Per piece, from the first such page to the last: address, bytes. spans: Vec<(usize, usize)>, + /// Per piece put beside the guards, all of it: its 64 KiB block and the + /// copy it was landed through (which the job holds until the flush). + landed: Vec<(usize, *const crate::shadow::Shadow)>, } +// SAFETY: the pointers are used by the job that has the notes, in `flush`. +unsafe impl Send for Notes {} + +/// Whether a copy a landing went through is noted as up to date with it +/// (`VICTORY_LAND_TAKEN=0`: it is not, and the next refresh copies the 64 +/// KiB again and sends them up to the card, as before). +/// +/// What a landing puts into title memory the copy holds already: the card +/// wrote it there, and a copy in the card's memory was given it on the CPU's +/// side by the same merge. But the block counted as written, for that copy +/// as for every other one, so the next refresh copied the whole block, sent +/// it up and had the card hash it again: some 900 blocks a frame landed +/// beside the guards, of the 103 MB a frame that went up (run record-1). +/// +/// Why it may be left out ([`crate::shadow::Shadow::landed`]): the copy held +/// title memory's bytes of the block before the landing, if it had taken it +/// after the block's last noted write and no write was to be noted (the +/// block's bit, `crate::watch::block_published`), and the landing put the +/// same bytes into both. Only where one copy alone landed in the block. +fn taken() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_TAKEN").is_none_or(|v| v != "0")) +} + +/// Since the last frame-rate line: blocks landed in beside the guards, and +/// those of them the copy was noted as up to date with. +static TAKEN: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + impl Notes { /// At the end of a job: what it wrote beside the guards is noted. pub(crate) fn flush(&mut self) { @@ -425,9 +466,24 @@ impl Notes { return; } let noting = std::time::Instant::now(); - crate::watch::landed_beside(&self.pages, &self.spans); + let (now, blocks) = crate::watch::landed_beside(&self.pages, &self.spans); + TAKEN[0].fetch_add(blocks.len() as u64, Ordering::Relaxed); + if taken() { + for (block, before) in blocks { + let mut through = self.landed.iter().filter(|l| l.0 == block).map(|l| l.1); + let Some(copy) = through.next() else { + continue; + }; + if !copy.is_null() && through.all(|other| other == copy) { + // SAFETY: the job holds its copies until this is done. + let copy = unsafe { &*copy }; + TAKEN[1].fetch_add(u64::from(copy.landed(block, before, now)), Ordering::Relaxed); + } + } + } self.pages.clear(); self.spans.clear(); + self.landed.clear(); spent(stat::NOTES, noting); } } @@ -447,9 +503,10 @@ pub(crate) unsafe fn piece( parts: &[(usize, usize)], take: bool, notes: &mut Notes, + copy: *const crate::shadow::Shadow, ) -> u64 { // SAFETY: the caller's. - unsafe { piece_at(title, now, held, parts, take, notes, beside_on()) } + unsafe { piece_at(title, now, held, parts, take, notes, beside_on(), copy) } } /// [`piece`], and whether a view of ours is looked for. @@ -464,6 +521,7 @@ unsafe fn piece_at( take: bool, notes: &mut Notes, beside: bool, + copy: *const crate::shadow::Shadow, ) -> u64 { let Some(end) = parts.last().map(|p| p.1) else { return 0; @@ -499,6 +557,7 @@ unsafe fn piece_at( spent(stat::NOTES, opening); } let into = beside.unwrap_or(title); + let since = crate::watch::changes(); let (mut pages, mut new_pages, mut blocks, mut dwords, mut missing) = (0, 0u64, 0, 0, 0); let mut span: Option<(usize, usize)> = None; for_pages(title, parts, |from, n| { @@ -508,7 +567,26 @@ unsafe fn piece_at( } // SAFETY: the caller's; title memory, by an address that shows it // (`beside`) or the title's own. - let done = unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) }; + let merge = |take| unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) }; + let mut done = merge(take && beside.is_some()); + if !done.there && beside.is_none() { + // Away only while the runtime changes a mapping beside it: the + // rest of it when that is done. What is still not there then is + // taken as the caller says. + let mut put = done.dwords; + let again = crate::watch::again_after_change(since, || { + done = merge(false); + put += done.dwords; + done.there + }); + if !again && take { + done = merge(true); + put += done.dwords; + } + done.dwords = put; + // (What was new to the first try was new.) + done.new = done.new.max(1); + } blocks += done.new; dwords += done.dwords; missing += u64::from(!done.there); @@ -527,6 +605,10 @@ unsafe fn piece_at( }); if let Some((from, to)) = span { notes.spans.push((from, to - from)); + // Not through a copy that is not to be noted, if that is asked: the + // block then has two. + let through = if missing == 0 { copy } else { std::ptr::null() }; + notes.landed.push((title / BLOCK, through)); } count(stat::NEW_PIECES, u64::from(new_pages > 0)); count(stat::PAGES, pages); diff --git a/crates/victory-gpu/src/land/tests.rs b/crates/victory-gpu/src/land/tests.rs index f2fef9f..f67d640 100644 --- a/crates/victory-gpu/src/land/tests.rs +++ b/crates/victory-gpu/src/land/tests.rs @@ -192,7 +192,7 @@ fn a_piece_lands_what_the_card_wrote_in_its_parts() { let asked = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view").0; let mut notes = Notes::default(); // SAFETY: vectors of `len` bytes. - let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes) }; + let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes, std::ptr::null()) }; notes.flush(); let mut expect_held = base.clone(); let mut expect = there.clone(); @@ -213,6 +213,43 @@ fn a_piece_lands_what_the_card_wrote_in_its_parts() { } } +/// A piece whose title memory is away only while the runtime changes a +/// mapping lands when that is done; where it stays away the copy's CPU side +/// takes the card's bytes (`take`) or not. +#[test] +fn a_piece_waits_for_a_change_of_mapping() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, VirtualAlloc, VirtualFree}; + assert!(crate::safecopy::on()); + // SAFETY: a reservation of ours, nothing of it committed. + let at = unsafe { VirtualAlloc(std::ptr::null(), BLOCK, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert_ne!(at, 0); + let now = [9u8; 100]; + for take in [true, false] { + let mut held = [0u8; 100]; + // SAFETY: arrays of 100 bytes. + let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], take, &mut Notes::default(), std::ptr::null()) }; + assert_eq!((put, held), (0, [if take { 9 } else { 0 }; 100])); + } + let (began, wait) = std::sync::mpsc::channel(); + let change = std::thread::spawn(move || { + let _changing = crate::watch::title_memory_remapping(); + began.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + // SAFETY: the reservation's first page. + assert!(!unsafe { VirtualAlloc(at as _, PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + }); + wait.recv().unwrap(); + let mut held = [0u8; 100]; + // SAFETY: as above. + let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], true, &mut Notes::default(), std::ptr::null()) }; + change.join().unwrap(); + assert_eq!((put, held), (100, now)); + // SAFETY: committed by now. + assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 100) }, now); + // SAFETY: our reservation. + unsafe { VirtualFree(at as _, 0, MEM_RELEASE) }; +} + /// Landings on several threads beside title threads that write the same /// blocks (other dwords) and a thread that refreshes a copy, guarding what /// it takes: no write of the title's is lost or undone, all the card wrote @@ -292,7 +329,7 @@ fn landings_beside_the_title_and_its_refreshes_lose_nothing() { let offset = address - at; // SAFETY: each job its own pieces of the two vectors. unsafe { - piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes); + piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes, std::ptr::null()); } } notes.flush(); @@ -420,7 +457,7 @@ fn what_landing_costs() { let mut notes = Notes::default(); for &(at, now, held) in &landing[jobs[j].clone()] { // SAFETY: each its own bytes. - unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside) }; + unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside, std::ptr::null()) }; } notes.flush(); }); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index d7bfbaa..905548b 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -72,6 +72,6 @@ pub use host::on_failure; pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping, - writing as kernel_will_write, + kernel_writing, title_memory_allocated, title_memory_freed, title_memory_reading, title_memory_remapped, + title_memory_remapping, title_memory_unmapping, writing as kernel_will_write, }; diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 9acd1d2..e3559c3 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -296,13 +296,19 @@ impl GraphicsState { .map(|e| { let slot = e.InputSlot.min(31) as usize; let format = e.Format.0 as u32; + let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); + // An appended element starts at the next multiple of + // min(4, its size) after the previous one, where D3D12 (and + // vkd3d) place it; the host pipeline gets the title's + // descriptions, so the offsets read here must match. let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT { next[slot] + .checked_next_multiple_of(bytes.clamp(1, 4)) + .unwrap_or(u32::MAX) } else { e.AlignedByteOffset }; - let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); - next[slot] = offset + bytes; + next[slot] = offset.saturating_add(bytes); Input { slot: slot as u32, offset, @@ -437,6 +443,19 @@ impl HostPipeline { } let host = host()?; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); + // SAFETY: the feature query writes the structure of the given size. + // Older runtimes may not recognize OPTIONS19; that means no support. + let aniso_point_mip_supported = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS19, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + } + .is_ok() + && options.AnisoFilterWithPointMipSupported.as_bool(); + // The root signature the translated shaders' bindings define. let mut params: Vec = Vec::new(); // The ranges table parameters point at, alive until the root @@ -544,7 +563,7 @@ impl HostPipeline { } for (n, s) in t.static_samplers.iter().enumerate() { samplers.push(D3D12_STATIC_SAMPLER_DESC { - Filter: D3D12_FILTER(s.filter as i32), + Filter: D3D12_FILTER(s.filter_for_host(aniso_point_mip_supported) as i32), AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32), AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32), AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32), @@ -1431,4 +1450,63 @@ mod tests { assert_eq!(run_draw(0.6, 1.0), 0, "depth 0.5 outside [0.6, 1.0] must be rejected"); assert_eq!(run_draw(0.4, 0.6), 255, "depth 0.5 inside [0.4, 0.6] must pass"); } + + fn element(format: DXGI_FORMAT, offset: u32) -> D3D12_INPUT_ELEMENT_DESC { + D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(c"TEXCOORD".as_ptr().cast()), + SemanticIndex: 0, + Format: format, + InputSlot: 0, + AlignedByteOffset: offset, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + InstanceDataStepRate: 0, + } + } + + fn offsets(inputs: &[D3D12_INPUT_ELEMENT_DESC]) -> Vec { + let state = GraphicsState { + inputs: inputs.to_vec(), + ..GraphicsState::default() + }; + state.elements().iter().map(|e| e.offset).collect() + } + + /// An appended element after one of 1 or 2 bytes started right after + /// it; D3D12 aligns it to min(4, its size), so the rectangle expansion + /// read its vertices from the wrong bytes. + #[test] + fn appended_elements_are_aligned() { + const APPEND: u32 = D3D12_APPEND_ALIGNED_ELEMENT; + // RG8 (2 bytes) then RG32 float: 4, not 2. + let a = [ + element(DXGI_FORMAT_R8G8_UNORM, 0), + element(DXGI_FORMAT_R32G32_FLOAT, APPEND), + ]; + assert_eq!(offsets(&a), [0, 4]); + // R8 then R16 float: 2, not 1; then R8 packs right after it. + let b = [ + element(DXGI_FORMAT_R8_UNORM, 0), + element(DXGI_FORMAT_R16_FLOAT, APPEND), + element(DXGI_FORMAT_R8_UNORM, APPEND), + ]; + assert_eq!(offsets(&b), [0, 2, 4]); + // Already aligned layouts are unchanged. + let c = [ + element(DXGI_FORMAT_R8G8B8A8_UNORM, 0), + element(DXGI_FORMAT_R32G32_FLOAT, APPEND), + element(DXGI_FORMAT_R32G32B32_FLOAT, APPEND), + ]; + assert_eq!(offsets(&c), [0, 4, 12]); + } + + /// An explicit offset near 4 GiB overflowed the next appended offset + /// (a panic in debug builds). + #[test] + fn a_huge_explicit_offset_does_not_overflow() { + let inputs = [ + element(DXGI_FORMAT_R32G32B32A32_FLOAT, u32::MAX - 8), + element(DXGI_FORMAT_R32_FLOAT, D3D12_APPEND_ALIGNED_ELEMENT), + ]; + let _ = offsets(&inputs); + } } diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index 3f73ee7..180e43e 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -55,6 +55,8 @@ enum Kind { F16, Unorm8, Unorm16, + Snorm8, + Snorm16, } /// Component count and kind of the vertex formats rectangles use. @@ -69,7 +71,16 @@ fn components(format: u32) -> Option<(usize, Kind)> { 54 => (1, Kind::F16), 11 => (4, Kind::Unorm16), 35 => (2, Kind::Unorm16), + 56 => (1, Kind::Unorm16), 28 | 29 | 87 | 91 => (4, Kind::Unorm8), + 49 => (2, Kind::Unorm8), + 61 => (1, Kind::Unorm8), + 13 => (4, Kind::Snorm16), + 37 => (2, Kind::Snorm16), + 58 => (1, Kind::Snorm16), + 31 => (4, Kind::Snorm8), + 51 => (2, Kind::Snorm8), + 63 => (1, Kind::Snorm8), _ => return None, }) } @@ -78,8 +89,8 @@ impl Kind { fn bytes(self) -> usize { match self { Kind::F32 => 4, - Kind::F16 | Kind::Unorm16 => 2, - Kind::Unorm8 => 1, + Kind::F16 | Kind::Unorm16 | Kind::Snorm16 => 2, + Kind::Unorm8 | Kind::Snorm8 => 1, } } @@ -90,6 +101,8 @@ impl Kind { Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])), Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0, Kind::Unorm8 => f32::from(b[0]) / 255.0, + Kind::Snorm16 => (f32::from(i16::from_le_bytes([b[0], b[1]])) / 32767.0).max(-1.0), + Kind::Snorm8 => (f32::from(b[0] as i8) / 127.0).max(-1.0), } } @@ -103,6 +116,10 @@ impl Kind { b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes()) } Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8, + Kind::Snorm16 => { + b.copy_from_slice(&((v.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes()) + } + Kind::Snorm8 => b[0] = (v.clamp(-1.0, 1.0) * 127.0).round() as i8 as u8, } } } @@ -218,6 +235,33 @@ mod tests { assert_eq!(dst[40..], vertex(4.0, 6.0)[..]); } + #[test] + fn normalized_attributes_are_interpolated_in_their_own_range() { + let vertex = |rg: [u8; 2], u16_value: u16, u8_value: u8, snorm8: i8, snorm16: i16| { + [ + &rg[..], + &u16_value.to_le_bytes(), + &[u8_value, snorm8 as u8], + &snorm16.to_le_bytes(), + ] + .concat() + }; + let src = [ + vertex([3, 250], 1000, 10, i8::MIN, -23000), + vertex([8, 200], 500, 3, -120, -18000), + vertex([20, 253], 10000, 100, -120, -32000), + ] + .concat(); + let mut dst = [0; 6 * 8]; + expand_rects( + &src, + &mut dst, + 8, + &[(0, 49), (2, 56), (4, 61), (5, 63), (6, 58)], + ); + assert_eq!(dst[40..], vertex([15, 255], 10500, 107, -127, -32767)); + } + /// `half_to_f32` reads subnormals, so an f16 rectangle output must be /// able to write them back instead of flushing every one to zero. #[test] diff --git a/crates/victory-gpu/src/replay/edit.rs b/crates/victory-gpu/src/replay/edit.rs index a9c7ce3..e4f1f98 100644 --- a/crates/victory-gpu/src/replay/edit.rs +++ b/crates/victory-gpu/src/replay/edit.rs @@ -8,6 +8,10 @@ use super::wire::{ALL, Barrier, Cmd, NONE, Va, slot}; /// The buffer the clamped arguments of all clamp passes lie in, in lists /// edited by [`clamps`]. pub const RESULTS: u32 = u32::MAX - 1; +/// The buffer texels are read back through (`play::pixel`). +pub const PROBE: u32 = u32::MAX - 2; +/// A buffer of the card's that depth goes through on the way there. +pub const SCRATCH: u32 = u32::MAX - 3; const INDIRECT_ARGUMENT: i32 = 0x200; const UNORDERED_ACCESS: i32 = 0x8; diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index f3580f0..b56f6e2 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -32,6 +32,7 @@ use super::wire::{ pub mod diverge; pub mod look; mod merge; +pub mod pixel; mod upcopies; /// The name of the argument clamp's pipeline, by which its passes are @@ -363,6 +364,12 @@ pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) -> other => format!("{other:?}"), }; line(&format!("buffer {} {} bytes, {place}: {}", r.id, r.desc.width, r.name)); + } else { + let d = &r.desc; + line(&format!( + "texture {} {}x{}x{} mips {} f{}: {}", + r.id, d.width, d.height, d.depth, d.mips, d.format, r.name + )); } } let mut place = 0; @@ -468,6 +475,8 @@ pub struct Player { card_writes: HashSet, /// The results of clamp passes ([`RESULTS`]). results: Option, + /// Other buffers of ours that commands name. + extra: HashMap, commands: Vec>, /// Resources in the states of the start (not those of the end). fresh: bool, @@ -535,6 +544,7 @@ impl Player { merging: false, card_writes: HashSet::new(), results: None, + extra: HashMap::new(), commands, fresh: true, at: States::default(), @@ -632,7 +642,10 @@ impl Player { if id == RESULTS { return self.results.as_ref(); } - self.objects.get(&id).map(|o| &o.res) + self.objects + .get(&id) + .map(|o| &o.res) + .or_else(|| self.extra.get(&id)) } fn va(&self, va: &Va) -> u64 { diff --git a/crates/victory-gpu/src/replay/play/pixel.rs b/crates/victory-gpu/src/replay/play/pixel.rs new file mode 100644 index 0000000..e79fce9 --- /dev/null +++ b/crates/victory-gpu/src/replay/play/pixel.rs @@ -0,0 +1,843 @@ +//! What draws a pixel: `--pixel`. After every command that can change a +//! texture, the texel under the pixel is copied out of it (of a draw: of its +//! targets, where the pixel lies in its viewport, and of the textures shaders +//! may write; of a dispatch: of those; of a copy, clear or resolve: of where +//! it goes), and commands that changed one are named with the values before +//! and after. + +use super::edit::{PROBE, SCRATCH}; +use super::*; + +/// What to look at. +#[derive(Clone, Debug, Default)] +pub struct Pixels { + /// Points of the presented picture. + pub points: Vec<(u32, u32)>, + /// Texels of textures: resource, subresource, place. + pub texels: Vec<(u32, u32, u32, u32)>, + /// Only these lists are looked into. + pub lists: Option<(u32, u32)>, + /// Depth targets too (a copy of the whole target for each draw). + pub depth: bool, + /// Textures shaders may write too. + pub written: bool, + /// Indirect draws that are run one by one: list, command. + pub split: Vec<(u32, u32)>, +} + +/// Bytes a sample has. +const ROOM: u64 = 512; +/// The most samples of one run. +const MOST: usize = 1 << 20; + +#[derive(Clone, Debug)] +struct Sample { + list: u32, + command: usize, + /// Of a split draw: which one. + part: u32, + before: bool, + spot: Spot, + pso: u32, + what: &'static str, +} + +/// A texture's part that a sample can be taken from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct Spot { + res: u32, + sub: u32, + x: u32, + y: u32, + z: u32, + /// The point of the picture it stands for (or [`OWN`]). + point: usize, + format: i32, + depth: bool, +} + +/// In [`Spot::point`]: a texel asked for by itself. +const OWN: usize = usize::MAX; + +/// The texel of a target of `size` that shows the point `(x, y)` of a picture +/// of `picture`, drawn through `view` (x, y, width, height): none if the +/// target has another shape than the picture. +fn texel( + (x, y): (u32, u32), + picture: (u32, u32), + view: [f32; 4], + size: (u32, u32), +) -> Option<(u32, u32)> { + let (w, h) = (picture.0 as f32, picture.1 as f32); + if !same_shape((view[2], view[3]), (w, h)) || view[2] < 16.0 { + return None; + } + let a = (view[0] + (x as f32 + 0.5) / w * view[2]).floor(); + let b = (view[1] + (y as f32 + 0.5) / h * view[3]).floor(); + (a >= 0.0 && b >= 0.0 && a < size.0 as f32 && b < size.1 as f32).then_some((a as u32, b as u32)) +} + +fn same_shape(a: (f32, f32), b: (f32, f32)) -> bool { + (0.97..1.03).contains(&(a.0 * b.1 / (a.1 * b.0).max(1e-6))) +} + +/// A float from a small one's bits (5 bits of exponent, `mantissa` of +/// mantissa, no sign). +fn small(bits: u32, mantissa: u32) -> f32 { + let (e, m) = ( + bits >> mantissa & 31, + (bits & ((1 << mantissa) - 1)) as f32, + ); + let unit = (1u32 << mantissa) as f32; + match e { + 0 => m / unit * 2f32.powi(-14), + 31 if m == 0.0 => f32::INFINITY, + 31 => f32::NAN, + e => (1.0 + m / unit) * 2f32.powi(e as i32 - 15), + } +} + +/// Bytes of a texel of a format; 0 for formats not read. +fn texel_bytes(format: i32) -> usize { + match format { + 1..=4 => 16, + 5..=8 => 12, + 9..=22 => 8, + 23..=47 => 4, + 48..=59 => 2, + 60..=65 => 1, + 67 | 85..=93 => 4, + _ => 0, + } +} + +/// A texel in words. +fn texel_text(format: i32, b: &[u8]) -> String { + let n = texel_bytes(format); + if n == 0 || b.len() < n { + return format!("{b:02x?}"); + } + let word = |i: usize| u32::from_le_bytes([b[i * 4], b[i * 4 + 1], b[i * 4 + 2], b[i * 4 + 3]]); + let float = |i: usize| f32::from_bits(word(i)); + let short = |i: usize| u16::from_le_bytes([b[i * 2], b[i * 2 + 1]]); + let half = |i: usize| { + let v = small(u32::from(short(i) & 0x7FFF), 10); + if short(i) >> 15 != 0 { -v } else { v } + }; + let unorm16 = |i: usize| f32::from(short(i)) / 65535.0; + let snorm16 = |i: usize| f32::from(short(i) as i16) / 32767.0; + let unorm8 = |i: usize| f32::from(b[i]) / 255.0; + let snorm8 = |i: usize| f32::from(b[i] as i8) / 127.0; + let all: Vec = match format { + 1 | 2 => (0..4).map(float).collect(), + 5 | 6 => (0..3).map(float).collect(), + 9 | 10 => (0..4).map(half).collect(), + 11 => (0..4).map(unorm16).collect(), + 13 => (0..4).map(snorm16).collect(), + 15 | 16 => (0..2).map(float).collect(), + 23 | 24 => vec![ + (word(0) & 1023) as f32 / 1023.0, + (word(0) >> 10 & 1023) as f32 / 1023.0, + (word(0) >> 20 & 1023) as f32 / 1023.0, + (word(0) >> 30) as f32 / 3.0, + ], + 26 => vec![ + small(word(0) & 2047, 6), + small(word(0) >> 11 & 2047, 6), + small(word(0) >> 22, 5), + ], + 27..=29 | 87 | 90 | 91 => (0..4).map(unorm8).collect(), + 31 => (0..4).map(snorm8).collect(), + 33 | 34 => (0..2).map(half).collect(), + 35 => (0..2).map(unorm16).collect(), + 37 => (0..2).map(snorm16).collect(), + 39..=41 => vec![float(0)], + 48 | 49 => (0..2).map(unorm8).collect(), + 51 => (0..2).map(snorm8).collect(), + 53 | 54 => vec![half(0)], + 55 | 56 => vec![unorm16(0)], + 58 => vec![snorm16(0)], + 60 | 61 => vec![unorm8(0)], + 63 => vec![snorm8(0)], + _ => Vec::new(), + }; + let all: Vec = all.iter().map(|v| format!("{v:.5}")).collect(); + format!("{} {:02x?}", all.join(" "), &b[..n]).trim().to_owned() +} + +/// One draw of an indirect call that has many. +fn part_of(c: &Cmd, i: u32, stride: u32) -> Cmd { + match c { + Cmd::Indirect { + signature, + args, + at, + .. + } => Cmd::Indirect { + signature: *signature, + most: 1, + args: *args, + at: at + u64::from(i) * u64::from(stride), + count: NONE, + count_at: 0, + }, + c => c.clone(), + } +} + +fn transition(res: u32, sub: u32, before: u32, after: u32) -> Barrier { + Barrier::Transition { + flags: 0, + res, + sub, + before: before as i32, + after: after as i32, + } +} + +/// What is known of the frame's textures. +struct Textures { + /// Formats copies have. + copied_as: HashMap, + /// Textures shaders may write and that have the picture's shape. + shaped: Vec, + /// The viewport targets of a size were last drawn through. + drawn: HashMap<(u32, u32), [f32; 4]>, +} + +impl Player { + fn texture(&self, id: u32) -> Option<&wire::Resource> { + let o = self.objects.get(&id)?; + let r = &self.frame.resources[o.index]; + (r.desc.dimension != D3D12_RESOURCE_DIMENSION_BUFFER.0 && r.desc.samples[0] <= 1) + .then_some(r) + } + + /// What a view of a target is of: subresource, depth slice, size, format. + fn seen_by(&self, s: &Slot) -> Option<(u32, u32, (u32, u32), i32)> { + let r = self.texture(s.res)?; + let word = |i: usize| { + u32::from_le_bytes([ + s.desc[i * 4], + s.desc[i * 4 + 1], + s.desc[i * 4 + 2], + s.desc[i * 4 + 3], + ]) + }; + let (mut mip, mut slice, mut z, mut format) = (0, 0, 0, 0); + if s.described != 0 { + format = word(0) as i32; + match (s.kind, word(1) as i32) { + // 2D, 2D array and 3D views. + (slot::RTV, 4) => mip = word(2), + (slot::RTV, 5) => (mip, slice) = (word(2), word(3)), + (slot::RTV, 8) => (mip, z) = (word(2), word(3)), + (slot::DSV, 3) => mip = word(3), + (slot::DSV, 4) => (mip, slice) = (word(3), word(4)), + _ => return None, + } + } + if format == 0 { + format = r.desc.format; + } + let mips = u32::from(r.desc.mips.max(1)); + let mip = mip.min(mips - 1); + let size = ( + (r.desc.width as u32 >> mip).max(1), + (r.desc.height >> mip).max(1), + ); + Some((mip + slice * mips, z, size, format)) + } + + /// Width and height of the presented picture. + pub fn picture_size(&self) -> Option<(u32, u32)> { + self.frame.presents.last().map(|p| (p.width, p.height)) + } + + /// Says which commands change the texels under points of the picture. + pub fn pixel(&mut self, o: &Options, p: &Pixels, say: &mut dyn FnMut(String)) -> Result<()> { + let picture = self.picture_size().context("no picture was presented")?; + self.set_merging(o.merge)?; + let mut report = Report::default(); + let submits = self.edited(o, &mut report, &[]); + let counts = self.counts_of(o, p, &submits)?; + let mut samples: Vec = Vec::new(); + let made = self.sampled(p, &submits, picture, &counts, &mut samples)?; + let bytes = self.probed(o, &made, samples.len() as u64 * ROOM)?; + say(format!( + "{} texels taken; picture {}x{}; points {:?}", + samples.len(), + picture.0, + picture.1, + p.points + )); + report.notes.drain(..).for_each(&mut *say); + let mut last: HashMap<(u32, u32, (u32, u32), usize), Vec> = HashMap::new(); + let mut said = None; + for (i, s) in samples.iter().enumerate() { + let t = &s.spot; + let n = texel_bytes(t.format).max(1); + let now = bytes[i * ROOM as usize..][..n].to_vec(); + let was = last.insert((t.res, t.sub, (t.x, t.y), t.point), now.clone()); + if was.as_ref() == Some(&now) { + continue; + } + let point = match t.point { + OWN => String::new(), + n => format!("point {n} "), + }; + let spot = format!( + " {point}{} sub {} at {},{}:", + self.called(t.res), + t.sub, + t.x, + t.y + ); + let now = texel_text(t.format, &now); + if s.before { + // Seen for the first time, or changed by what is not looked + // into. + if was.is_some() { + say(format!("{spot} changed unseen to {now}")); + } + continue; + } + if said != Some((s.list, s.command, s.part)) { + said = Some((s.list, s.command, s.part)); + let part = match p.split.contains(&(s.list, s.command as u32)) { + true => format!(" draw {}", s.part), + false => String::new(), + }; + let of = match s.pso { + NONE => String::new(), + pso => format!(" of {pso} {}", self.pipeline_name(pso)), + }; + say(format!("{}:{}{part} {}{of}", s.list, s.command, s.what)); + } + let was = was.map_or("?".to_owned(), |w| texel_text(t.format, &w)); + say(format!("{spot} {was} -> {now}")); + } + Ok(()) + } + + /// Runs the frame with commands that copy to [`PROBE`], which is of + /// `len` bytes; its bytes after that. + fn probed(&mut self, o: &Options, submits: &[Vec>], len: u64) -> Result> { + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + len.max(4), + D3D12_RESOURCE_FLAG_NONE, + )?; + self.extra.insert(PROBE, back); + self.restore(o.restore)?; + let built = self.build(submits, o)?; + self.fresh = false; + self.send(&built, o)?; + // SAFETY: the mapping; the copies into it have run. + let bytes = unsafe { std::slice::from_raw_parts(data, len as usize) }.to_vec(); + self.extra.remove(&PROBE); + Ok(bytes) + } + + /// How many draws the calls to be split have. + fn counts_of( + &mut self, + o: &Options, + p: &Pixels, + submits: &[Vec>], + ) -> Result> { + let mut counts = HashMap::new(); + if p.split.is_empty() { + return Ok(counts); + } + const ARGS: u32 = 0x200; + let mut made = submits.to_vec(); + let mut asked: Vec<(u32, u32)> = Vec::new(); + for (here, cmds) in made.iter_mut().flatten().enumerate() { + let mut out = Vec::new(); + for (n, c) in std::mem::take(cmds).into_iter().enumerate() { + let key = (here as u32, n as u32); + if let Cmd::Indirect { + most, + count, + count_at, + .. + } = c + && p.split.contains(&key) + { + counts.insert(key, most); + if count != NONE { + out.push(Cmd::Barriers { + all: vec![transition(count, ALL, ARGS, COPY_SOURCE)], + }); + out.push(Cmd::CopyBuffer { + dst: PROBE, + dst_at: asked.len() as u64 * 4, + src: count, + src_at: count_at, + len: 4, + }); + out.push(Cmd::Barriers { + all: vec![transition(count, ALL, COPY_SOURCE, ARGS)], + }); + asked.push(key); + } + } + out.push(c); + } + *cmds = out; + } + let bytes = self.probed(o, &made, asked.len() as u64 * 4)?; + for (key, n) in asked.iter().zip(bytes.chunks_exact(4)) { + if let Some(most) = counts.get_mut(key) { + *most = (*most).min(u32::from_le_bytes([n[0], n[1], n[2], n[3]])); + } + } + Ok(counts) + } + + fn textures(&self, picture: (u32, u32)) -> Textures { + let textures = || { + self.frame + .resources + .iter() + .filter(|r| self.texture(r.id).is_some()) + }; + let shaped = textures() + .filter(|r| { + let d = &r.desc; + d.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 + && d.flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0 + && d.width as u32 * 4 >= picture.0 + && same_shape( + (d.width as f32, d.height as f32), + (picture.0 as f32, picture.1 as f32), + ) + }) + .map(|r| r.id) + .collect(); + let copied_as = textures() + .map(|r| { + let f = gpu::footprints(&self.device, &gpu::to_desc(&r.desc), 0, 1).0; + (r.id, f[0].Footprint.Format.0) + }) + .collect(); + Textures { + copied_as, + shaped, + drawn: HashMap::new(), + } + } + + /// The spots of a texture (of its subresource `sub`) that is written not + /// as a target. + fn spots_of( + &self, + p: &Pixels, + t: &Textures, + picture: (u32, u32), + id: u32, + sub: u32, + out: &mut Vec, + ) { + let Some(r) = self.texture(id) else { return }; + let depth = r.desc.flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0; + for &(res, at, x, y) in &p.texels { + if res == id && (sub == at || sub == ALL) { + out.push(Spot { + res, + sub: at, + x, + y, + z: 0, + point: OWN, + format: r.desc.format, + depth, + }); + } + } + if r.desc.dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 || !(sub == 0 || sub == ALL) { + return; + } + let size = (r.desc.width as u32, r.desc.height); + let whole = [0.0, 0.0, size.0 as f32, size.1 as f32]; + let view = t.drawn.get(&size).copied().unwrap_or(whole); + for (point, at) in p.points.iter().enumerate() { + if let Some((x, y)) = texel(*at, picture, view, size) { + out.push(Spot { + res: id, + sub: 0, + x, + y, + z: 0, + point, + format: r.desc.format, + depth, + }); + } + } + } + + /// Whether a texture is the one in use of those that share its memory. + fn in_use(&self, states: &States, id: u32) -> bool { + self.objects.get(&id).is_some_and(|o| { + !self.frame.resources[o.index].idle || states.used.contains_key(&id) + }) + } + + /// The commands that copy the texels of `spots` to [`PROBE`] from `first` + /// on; `copied`: a copy to them went before. + fn take( + &self, + spots: &[Spot], + first: u64, + states: &States, + t: &Textures, + copied: bool, + scratch: &mut u64, + out: &mut Vec, + ) { + let (mut to, mut from, mut copies) = (Vec::new(), Vec::new(), Vec::new()); + let mut moved = HashSet::new(); + for (i, s) in spots.iter().enumerate() { + let Some(r) = self.texture(s.res) else { + continue; + }; + let all = states.get(s.res).unwrap_or(vec![COMMON]); + let mut state = all + .get(s.sub as usize) + .or(all.first()) + .copied() + .unwrap_or(COMMON); + if copied && state == COMMON { + state = COPY_DEST; + } + if state & COPY_SOURCE == 0 && moved.insert((s.res, s.sub)) { + to.push(transition(s.res, s.sub, state, COPY_SOURCE)); + from.push(transition(s.res, s.sub, COPY_SOURCE, state)); + } + let offset = (first + i as u64) * ROOM; + if !s.depth { + copies.push(Cmd::CopyTexture { + dst: Loc::Placed { + res: PROBE, + offset, + format: t.copied_as.get(&s.res).copied().unwrap_or(r.desc.format), + size: [1, 1, 1], + pitch: 256, + }, + at: [0; 3], + src: Loc::Sub { + res: s.res, + sub: s.sub, + }, + part: Some([s.x, s.y, s.z, s.x + 1, s.y + 1, s.z + 1]), + }); + continue; + } + // Depth is only copied whole. + let mip = s.sub % u32::from(r.desc.mips.max(1)); + let w = (r.desc.width as u32 >> mip).max(1); + let h = (r.desc.height >> mip).max(1); + let bytes = texel_bytes(s.format) as u64; + let pitch = (w * bytes as u32).next_multiple_of(256); + *scratch = (*scratch).max(u64::from(pitch) * u64::from(h)); + copies.push(Cmd::CopyTexture { + dst: Loc::Placed { + res: SCRATCH, + offset: 0, + format: t.copied_as.get(&s.res).copied().unwrap_or(r.desc.format), + size: [w, h, 1], + pitch, + }, + at: [0; 3], + src: Loc::Sub { + res: s.res, + sub: s.sub, + }, + part: None, + }); + copies.push(Cmd::Barriers { + all: vec![transition(SCRATCH, ALL, COPY_DEST, COPY_SOURCE)], + }); + copies.push(Cmd::CopyBuffer { + dst: PROBE, + dst_at: offset, + src: SCRATCH, + src_at: u64::from(pitch) * u64::from(s.y) + u64::from(s.x) * bytes, + len: bytes, + }); + copies.push(Cmd::Barriers { + all: vec![transition(SCRATCH, ALL, COPY_SOURCE, COPY_DEST)], + }); + } + if !to.is_empty() { + out.push(Cmd::Barriers { all: to }); + } + out.extend(copies); + if !from.is_empty() { + out.push(Cmd::Barriers { all: from }); + } + } + + /// The frame's lists with copies of texels after commands. + fn sampled( + &mut self, + p: &Pixels, + submits: &[Vec>], + picture: (u32, u32), + counts: &HashMap<(u32, u32), u32>, + samples: &mut Vec, + ) -> Result>>> { + let strides: HashMap = self + .frame + .signatures + .iter() + .map(|s| (s.id, s.stride)) + .collect(); + let dispatching: HashSet = self + .frame + .signatures + .iter() + .filter(|s| { + s.args + .iter() + .any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32) + }) + .map(|s| s.id) + .collect(); + let mut t = self.textures(picture); + let mut states = self.start_states(); + let mut known: HashSet = HashSet::new(); + let mut made = Vec::new(); + let mut here = 0; + let mut scratch = 0u64; + for lists in submits { + let mut out_lists = Vec::new(); + for cmds in lists { + let wanted = p.lists.is_none_or(|(a, b)| (a..=b).contains(&here)); + let mut out = Vec::with_capacity(cmds.len()); + let mut pso = NONE; + let mut targets: Vec = Vec::new(); + let mut view: Option<[f32; 4]> = None; + for (n, c) in cmds.iter().enumerate() { + match c { + Cmd::Pipeline { pso: id } => pso = *id, + Cmd::Targets { colors, depth } => { + targets = colors.iter().chain(depth).copied().collect(); + } + Cmd::Viewports { all } => { + view = all.first().map(|v| [v[0], v[1], v[2], v[3]]); + } + _ => {} + } + let dispatches = matches!(c, Cmd::Dispatch { .. }) + || matches!(c, Cmd::Indirect { signature, .. } if dispatching.contains(signature)); + let draws = c.runs_shaders() && !dispatches; + let mut spots: Vec = Vec::new(); + let looked = wanted && c.works() && samples.len() < MOST; + for s in targets.iter().filter(|_| looked && draws) { + let Some((sub, z, size, format)) = self.seen_by(s) else { + continue; + }; + let depth = s.kind == slot::DSV; + let spot = |x, y, point| Spot { + res: s.res, + sub, + x, + y, + z, + point, + format, + depth, + }; + let view = view.unwrap_or([0.0, 0.0, size.0 as f32, size.1 as f32]); + for (point, at) in p.points.iter().enumerate() { + if let Some((x, y)) = texel(*at, picture, view, size) { + t.drawn.insert(size, view); + spots.push(spot(x, y, point)); + } + } + for &(res, at, x, y) in &p.texels { + if (res, at) == (s.res, sub) { + spots.push(spot(x, y, OWN)); + } + } + } + if looked && c.runs_shaders() { + let all = p.texels.iter().map(|t| t.0); + let some = p.written && (dispatches || !targets.is_empty()); + let all: HashSet = + all.chain(t.shaped.iter().copied().filter(|_| some)).collect(); + for id in all { + let writable = states + .get(id) + .is_some_and(|s| s.iter().any(|s| s & UNORDERED_ACCESS != 0)); + if writable && self.in_use(&states, id) { + self.spots_of(p, &t, picture, id, ALL, &mut spots); + } + } + } + let mut copied = false; + if looked { + let mut to = None; + match c { + Cmd::CopyTexture { + dst: Loc::Sub { res, sub }, + .. + } => to = Some((*res, *sub, true)), + Cmd::CopyResource { dst, .. } => to = Some((*dst, ALL, true)), + Cmd::Resolve { dst, dst_sub, .. } + | Cmd::ResolveRegion { dst, dst_sub, .. } => { + to = Some((*dst, *dst_sub, false)); + } + Cmd::ClearTarget { view, .. } | Cmd::ClearDepth { view, .. } => { + to = self.seen_by(view).map(|s| (view.res, s.0, false)); + } + _ => {} + } + if let Some((res, sub, is_copy)) = to { + copied = is_copy; + self.spots_of(p, &t, picture, res, sub, &mut spots); + } + } + let mut seen = HashSet::new(); + spots.retain(|s| { + (p.depth || !s.depth) && texel_bytes(s.format) > 0 && seen.insert(*s) + }); + let what = match c { + Cmd::Draw { .. } => "Draw", + Cmd::DrawIndexed { .. } => "DrawIndexed", + Cmd::DispatchMesh { .. } => "DispatchMesh", + Cmd::Dispatch { .. } => "Dispatch", + Cmd::Indirect { .. } if dispatches => "indirect Dispatch", + Cmd::Indirect { .. } => "indirect draw", + Cmd::ClearTarget { .. } | Cmd::ClearDepth { .. } => "clear", + Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolve", + _ => "copy", + }; + let runs = if c.runs_shaders() { pso } else { NONE }; + let mut take = |before: bool, part: u32, spots: &[Spot], out: &mut Vec| { + let first = samples.len() as u64; + self.take(spots, first, &states, &t, copied && !before, &mut scratch, out); + samples.extend(spots.iter().map(|spot| Sample { + list: here, + command: n, + part, + before, + spot: *spot, + pso: runs, + what, + })); + }; + // What was not seen before this command, as it is now. + let new: Vec = + spots.iter().filter(|s| known.insert(**s)).copied().collect(); + if !new.is_empty() { + take(true, 0, &new, &mut out); + } + match (counts.get(&(here, n as u32)), c) { + (Some(&count), Cmd::Indirect { signature, .. }) => { + let stride = strides.get(signature).copied().unwrap_or(0); + for i in 0..count { + out.push(part_of(c, i, stride)); + take(false, i, &spots, &mut out); + } + } + _ => { + out.push(c.clone()); + if !spots.is_empty() { + take(false, 0, &spots, &mut out); + } + } + } + let mut all = Vec::new(); + states::changes(c, &mut all); + all.iter().for_each(|c| states.change(c)); + } + out_lists.push(out); + here += 1; + } + states.decay(); + made.push(out_lists); + } + if scratch > 0 { + let buffer = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_DEFAULT, + scratch, + D3D12_RESOURCE_FLAG_NONE, + )?; + self.extra.insert(SCRATCH, buffer.0); + } + Ok(made) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn points_lie_in_viewports_of_the_pictures_shape() { + let whole = |w: u32, h: u32| ([0.0, 0.0, w as f32, h as f32], (w, h)); + let picture = (3840, 2160); + let (view, size) = whole(1920, 1080); + assert_eq!(texel((3839, 2159), picture, view, size), Some((1919, 1079))); + assert_eq!(texel((0, 0), picture, view, size), Some((0, 0))); + let (view, size) = whole(2048, 2048); + assert_eq!(texel((0, 0), picture, view, size), None); + // A part of a larger target. + let part = [0.0, 0.0, 1920.0, 1080.0]; + assert_eq!( + texel((1920, 1080), picture, part, (3840, 2160)), + Some((960, 540)) + ); + let beside = [1920.0, 0.0, 1920.0, 1080.0]; + assert_eq!(texel((1920, 1080), picture, beside, (1920, 1080)), None); + } + + #[test] + fn texels_are_read() { + assert_eq!( + texel_text(41, &1.5f32.to_le_bytes()), + "1.50000 [00, 00, c0, 3f]" + ); + assert_eq!( + texel_text(28, &[255, 0, 0, 51]), + "1.00000 0.00000 0.00000 0.20000 [ff, 00, 00, 33]" + ); + assert!( + texel_text(10, &[0, 0x3C, 0, 0xBC, 0, 0, 0, 0x38]) + .starts_with("1.00000 -1.00000 0.00000 0.50000 ") + ); + let v = 0x3C0u32 | 0x380 << 11 | 0x200 << 22; + assert!(texel_text(26, &v.to_le_bytes()).starts_with("1.00000 0.50000 2.00000 ")); + assert_eq!(texel_text(42, &[1, 2, 3, 4]), "[01, 02, 03, 04]"); + // Too few bytes, or a format that is not read. + assert_eq!(texel_text(41, &[1]), "[01]"); + assert_eq!(texel_text(98, &[1, 2]), "[01, 02]"); + } + + #[test] + fn an_indirect_draw_is_taken_apart() { + let all = Cmd::Indirect { + signature: 1, + most: 8, + args: 2, + at: 100, + count: 3, + count_at: 4, + }; + let one = Cmd::Indirect { + signature: 1, + most: 1, + args: 2, + at: 124, + count: NONE, + count_at: 0, + }; + assert_eq!(part_of(&all, 2, 12), one); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 1b74262..3cdd30f 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -585,7 +585,7 @@ pub(crate) fn family(format: u32) -> u32 { (44, 47), (48, 52), (53, 59), - (60, 65), + (60, 64), (70, 72), (73, 75), (76, 78), @@ -695,8 +695,7 @@ const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint { row_pitch: 0, }; -/// One subresource's size in an upload buffer: footprint (offset 0), rows -/// and bytes per row. Planes of depth-stencil formats are not told apart. +/// One subresource's upload footprint (offset 0), row count and unpadded row size. fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> { const PITCH: u64 = 256; if desc.dimension == BUFFER { @@ -716,11 +715,18 @@ fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, } else { u32::from(desc.depth_or_array_size).max(1) }; - let (mip, slice) = (index % mips, index / mips); - if slice >= slices { - return None; - } - let (element, block) = element(desc.format)?; + let mip = index % mips; + let plane = index / mips / slices; + let depth_stencil = matches!(desc.format, 19..=22 | 44..=47); + // Each plane contains all the mip levels and array slices. Depth and + // stencil copies use separate formats and 512-byte row alignment. + let (format, pitch_alignment) = match (depth_stencil, plane) { + (true, 0) => (39, 512), // DXGI_FORMAT_R32_TYPELESS + (true, 1) => (60, 512), // DXGI_FORMAT_R8_TYPELESS + (false, 0) => (desc.format, PITCH), + _ => return None, + }; + let (element, block) = element(format)?; let width = (desc.width >> mip).max(1).next_multiple_of(block); let height = (u64::from(desc.height) >> mip) .max(1) @@ -733,18 +739,18 @@ fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, let row_size = width / block * element; let footprint = PlacedFootprint { offset: 0, - format: desc.format, + format, width: u32::try_from(width).ok()?, height: u32::try_from(height).ok()?, depth, - row_pitch: u32::try_from(row_size.next_multiple_of(PITCH)).ok()?, + row_pitch: u32::try_from(row_size.next_multiple_of(pitch_alignment)).ok()?, }; Some((footprint, u32::try_from(height / block).ok()?, row_size)) } -/// Device method: where each subresource goes in an upload buffer, rows -/// 256-byte and subresources 512-byte aligned, as on PC. Unknown sizes give -/// the documented all-ones values. +/// Places subresources at 512-byte boundaries in an upload buffer. +/// Row pitch is aligned to 512 bytes for depth/stencil planes and 256 bytes +/// otherwise. Unknown sizes give the documented all-ones values. pub(crate) extern "system" fn copyable_footprints( _: This, desc: *const ResourceDesc, @@ -2559,6 +2565,22 @@ mod tests { use super::*; use crate::object::slot; + #[test] + fn a8_unorm_is_not_in_the_r8_typeless_family() { + // DXGI_FORMAT values: 60 R8_TYPELESS, 61 R8_UNORM, 62 R8_UINT, + // 63 R8_SNORM, 64 R8_SINT, 65 A8_UNORM. The R8 typeless family is + // 60..=64; A8_UNORM has no typeless family and cannot be cast to R8, + // so it must stand alone rather than fold into R8_TYPELESS. + assert_eq!(family(60), 60); + for f in 61..=64 { + assert_eq!(family(f), 60); + } + assert_eq!(family(65), 65); + // Boundaries: 59 belongs to the preceding family, 66 is unmapped. + assert_eq!(family(59), 53); + assert_eq!(family(66), 66); + } + type Release = extern "system" fn(This) -> u32; type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT; type Address = extern "system" fn(This) -> u64; @@ -2790,6 +2812,55 @@ mod tests { assert_eq!(t, u64::MAX, "no second subresource"); } + #[test] + fn depth_stencil_footprints_follow_the_pc_plane_order() { + // Native D3D12 reports the same layout for both depth/stencil families + // and their view formats. Mips vary fastest, then array slices, then planes. + let expected = [ + (512, 39, 16, 8), + (4_608, 39, 8, 4), + (6_656, 39, 16, 8), + (10_752, 39, 8, 4), + (12_800, 60, 16, 8), + (16_896, 60, 8, 4), + (18_944, 60, 16, 8), + (23_040, 60, 8, 4), + ]; + for format in (19..=22).chain(44..=47) { + let desc = ResourceDesc { + depth_or_array_size: 2, + ..texture(16, 8, format, 2) + }; + let mut layouts = [NO_FOOTPRINT; 8]; + let (mut rows, mut sizes, mut total) = ([0; 8], [0; 8], 0); + copyable_footprints( + std::ptr::null(), + &desc, + 0, + 8, + 512, + layouts.as_mut_ptr(), + rows.as_mut_ptr(), + sizes.as_mut_ptr(), + &mut total, + ); + + assert_eq!( + layouts.map(|l| (l.offset, l.format, l.width, l.height)), + expected, + "format {format}" + ); + assert!( + layouts.iter().all(|l| l.depth == 1 && l.row_pitch == 512), + "format {format}" + ); + assert_eq!(rows, [8, 4, 8, 4, 8, 4, 8, 4], "format {format}"); + assert_eq!(sizes, [64, 32, 64, 32, 16, 8, 16, 8], "format {format}"); + assert_eq!(total, 24_072, "format {format}"); + assert!(subresource(&desc, 8).is_none(), "format {format}"); + } + } + /// A 4x4 texture filled from a title buffer through our list and queue, /// then read back from the host GPU. #[cfg(windows)] diff --git a/crates/victory-gpu/src/safecopy.rs b/crates/victory-gpu/src/safecopy.rs index aa331eb..66bb68a 100644 --- a/crates/victory-gpu/src/safecopy.rs +++ b/crates/victory-gpu/src/safecopy.rs @@ -75,46 +75,6 @@ std::arch::global_asm!( "vzeroupper", "xor eax, eax", "ret", - ".globl victory_safe_update", - ".globl victory_safe_update_at", - ".globl victory_safe_update_after", - ".globl victory_safe_update_failed", - // rcx destination, rdx source, r8 bytes (whole 64s, not none), r9 where - // the offset of the first 64 bytes that differed goes (-1: none did) and - // behind it the offset of the end of the last: stores the 64s that - // differ. eax: whether all could be read. - "victory_safe_update:", - "xor r10d, r10d", - "mov r11, -1", - "xor eax, eax", - "2:", - "victory_safe_update_at:", - "vmovdqu ymm0, ymmword ptr [rdx + r10]", - "vmovdqu ymm1, ymmword ptr [rdx + r10 + 32]", - "victory_safe_update_after:", - "vpxor ymm2, ymm0, ymmword ptr [rcx + r10]", - "vpxor ymm3, ymm1, ymmword ptr [rcx + r10 + 32]", - "vpor ymm2, ymm2, ymm3", - "vptest ymm2, ymm2", - "jz 3f", - "vmovdqu ymmword ptr [rcx + r10], ymm0", - "vmovdqu ymmword ptr [rcx + r10 + 32], ymm1", - "cmp r11, -1", - "cmove r11, r10", - "lea rax, [r10 + 64]", - "3:", - "add r10, 64", - "cmp r10, r8", - "jb 2b", - "mov qword ptr [r9], r11", - "mov qword ptr [r9 + 8], rax", - "vzeroupper", - "mov eax, 1", - "ret", - "victory_safe_update_failed:", - "vzeroupper", - "xor eax, eax", - "ret", ".globl victory_safe_merge", ".globl victory_safe_merge_at", ".globl victory_safe_merge_after", @@ -185,63 +145,12 @@ unsafe extern "system" { fn victory_safe_put_at(); fn victory_safe_put_after(); fn victory_safe_put_failed(); - fn victory_safe_update(dst: *mut u8, src: *const u8, len: usize, changed: *mut [usize; 2]) -> u32; - fn victory_safe_update_at(); - fn victory_safe_update_after(); - fn victory_safe_update_failed(); fn victory_safe_merge(title: *mut u8, now: *const u8, held: *mut u8, blocks: usize, counts: *mut [u64; 2]) -> usize; fn victory_safe_merge_at(); fn victory_safe_merge_after(); fn victory_safe_merge_failed(); } -/// What [`update`] found. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Updated { - /// Every byte was the same already; nothing was stored. - Same, - /// The bytes that changed lie in these offsets. - Changed(usize, usize), - /// Not all of the source could be read; some may have been copied. - Failed, -} - -/// Makes `dst` hold what `src` holds, storing only what differs. The source -/// may change meanwhile: what is compared is what is stored, read once. -/// -/// # Safety -/// As [`copy`]'s, and the destination is memory of ours that nothing else -/// writes. -pub(crate) unsafe fn update(dst: *mut u8, src: *const u8, len: usize) -> Updated { - let whole = len / 64 * 64; - let (mut from, mut to) = (usize::MAX, 0); - if whole > 0 { - let mut changed = [usize::MAX, 0]; - // SAFETY: the source's faults leave through the failing exit; the - // rest is the caller's. - if unsafe { victory_safe_update(dst, src, whole, &mut changed) } == 0 { - return Updated::Failed; - } - [from, to] = changed; - } - if whole < len { - let mut rest = [0u8; 64]; - let rest = &mut rest[..len - whole]; - // SAFETY: as above; `rest` is ours. - unsafe { - if !copy(rest.as_mut_ptr(), src.add(whole), rest.len()) { - return Updated::Failed; - } - let held = std::slice::from_raw_parts_mut(dst.add(whole), rest.len()); - if held != rest { - held.copy_from_slice(rest); - (from, to) = (from.min(whole), len); - } - } - } - if from >= to { Updated::Same } else { Updated::Changed(from, to) } -} - /// What [`merge`] did. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct Merged { @@ -445,10 +354,6 @@ pub(crate) fn failing_exit(at: usize) -> Option { if (from..to).contains(&at) { return Some(victory_safe_put_failed as *const () as usize); } - let (from, to) = (victory_safe_update_at as *const () as usize, victory_safe_update_after as *const () as usize); - if (from..to).contains(&at) { - return Some(victory_safe_update_failed as *const () as usize); - } let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize); (from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize) } @@ -504,52 +409,6 @@ mod tests { } } - /// An update makes the two the same, says where they differed (to 64 - /// bytes), stores nothing where they did not, and fails at a page that - /// is not there. - #[test] - fn updates_store_what_differs() { - assert!(on()); - let (src, dst) = (Pages::new(1 << 14), Pages::new(1 << 14)); - for len in [0usize, 1, 63, 64, 65, 200, 4096, 5000] { - for (da, sa) in [(0usize, 0usize), (3, 0), (0, 5)] { - for changed in [vec![], vec![0usize], vec![len / 2], vec![len.saturating_sub(1)], vec![1, len / 3, len / 2]] { - src.fill(); - // SAFETY: inside the two allocations. - unsafe { - std::ptr::write_bytes(dst.0, 0xEE, dst.1); - std::ptr::copy_nonoverlapping(src.0.add(sa), dst.0.add(da), len); - let at: std::collections::BTreeSet = changed.iter().copied().filter(|&i| i < len).collect(); - for &i in &at { - *src.0.add(sa + i) ^= 0x40; - } - let found = update(dst.0.add(da), src.0.add(sa), len); - match (at.iter().min(), at.iter().max()) { - (Some(&first), Some(&last)) => { - let Updated::Changed(from, to) = found else { - panic!("{len} {at:?}: {found:?}") - }; - assert_eq!(from, first / 64 * 64); - assert_eq!(to, ((last / 64 + 1) * 64).min(len)); - } - _ => assert_eq!(found, Updated::Same), - } - let (to, from) = (std::slice::from_raw_parts(dst.0, dst.1), std::slice::from_raw_parts(src.0, src.1)); - assert_eq!(to[da..da + len], from[sa..sa + len]); - assert!(to[..da].iter().chain(&to[da + len..]).all(|&x| x == 0xEE)); - } - } - } - } - // SAFETY: our allocation. - unsafe { - VirtualFree(src.0.add(4096).cast(), 4096, MEM_DECOMMIT); - assert_eq!(update(dst.0, src.0, 8192), Updated::Failed); - assert_eq!(update(dst.0, src.0.add(4096), 10), Updated::Failed); - assert_ne!(update(dst.0, src.0, 4096), Updated::Failed); - } - } - /// The dwords that changed are stored, and no byte of any other, at /// every alignment and length; a page that is not there fails. #[test] diff --git a/crates/victory-gpu/src/sampler.rs b/crates/victory-gpu/src/sampler.rs index ee95da3..2132273 100644 --- a/crates/victory-gpu/src/sampler.rs +++ b/crates/victory-gpu/src/sampler.rs @@ -47,30 +47,58 @@ impl Fields { } else { linear(self.min) << 4 | linear(self.mag) << 2 | u32::from(self.mip == 2) }; + let min_lod = finite_lod(self.min_lod, 0.0); + // Without a mip filter the console clamps sampling to `min_lod`. + let max_lod = if self.mip == 0 { + min_lod + } else { + finite_lod(self.max_lod, min_lod).max(min_lod) + }; D3D12_SAMPLER_DESC { Filter: D3D12_FILTER((reduction << 7 | filter) as i32), - AddressU: D3D12_TEXTURE_ADDRESS_MODE(self.address[0] as i32), - AddressV: D3D12_TEXTURE_ADDRESS_MODE(self.address[1] as i32), - AddressW: D3D12_TEXTURE_ADDRESS_MODE(self.address[2] as i32), - MipLODBias: self.bias, + AddressU: address_mode(self.address[0]), + AddressV: address_mode(self.address[1]), + AddressW: address_mode(self.address[2]), + MipLODBias: if self.bias.is_nan() { + 0.0 + } else { + self.bias + .clamp(D3D12_MIP_LOD_BIAS_MIN, D3D12_MIP_LOD_BIAS_MAX) + }, MaxAnisotropy: if aniso { self.anisotropy.clamp(1, 16) } else { 1 }, - ComparisonFunc: D3D12_COMPARISON_FUNC(self.compare.max(1) as i32), - BorderColor: self.border, - MinLOD: self.min_lod, - // Without a mip filter the console samples mip 0 only. - MaxLOD: if self.mip == 0 { - self.min_lod + ComparisonFunc: if reduction == 1 { + D3D12_COMPARISON_FUNC(self.compare as i32) } else { - self.max_lod + D3D12_COMPARISON_FUNC_NEVER }, + BorderColor: self.border, + MinLOD: min_lod, + MaxLOD: max_lod, } } } +/// Maps a console address mode (`1..=5`) to host D3D12, falling back to `CLAMP`. +fn address_mode(mode: u32) -> D3D12_TEXTURE_ADDRESS_MODE { + match mode { + 1..=5 => D3D12_TEXTURE_ADDRESS_MODE(mode as i32), + _ => D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + } +} + +/// Sanitizes an LOD bound for D3D12, substituting `fallback` for `NaN` and clamping infinities. +fn finite_lod(value: f32, fallback: f32) -> f32 { + if value.is_nan() { + fallback + } else { + value.clamp(-D3D12_FLOAT32_MAX, D3D12_FLOAT32_MAX) + } +} + /// The console's sampler description (27 words): flags, magnification, /// minification, mip and depth filters, filter mode, three address modes, /// minimum and maximum LOD, LOD bias, secondary bias, anisotropy, its bias @@ -116,4 +144,86 @@ mod tests { w[16] = 1; assert_eq!(console(&w).Filter.0, 0x5); } + + #[test] + fn mip_none_clamps_to_min_lod_and_inverted_lod_range_clamps() { + let mut w = [0u32; 27]; + w[3] = 0; // mip none + w[9] = 3.0f32.to_bits(); + w[10] = 8.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (3.0, 3.0)); + + w[9] = f32::NAN.to_bits(); + w[10] = 8.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (0.0, 0.0)); + + w[9] = f32::INFINITY.to_bits(); + w[10] = 8.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (D3D12_FLOAT32_MAX, D3D12_FLOAT32_MAX)); + + w[3] = 2; // linear mips + w[9] = 4.0f32.to_bits(); + w[10] = 1.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (4.0, 4.0)); + + w[9] = f32::NAN.to_bits(); + w[10] = f32::INFINITY.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (0.0, D3D12_FLOAT32_MAX)); + + w[9] = 2.5f32.to_bits(); + w[10] = f32::NAN.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (2.5, 2.5)); + + w[9] = f32::NEG_INFINITY.to_bits(); + w[10] = f32::NEG_INFINITY.to_bits(); + let d = console(&w); + assert_eq!( + (d.MinLOD, d.MaxLOD), + (-D3D12_FLOAT32_MAX, -D3D12_FLOAT32_MAX) + ); + } + + #[test] + fn bias_address_and_comparison_stay_in_host_bounds() { + let mut w = [0u32; 27]; + w[6..9].copy_from_slice(&[0, 6, 3]); + w[11] = 24.0f32.to_bits(); + w[16] = 99; + let d = console(&w); + assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MAX); + assert_eq!( + [d.AddressU, d.AddressV, d.AddressW], + [D3D12_TEXTURE_ADDRESS_MODE_CLAMP; 3] + ); + assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER); + + w[11] = (-24.0f32).to_bits(); + w[5] = 1; // minimum reduction + w[16] = 4; // less-or-equal, ignored when reduction != 1 + let d = console(&w); + assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MIN); + assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER); + + w[11] = f32::NAN.to_bits(); + w[5] = 0; // plain mode, reduction == 1 from compare == 4 + w[6..9].copy_from_slice(&[1, 4, 5]); + w[16] = 4; + let d = console(&w); + assert_eq!(d.MipLODBias, 0.0); + assert_eq!( + [d.AddressU, d.AddressV, d.AddressW], + [ + D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE_BORDER, + D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE, + ] + ); + assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_LESS_EQUAL); + } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index ecd779b..83298f7 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -939,6 +939,8 @@ fn give_back(v: Vec) { } const NOT_WATCHED: u8 = 2; +/// Watched, not by the kernel but by the guards, when last asked about. +const GUARDED: u8 = 3; /// Where `a` and `b` (of one length) first differ, compared eight bytes at /// a time. @@ -1505,30 +1507,34 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { runs } -/// Whether pages of a copy in the card's memory that a refresh takes again -/// go up to the card only where they are not what the CPU's side holds -/// already (`VICTORY_SEND_CHANGED=1`; off by default). +/// Whether a refresh of a copy in the card's memory takes, and sends up, +/// the dwords that title memory changed and no others +/// (`VICTORY_SEND_CHANGED=0`: the 64 KiB pages written since it last took +/// them, whole, as before). /// -/// A refresh copies the 64 KiB pages that were written since it last took -/// them, and all of each went up and was hashed there again. Most of them -/// the title did not write: the relay put what shaders wrote into title -/// memory, and the card and the CPU's side hold those bytes already -/// ([`Shadow::card_merge_relay`]). Run record-1: 1,500 pieces (98 MB) a -/// frame fetched from the card, 103 MB in 328 ranges sent up, 322 hash -/// passes, while the title's own writes took some 260 guards off. +/// A page that counts as written is mostly not the title's doing, or not all +/// of it: a word the title wrote, and around it what shaders wrote and the +/// title never touched; or only what the relay put into title memory, which +/// the card and the CPU's side hold already ([`Shadow::card_merge_relay`]). +/// Sent up whole, such a page goes over whatever the card holds there that +/// did not come back yet, or never will (a write through a view nobody +/// declared): what stood on the card, newer, was gone. /// -/// What it rests on: the card's side holds what the CPU's side holds, but -/// for ranges shaders may be writing (no refresh touches them) and what is -/// still to go up. A page's first taking always goes up whole, so does one -/// that could not be read; after that every byte that changes on the CPU's -/// side goes up (the bytes compared are the bytes stored). +/// What it rests on: the CPU's side is what the card's side was last known +/// to hold, for every range no shader may be writing (no refresh touches +/// the others). So a dword goes up only if title memory holds another value +/// of it than the CPU's side, which then holds it too; title memory is read +/// once, what is compared is what is stored and sent. Dwords, not bytes: +/// no shader writes less, and the title's bytes beside a changed one in its +/// dword are those the CPU's side holds. /// -/// Why it is not on by default: a shader that writes a copy through a view -/// nobody declared (`crate::draw`, buffers picked by index) breaks that -/// rule. Taken again, its page went up over what it wrote; with the switch -/// its bytes stay, as they would on the console, until the title changes the -/// same 64 bytes: clearing them to the zeros they held before is then no -/// change. +/// A page never taken goes up whole as long as no shader's write was ever +/// declared for the copy. After that it is compared as any other: the CPU's +/// side and the card's began as zeros, both. +/// +/// What it cannot know: that the title wrote a value over the same value. +/// Where a shader wrote in between, through a view nobody declared, the +/// shader's stays. fn send_changed() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| { @@ -1536,19 +1542,19 @@ fn send_changed() -> bool { if crate::copystat::mode() != 0 { return false; } - std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") && crate::safecopy::on() + std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0") }) } -/// Since the last frame-rate line, of pages taken again into copies in the +/// Since the last frame-rate line, of pages taken into copies in the /// card's memory ([`send_changed`]): bytes compared, those of pages that -/// held the same, and bytes to go up. -static SEND: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; +/// held the same, bytes to go up, and the runs they are. +static SEND: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; /// [`SEND`], taken. #[cfg(feature = "diagnostics")] -pub(crate) fn send_stats() -> [u64; 3] { - [0, 1, 2].map(|i| SEND[i].swap(0, Ordering::Relaxed)) +pub(crate) fn send_stats() -> [u64; 4] { + [0, 1, 2, 3].map(|i| SEND[i].swap(0, Ordering::Relaxed)) } /// Whether what shaders wrote goes into title memory run by run @@ -1602,6 +1608,7 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { if crate::safecopy::on() { PUT[0].fetch_add(1, Ordering::Relaxed); PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed); + let since = crate::watch::changes(); // SAFETY: title memory; a page of it that is not there fails the // put, and the rest is put page by page. if unsafe { crate::safecopy::put_changed(at as *mut u8, title, merged) } { @@ -1610,8 +1617,14 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { let mut from = 0; while from < merged.len() { let n = (4096 - (at + from) % 4096).min(merged.len() - from); + let (was, now) = (&title[from..from + n], &merged[from..from + n]); // SAFETY: as above. - unsafe { crate::safecopy::put_changed((at + from) as *mut u8, &title[from..from + n], &merged[from..from + n]) }; + let put = || unsafe { crate::safecopy::put_changed((at + from) as *mut u8, was, now) }; + // A page that is away only while the runtime changes a mapping + // beside it gets its bytes when that is done. + if !put() && !crate::watch::again_after_change(since, put) { + crate::watch::lost("what shaders wrote", at + from, n); + } from += n; } return merged.len(); @@ -1655,7 +1668,35 @@ pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, ti #[cfg(test)] mod merge_tests { - use super::{changed_runs, dword_runs}; + use super::{changed_runs, dword_runs, put_changed}; + + /// What shaders wrote reaches a page that is away only while the runtime + /// changes a mapping; a page that stays away loses it, and nothing else. + #[test] + fn a_put_waits_for_a_change_of_mapping() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + // SAFETY: a reservation of ours, nothing of it committed. + let at = unsafe { VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert_ne!(at, 0); + put_changed(at, &[0; 64], &[3; 64]); + let (began, wait) = std::sync::mpsc::channel(); + let change = std::thread::spawn(move || { + let _changing = crate::watch::title_memory_remapping(); + began.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + // SAFETY: the reservation's first page. + assert!(!unsafe { VirtualAlloc(at as _, 4096, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + }); + wait.recv().unwrap(); + put_changed(at, &[0; 64], &[1; 64]); + change.join().unwrap(); + // SAFETY: committed by now. + assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 64) }, [1; 64]); + // SAFETY: our reservation. + unsafe { VirtualFree(at as _, 0, MEM_RELEASE) }; + } /// Whole dwords around every changed byte and no other, whatever the /// alignment; small gaps joined only when asked. @@ -2017,6 +2058,14 @@ impl Shadow { self.watched.load(Ordering::Relaxed) == NOT_WATCHED } + /// Whether a submission asks the kernel about the copy's ranges ahead: + /// not of memory that is not watched, nor of view memory, which the + /// kernel would refuse (and with it the ranges asked about together). + pub(crate) fn asked_ahead(&self) -> bool { + let watched = self.watched.load(Ordering::Relaxed); + watched != NOT_WATCHED && (watched != GUARDED || !crate::watch::light()) + } + /// The copy's own number (see the field). pub(crate) fn id(&self) -> u64 { self.id @@ -2774,7 +2823,7 @@ impl Shadow { if from >= to { return true; } - if self.watched.load(Ordering::Relaxed) != 1 { + if !matches!(self.watched.load(Ordering::Relaxed), 1 | GUARDED) { return false; } // Around ranges shaders are writing the refresh asks gap by gap. @@ -2804,7 +2853,8 @@ impl Shadow { fn update_free(&self, from: usize, to: usize) -> usize { if self.watched.load(Ordering::Relaxed) != NOT_WATCHED { if let Some((now, written)) = crate::watch::writes(from, to, true) { - self.watched.store(1, Ordering::Relaxed); + let guarded = crate::watch::guarded(from, to); + self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed); let copied = self.copy_stale(from, to, now, &written); self.refresh_check(from, to); #[cfg(feature = "diagnostics")] @@ -2982,34 +3032,47 @@ impl Shadow { /// Copies title memory `[from, to)` (inside the buffer) into the copy; /// `known`: the copy held it before ([`send_changed`]). fn take(&self, from: usize, to: usize, known: bool) -> usize { - if !known || self.card.is_none() || !send_changed() { - return self.copy(from, to); + thread_local! { + /// A page of title memory, as read. + static TITLE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } + let Some(card) = self.card.as_ref().filter(|_| send_changed()) else { + return self.copy(from, to); + }; + let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none(); let start = self.start as usize; - let mut at = from; - while at < to { - let n = (PAGE - at % PAGE).min(to - at); - // SAFETY: inside the mapping of the copy's CPU side, which - // nothing else writes there: no shader's range holds it. - let found = unsafe { crate::safecopy::update(self.data.add(at - start), at as *const u8, n) }; - SEND[0].fetch_add(n as u64, Ordering::Relaxed); - match found { - crate::safecopy::Updated::Same => { + TITLE.with_borrow_mut(|title| { + title.resize(PAGE, 0); + let mut at = from; + while at < to { + let n = (PAGE - at % PAGE).min(to - at); + let title = &mut title[..n]; + // (Pages that are not there read as zeros.) + crate::host::copy_mapped(title.as_mut_ptr(), at as *const u8, n, false); + // SAFETY: inside the mapping of the copy's CPU side, which + // nothing else reads or writes there (the card copies from + // it): no shader's range holds it, and the parts of a + // refresh lie apart. + let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) }; + let was = crate::host::upcheck::on().then(|| held.to_vec()); + let runs = if whole { vec![(0, n)] } else { dword_runs(at, held, title, 0) }; + for &(a, len) in &runs { + held[a..a + len].copy_from_slice(&title[a..a + len]); + self.changed(at - start + a, at - start + a + len); + } + self.card_changed_runs(runs.iter().map(|&(a, len)| (at - start + a, at - start + a + len))); + if let Some(was) = was { + crate::host::upcheck::note(self.id, at - start, &was, held); + } + SEND[0].fetch_add(n as u64, Ordering::Relaxed); + if runs.is_empty() { SEND[1].fetch_add(n as u64, Ordering::Relaxed); } - crate::safecopy::Updated::Changed(a, b) => { - SEND[2].fetch_add((b - a) as u64, Ordering::Relaxed); - self.changed(at - start + a, at - start + b); - self.card_changed(at - start + a, at - start + b); - } - // A page is not there: as before, around it, and all of it - // goes up. - crate::safecopy::Updated::Failed => { - self.copy(at, at + n); - } + SEND[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed); + SEND[3].fetch_add(runs.len() as u64, Ordering::Relaxed); + at += n; } - at += n; - } + }); to - from } @@ -3044,16 +3107,24 @@ impl Shadow { /// The CPU side's bytes at offsets `[from, to)` changed: they go to the /// card's side before the next submission. fn card_changed(&self, from: usize, to: usize) { + self.card_changed_runs(std::iter::once((from, to))); + } + + /// [`Shadow::card_changed`] of each of `runs`. + fn card_changed_runs(&self, runs: impl Iterator) { let Some(card) = &self.card else { return; }; - if from >= to { + let mut runs = runs.filter(|r| r.0 < r.1).peekable(); + if runs.peek().is_none() { return; } let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); - match dirty.last_mut() { - Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)), - _ => dirty.push((from, to)), + for (from, to) in runs { + match dirty.last_mut() { + Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)), + _ => dirty.push((from, to)), + } } } @@ -3379,7 +3450,7 @@ impl Shadow { // Where title memory is not mapped the CPU's side keeps what // the card wrote, as before. let merged = - unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes) }; + unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes, self) }; self.walls_merged(hi - lo, merged as usize); put += merged; } @@ -3409,7 +3480,33 @@ impl Shadow { // keeps out what else writes them. Title memory that is not there // is looked at again when the next flight that declared the range // lands. - unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes) } + unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes, self) } + } + + /// What shaders wrote in 64 KiB block `block` (of title memory) of this + /// copy was put into title memory beside the guard, which was noted as a + /// write with number `now`, `before` the number of the block's last write + /// before. If the copy held title memory's bytes of the block ahead of + /// that it holds them still, and is noted to ([`crate::land`] says why); + /// whether it was. + /// + /// That it did: it took the whole block after that write, and no other + /// came that is not noted yet. Looked at after the note, whatever comes + /// later has a number above it: a write of the title's takes the block's + /// bit, until an asking has noted it. + pub(crate) fn landed(&self, block: usize, before: u64, now: u64) -> bool { + let Some(page) = block.checked_sub(self.start as usize / PAGE) else { + return false; + }; + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let Some(at) = copied.get_mut(page) else { + return false; + }; + let held = *at != 0 && *at >= before && crate::watch::block_published(block); + if held { + *at = (*at).max(now); + } + held } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 267597e..846cb66 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -1119,6 +1119,16 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { } let start = at as usize; let end = start.saturating_add(len); + // Streamed textures lie in views of physical pages, of which the runtime + // knows which are there: one look, where the host was asked for every + // 64 KiB of the texture (and once more for each that is not there). + // `VICTORY_MAPPED_BY_VIEWS=0`: the host is asked, as before. + static BY_VIEWS: std::sync::OnceLock = std::sync::OnceLock::new(); + if *BY_VIEWS.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_VIEWS").is_none_or(|v| v != "0")) + && let Some(there) = crate::inplace::shown_bytes(start, len) + { + return there; + } if !committed(at, 1) && !committed((end - 1) as *const u8, 1) { return 0; } @@ -1417,6 +1427,40 @@ mod allocation_costs { drop(all); } + /// What a look at how much of a texture is there costs: by questions to + /// the host, and by the runtime's record of its views. + #[test] + #[ignore = "a measurement, not a check"] + fn look_costs() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const BLOCK: usize = 64 << 10; + for (name, blocks, there) in [("350 KB, all there", 6, 6), ("22 MB, all there", 350, 350), ("22 MB, 1 MB there", 350, 16)] { + let make = || { + // SAFETY: a reservation of our own, of which the first part + // is committed and touched. + unsafe { + let at = VirtualAlloc(std::ptr::null(), blocks * BLOCK, MEM_RESERVE, PAGE_READWRITE); + VirtualAlloc(at, there * BLOCK, MEM_COMMIT, PAGE_READWRITE); + std::ptr::write_bytes(at.cast::(), 1, there * BLOCK); + at as usize + } + }; + let (asked, noted) = (make(), make()); + for block in 0..there { + crate::title_memory_view(noted + block * BLOCK, BLOCK, 9, 0); + } + for (how, at) in [("asking the host", asked), ("by the views", noted)] { + const N: u32 = 200; + let began = std::time::Instant::now(); + for _ in 0..N { + assert_eq!(super::mapped_bytes(at as *const u8, blocks * BLOCK), (there * BLOCK) as u64); + } + println!("{name}, {how}: {:.1} us a look", began.elapsed().as_secs_f64() * 1e6 / f64::from(N)); + } + crate::inplace::views_gone(noted, blocks * BLOCK); + } + } + #[test] #[ignore = "a measurement, not a check"] fn allocation_costs() { diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 8c6a8be..4994739 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -140,11 +140,17 @@ fn kernel_written(first: usize, last: usize) -> Option> { &mut granularity, ) } != 0; + #[cfg(feature = "diagnostics")] + { + tally(10, u64::from(failed)); + tally(11, started.elapsed().as_nanos() as u64); + } if failed { return None; } #[cfg(feature = "diagnostics")] { + tally(12, count as u64); use crate::copystat::{C, add}; add(C::Watches, 1); add(C::WatchUs, started.elapsed().as_micros() as u64); @@ -279,13 +285,15 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { } ask_once_end(); ask_ahead(ranges); + ask_rest(ranges); +} + +/// [`ask_once`] after its [`ask_ahead`]: what that left to `writes`, and the +/// asking stands. +fn ask_rest(ranges: &[(usize, usize)]) { let _all = Asking::hold_all(); let mut ahead = { let mut j = journal_mut(); - if j.ahead.is_empty() { - // `ask_ahead` asked nothing (fewer than two ranges). - j.ahead_asked = next_asking(); - } std::mem::take(&mut j.ahead) }; // `ask_ahead` leaves a range that lies alone to `writes`, which asks @@ -307,7 +315,12 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { } } let mut j = journal_mut(); - let now = j.ahead_asked; + // A number of its own, and the one this asking stands under: between + // the two parts another thread may have asked about a range of the + // second, copied it, and the title written it since. Under the first + // part's number that write was older than the copy, and never copied. + let now = next_asking(); + j.ahead_asked = now; j.written.extend(written.into_iter().map(|page| (page, now))); j.kept = !ahead.is_empty(); j.ahead = ahead; @@ -534,6 +547,27 @@ impl Bits { } } + /// Whether a bit of `[first, last)` is set. + fn any(&self, first: usize, last: usize) -> bool { + let mut block = first; + while block < last { + let word = block / 64; + let until = ((word + 1) * 64).min(last); + let mask = (u64::MAX >> (64 - (until - block))) << (block % 64); + match self.piece(word) { + Some(piece) => { + if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::SeqCst) & mask != 0 { + return true; + } + block = until; + } + // None of the piece's. + None => block = (word / Bits::WORDS + 1) * Bits::WORDS * 64, + } + } + false + } + /// Whether the bits of all of `[first, last)` are set (not so of none). fn all(&self, first: usize, last: usize) -> bool { let mut block = first; @@ -567,18 +601,146 @@ impl Bits { /// at the journal after that finds every earlier write in it. A write that /// comes while the bit is looked at is no different from one that comes just /// after an asking: the next asking finds the block open. +/// +/// So too for the blocks of placeholders that were copied as zeros +/// (`Guards::held`): nothing can be there before the runtime maps it, and +/// it tells of that ([`title_memory_remapped`]) before the title is. static PUBLISHED: Bits = Bits::new(); +/// The blocks read-only by our hand, or about to be: set under the guards' +/// lock ahead of the protection, cleared under it when the block is open +/// again. Who finds none set has no guard to open and need not wait for the +/// lock ([`writing`]): some 700 pieces a frame are landed in memory that is +/// no view. +static PROTECTED: Bits = Bits::new(); + /// An asking made blocks of `pages` clean and noted them in the journal. fn publish(pages: &[usize]) { let g = guards(); for page in pages { - if g.clean.contains(page) { + if g.clean.contains(page) || g.held.contains(page) { PUBLISHED.set(*page); } } } +/// Whether placeholders are known for what they are (`VICTORY_KNOWN_HOLES=0`: +/// every hole is looked at at every asking, as before). +/// +/// Most ranges asked about have holes, reservations the title maps its pages +/// into as it streams (231,000 regions, 1,125 of a frame's 1,530 asked view +/// ranges, run next1-1). Such a range was never known whole: each asking put +/// a question to Windows for each of its holes, under the guards' lock, and +/// 111 ms a frame of all threads' time went into waiting for that lock. +fn known_holes() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_KNOWN_HOLES").is_none_or(|v| v != "0") && light()) +} + +/// Whether `block` lies in a placeholder: a reservation in which pages come +/// to be only by mapping a view (or an allocation) in its place, which an +/// ordinary commit cannot do. +fn placeholder(block: usize) -> bool { + /// `MEMORY_REGION_INFORMATION` (ntddk). + #[repr(C)] + #[derive(Default)] + struct Region { + allocation_base: usize, + allocation_protect: u32, + region_type: u32, + region_size: usize, + commit_size: usize, + partition_id: usize, + node_preference: usize, + } + #[link(name = "ntdll", kind = "raw-dylib")] + unsafe extern "system" { + fn NtQueryVirtualMemory( + process: *mut std::ffi::c_void, + at: *const std::ffi::c_void, + class: u32, + out: *mut std::ffi::c_void, + len: usize, + returned: *mut usize, + ) -> i32; + } + // (Class 3 answers with the kind of memory in that word, not the flags.) + const MEMORY_REGION_INFORMATION_EX: u32 = 7; + const PLACEHOLDER_RESERVATION: u32 = 1 << 8; + let mut region = Region::default(); + // SAFETY: the answer's room and its size. + let status = unsafe { + NtQueryVirtualMemory( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + (block * BLOCK) as *const _, + MEMORY_REGION_INFORMATION_EX, + (&raw mut region).cast(), + size_of::(), + std::ptr::null_mut(), + ) + }; + status >= 0 && region.region_type & PLACEHOLDER_RESERVATION != 0 +} + +/// The runtime gave the title memory at `[at, at + len)`, allocated or +/// committed: what was known of holes there is asked again. +pub fn title_memory_allocated(at: usize, len: usize) { + if len == 0 || !known_holes() { + return; + } + let mut g = guards(); + let blocks: Vec = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + for block in blocks { + g.held.remove(&block); + PUBLISHED.clear(block); + } +} + +/// Once a frame: a hundredth of the known holes are looked at, in case one +/// was filled with nobody telling ([`title_memory_allocated`], +/// [`title_memory_remapped`]), which no title we know does. +pub(crate) fn look_at_holes() { + const PARTS: usize = 100; + if !known_holes() { + return; + } + static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let blocks: Vec = { + let g = guards(); + let from = FROM.load(std::sync::atomic::Ordering::Relaxed); + let part: Vec = g.held.range(from..).take(g.held.len() / PARTS + 1).copied().collect(); + FROM.store(part.last().map_or(0, |b| b + 1), std::sync::atomic::Ordering::Relaxed); + part + }; + let mut until = 0; + for block in blocks { + if block >= until { + until = uncommitted_end(block); + } + if block >= until { + // (Or unmapped memory was mapped since the part was taken: told + // already, and forgotten.) + let mut g = guards(); + if g.held.remove(&block) { + PUBLISHED.clear(block); + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| { + tracing::warn!( + address = format_args!("{:#x}", block * BLOCK), + "a placeholder of the title's was filled with nobody telling (VICTORY_KNOWN_HOLES=0 asks every time)" + ); + }); + } + } + } +} + +/// Whether a block of `[start, end)` is view memory read-only by our hand: +/// the kernel keeps no written pages of it and would refuse an asking. +pub(crate) fn guarded(start: usize, end: usize) -> bool { + PROTECTED.any(start / BLOCK, end.div_ceil(BLOCK)) +} + /// Whether nothing of `[start, end)` can have been written since an asking /// noted it in the journal ([`PUBLISHED`]). fn published(start: usize, end: usize) -> bool { @@ -589,9 +751,11 @@ fn published(start: usize, end: usize) -> bool { /// askings and the KiB they walked; view ranges answered by their bits, by /// the guards whole clean, and block by block; blocks made read-only; blocks /// opened by ourselves; nanoseconds waiting for the guards' lock and -/// nanoseconds of changing protections (all threads). +/// nanoseconds of changing protections (all threads); questions to Windows +/// about holes; kernel askings refused; nanoseconds in kernel askings; the +/// 4 KiB pages they found written. #[cfg(feature = "diagnostics")] -static ASKS: [std::sync::atomic::AtomicU64; 9] = [const { std::sync::atomic::AtomicU64::new(0) }; 9]; +static ASKS: [std::sync::atomic::AtomicU64; 13] = [const { std::sync::atomic::AtomicU64::new(0) }; 13]; #[cfg(feature = "diagnostics")] fn tally(what: usize, n: u64) { @@ -600,7 +764,7 @@ fn tally(what: usize, n: u64) { /// [`ASKS`], taken. #[cfg(feature = "diagnostics")] -pub(crate) fn asks() -> [u64; 9] { +pub(crate) fn asks() -> [u64; 13] { std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) } @@ -622,12 +786,33 @@ struct Guards { /// Blocks already copied as zeros. While they remain wholly uncommitted, /// the copy can skip hundreds of MB of failing kernel reads per world frame. absent: BTreeSet, + /// Of those, the ones in placeholders ([`known_holes`]). + held: BTreeSet, + /// Blocks that were absent and turned out to be other memory than views + /// when something was there again: never guarded, copied every time. + foreign: BTreeSet, + /// Blocks (first, past the last) the kernel writes now + /// ([`kernel_writing`]), and blocks the runtime has unmapped in a change + /// not yet done ([`title_memory_unmapping`]). Not in the sets above, and + /// left as they are by [`guard`], which reports them written. + kernel: Vec<(usize, usize)>, + changing: Vec<(usize, usize)>, +} + +impl Guards { + fn left_alone(&self, block: usize) -> bool { + self.kernel.iter().chain(&self.changing).any(|&(first, last)| (first..last).contains(&block)) + } } static GUARDS: Mutex = Mutex::new(Guards { protected: BTreeSet::new(), clean: BTreeSet::new(), absent: BTreeSet::new(), + held: BTreeSet::new(), + foreign: BTreeSet::new(), + kernel: Vec::new(), + changing: Vec::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -687,7 +872,12 @@ pub(crate) fn landing(at: usize, len: usize) { /// before they were did so with the number of an asking made before that, /// which is under the one given here, and takes it again; noted before, a /// copy could read the older bytes with a number above the note's. -pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) { +/// +/// Returns the note's number, and for each 64 KiB block noted the number of +/// the block's last write before (0: none is known). +pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, Vec<(usize, u64)>) { + let mut before = Vec::with_capacity(spans.len()); + let noted; { let frame = crate::frame::current(); let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); @@ -699,11 +889,12 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) { { let mut j = journal_mut(); let now = next_asking(); + noted = now; let mut last = usize::MAX; for &page in pages { let block = page * KERNEL_PAGE / PAGE; if block != last { - j.written.insert(block, now); + before.push((block, j.written.insert(block, now).unwrap_or(0))); last = block; } } @@ -712,6 +903,13 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) { // A placed texture there changes with no descriptor written. crate::descriptor::host::remapped(at, len); } + (noted, before) +} + +/// Whether every write of the title's to 64 KiB block `block` so far is in +/// the journal ([`PUBLISHED`]). +pub(crate) fn block_published(block: usize) -> bool { + light() && PUBLISHED.all(block, block + 1) } /// Whether shaders' writes went into a page of `[at, at + len)` in the last @@ -751,58 +949,73 @@ 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_timed(); - let first = start / BLOCK; - g.protected.contains(&first) || g.absent.contains(&first) - }; + let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); + let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) + && (PROTECTED.any(first, first + 1) || { + let g = guards_timed(); + g.protected.contains(&first) || g.absent.contains(&first) + }); if !known && !is_view(start, end) { return None; } install(); - let mut g = guards_timed(); - let mut written = Vec::new(); - let mut run: Option = None; - let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); - // The range's clean blocks, in order: read off the set in one pass, - // not looked up one block at a time. A frame asks about some 10 GB of - // view memory, 150,000 blocks, nearly all clean: the lookups were most - // of the 60-90 ms a frame of "guards" (run 54). What the loop adds to - // the set meanwhile is the block it stands at or ones before it. - let clean: Vec = g.clean.range(first..last).copied().collect(); - if clean.len() == last - first { - // Nothing written, mapped or new since the range was last taken. - #[cfg(feature = "diagnostics")] - tally(3, 1); - return Some(written); + // The holes that an ordinary commit may have filled, with no word of the + // runtime's. Windows is asked with the lock not held (the range is, no + // other thread asks about it: `ASKING`); what the runtime tells meanwhile + // takes the block out of the set, and it is looked at as any other. + let unsure: Vec = { + let g = guards_timed(); + if g.clean.range(first..last).count() == last - first { + // Nothing written, mapped or new since the range was last taken. + #[cfg(feature = "diagnostics")] + tally(3, 1); + return Some(Vec::new()); + } + g.absent.range(first..last).filter(|block| !g.held.contains(block)).copied().collect() + }; + let mut came: Vec<(usize, bool)> = Vec::new(); + let mut uncommitted_until = first; + for block in unsure { + // One question for the blocks of a region. + if block >= uncommitted_until { + uncommitted_until = uncommitted_end(block); + #[cfg(feature = "diagnostics")] + tally(9, 1); + } + if block >= uncommitted_until { + // The hole may have been given up, and its address be the + // title's heap's, or code's, now: not ours to guard. + came.push((block, is_view(block * BLOCK, (block + 1) * BLOCK))); + } } + let mut g = guards_timed(); #[cfg(feature = "diagnostics")] tally(4, 1); - let mut next_clean = 0; - let mut uncommitted_until = first; + for &(block, view) in &came { + if g.absent.remove(&block) && !view { + g.foreign.insert(block); + } + } + let mut written = Vec::new(); + let mut run: Option = None; + // The range's clean blocks, and those known to be holes, in order: read + // off the sets in one pass, not looked up one block at a time. A frame + // asks about some 10 GB of view memory, 150,000 blocks, nearly all + // clean: the lookups were most of the 60-90 ms a frame of "guards" + // (run 54). What the loop adds to the sets meanwhile is the block it + // stands at or ones before it. + let clean: Vec = g.clean.range(first..last).copied().collect(); + let absent: Vec = g.absent.range(first..last).copied().collect(); + let (mut clean, mut absent) = (clean.into_iter().peekable(), absent.into_iter().peekable()); for block in first..=last { - while next_clean < clean.len() && clean[next_clean] < block { - next_clean += 1; - } - let is_clean = next_clean < clean.len() && clean[next_clean] == block; - let mut open = block < last && !is_clean; - if open && g.absent.contains(&block) { - // Ordinary commits need no runtime mapping notification. Reuse - // this asking's query for the following blocks in the same region. - if block >= uncommitted_until { - uncommitted_until = uncommitted_end(block); - } - open = block >= uncommitted_until; - if open { - g.absent.remove(&block); - } - } - if open { + let is_clean = clean.next_if_eq(&block).is_some(); + let is_absent = absent.next_if_eq(&block).is_some(); + if block < last && !is_clean && !is_absent { written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE); if g.protected.contains(&block) { // Written through the runtime, still read-only. g.clean.insert(block); - } else { + } else if !g.foreign.contains(&block) && !g.left_alone(block) { run.get_or_insert(block); continue; } @@ -862,13 +1075,13 @@ fn is_view(start: usize, end: usize) -> bool { /// block by block if they span views, leaving out any that fail, and /// noting those not committed (unmapped) absent. fn protect(g: &mut Guards, from: usize, to: usize) { - use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; + use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; let set = |from: usize, to: usize| { let mut old = 0; #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); // SAFETY: title view memory; only its protection changes. - let done = unsafe { + let mut done = unsafe { VirtualProtect( (from * BLOCK) as *const _, (to - from) * BLOCK, @@ -876,6 +1089,13 @@ fn protect(g: &mut Guards, from: usize, to: usize) { &mut old, ) != 0 }; + if done && !matches!(old, PAGE_READWRITE | PAGE_READONLY) { + // What is there is not for us to guard (code, or memory the + // title protects itself): as it was. + // SAFETY: as above. + unsafe { VirtualProtect((from * BLOCK) as *const _, (to - from) * BLOCK, old, &mut old) }; + done = false; + } #[cfg(feature = "diagnostics")] { tally(5, (to - from) as u64); @@ -887,15 +1107,30 @@ fn protect(g: &mut Guards, from: usize, to: usize) { g.protected.extend(from..to); g.clean.extend(from..to); }; + // Ahead of the protection (`PROTECTED`). + (from..to).for_each(|block| PROTECTED.set(block)); if set(from, to) { note(g, from, to); return; } + let mut uncommitted_until = from; for block in from..to { - if set(block, block + 1) { + // (Not one question a block of a region that is not there.) + if block >= uncommitted_until && set(block, block + 1) { note(g, block, block + 1); - } else if block < uncommitted_end(block) { + continue; + } + PROTECTED.clear(block); + if block >= uncommitted_until { + uncommitted_until = uncommitted_end(block); + #[cfg(feature = "diagnostics")] + tally(9, 1); + } + if block < uncommitted_until { g.absent.insert(block); + if known_holes() && placeholder(block) { + g.held.insert(block); + } } } } @@ -919,7 +1154,7 @@ fn uncommitted_end(block: usize) -> usize { /// Gives write access back to the guarded blocks of `[start, end)` and /// notes them written; true if any was guarded. fn open(g: &mut Guards, start: usize, end: usize) -> bool { - use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; let blocks: Vec = g .protected .range(start / BLOCK..end.div_ceil(BLOCK)) @@ -934,7 +1169,16 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { PUBLISHED.clear(block); let mut old = 0; // SAFETY: a block we made read-only. - unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; + unsafe { + if VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) != 0 + && !matches!(old, PAGE_READONLY | PAGE_READWRITE) + { + // Not what we left there: the address is other memory's + // (code's, say), which keeps its protection. + VirtualProtect((block * BLOCK) as *const _, BLOCK, old, &mut old); + } + } + PROTECTED.clear(block); } #[cfg(feature = "diagnostics")] if !blocks.is_empty() { @@ -949,7 +1193,8 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { /// reads into its own memory. pub fn writing(at: usize, len: usize) { // The length is the title's (`fread`'s size times count, saturated). - { + let last = at.saturating_add(len).div_ceil(BLOCK); + if !light() || PROTECTED.any(at / BLOCK, last) { let mut g = guards_timed(); #[cfg(feature = "diagnostics")] let held = g.protected.len(); @@ -961,6 +1206,49 @@ pub fn writing(at: usize, len: usize) { crate::descriptor::host::remapped(at, len); } +/// The kernel writes title memory `[at, at + len)` until what this returns +/// is dropped ([`kernel_writing`]). +pub struct KernelWrite(usize, usize); + +/// The runtime is about to have the kernel write title memory +/// `[at, at + len)` (a file read): its guarded blocks are opened, as by +/// [`writing`], and no refresh guards them again before what this returns is +/// dropped, at the end of that call. One that did would make the kernel's +/// write fail (the kernel does not fault into our handler): a read cut +/// short, which the title takes for what the file holds. +pub fn kernel_writing(at: usize, len: usize) -> KernelWrite { + let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); + { + let mut g = guards_timed(); + open(&mut g, at, at.saturating_add(len)); + if len != 0 { + // Nothing known of them stands while they are left alone. + let absent: Vec = g.absent.range(first..last).copied().collect(); + for block in absent { + g.absent.remove(&block); + if g.held.remove(&block) { + PUBLISHED.clear(block); + } + } + g.kernel.push((first, last)); + } + } + crate::descriptor::host::remapped(at, len); + KernelWrite(first, if len == 0 { first } else { last }) +} + +impl Drop for KernelWrite { + fn drop(&mut self) { + if self.0 == self.1 { + return; + } + let mut g = guards(); + if let Some(i) = g.kernel.iter().position(|&r| r == (self.0, self.1)) { + g.kernel.swap_remove(i); + } + } +} + /// Held shared by a read of title memory in place, and alone by the runtime /// while it changes what title memory shows. /// @@ -980,12 +1268,149 @@ static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); /// ([`title_memory_remapping`]). pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>); +impl Drop for Remapping { + fn drop(&mut self) { + // The change is done: what is there now may be guarded. + if CHANGING.replace((false, false)).1 { + guards().changing.clear(); + } + CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } +} + +/// How often the runtime began or ended a change of what title memory +/// shows: odd while one is under way. +static CHANGES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +thread_local! { + /// This thread holds [`Remapping`]; and put blocks in + /// [`Guards::changing`]. + static CHANGING: std::cell::Cell<(bool, bool)> = const { std::cell::Cell::new((false, false)) }; +} + +/// For [`again_after_change`]: to be asked before what may fail. +pub(crate) fn changes() -> u64 { + CHANGES.load(std::sync::atomic::Ordering::SeqCst) +} + +/// `f` failed to read or write title memory, at some time since [`changes`] +/// said `since`. If the runtime changed a mapping in that time, the pages +/// may have been away for that moment only ([`MAPPING`]): again, when the +/// change is done. Whether `f` did it. +pub(crate) fn again_after_change(since: u64, mut f: impl FnMut() -> bool) -> bool { + let mut since = since; + for _ in 0..4 { + let now = change_done(); + if now == since { + return false; + } + since = now; + if f() { + return true; + } + } + false +} + +/// [`changes`], when no change is under way (or one has been for a second). +fn change_done() -> u64 { + let mut tries = 0; + let mut started = None; + loop { + let now = changes(); + if now.is_multiple_of(2) { + return now; + } + tries += 1; + if tries < 100 { + std::hint::spin_loop(); + continue; + } + if started.get_or_insert_with(std::time::Instant::now).elapsed().as_secs() >= 1 { + return now; + } + // SAFETY: gives the processor to another thread. + unsafe { windows_sys::Win32::System::Threading::Sleep(u32::from(tries > 200)) }; + } +} + +/// Faults of title threads that met a change of mapping and went on after +/// it ([`came_back`]). +static MET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A title thread's access to `at` (`write`: a write) faulted. Whether it +/// can be made now: if a change of mapping is under way, after it. +/// +/// The console changes one page's mapping and no other's. Here the rest of +/// a view is unmapped and mapped again ([`MAPPING`]), and a title thread that +/// uses a page of it just then, which the title never gave up, faulted +/// ("reserved, never committed", or read-only for the moment between our +/// forgetting a guarded block and its unmapping). It waits here instead. +/// Memory that is not there with no change under way is not waited for. +fn came_back(at: usize, write: bool) -> bool { + let there = || { + if !write { + return readable_view(at); + } + // (A refresh may have guarded the page that came back.) + open(&mut guards(), at, at + 1) || writable(at) + }; + let before = changes(); + if there() || again_after_change(before, there) { + MET.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + false +} + +/// Whether `at` is in a committed page of a view that can be read. +fn readable_view(at: usize) -> bool { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_READONLY, PAGE_READWRITE, VirtualQuery, + }; + // 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(at as *const _, &mut info, size_of_val(&info)) }; + n != 0 + && info.State == MEM_COMMIT + && info.Type == MEM_MAPPED + && matches!(info.Protect, PAGE_READONLY | PAGE_READWRITE) +} + +/// Title memory that could not be written with what was to go there (what a +/// shader wrote, a title's copy): counted, and said at the 1st, 2nd, 4th, 8th +/// and so on. A page the title unmapped loses nothing by it; a page that is +/// there does. +pub(crate) fn lost(what: &'static str, at: usize, len: usize) { + static LOST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = LOST.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() { + let there = writable(at); + tracing::warn!(n, what, at = format_args!("{at:#x}"), len, there, "title memory not written"); + } +} + + /// The runtime is about to map, unmap or move physical pages of title /// memory: until what it returns is dropped, no read of title memory in /// place is under way and none begins ([`title_memory_reading`]). Taken /// around the whole change, the unmapping and the mapping again. pub fn title_memory_remapping() -> Remapping { - Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner())) + // For the title's own threads ([`came_back`]). + install(); + let met = MET.load(std::sync::atomic::Ordering::Relaxed); + if met != 0 { + static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if met >= 2 * SAID.load(std::sync::atomic::Ordering::Relaxed) { + SAID.store(met, std::sync::atomic::Ordering::Relaxed); + tracing::info!(met, "accesses of title threads that waited for a change of mapping"); + } + } + let changing = MAPPING.write().unwrap_or_else(|e| e.into_inner()); + CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + CHANGING.set((true, false)); + Remapping(changing) } /// What a read of title memory in place holds ([`title_memory_reading`]). @@ -1025,9 +1450,20 @@ pub fn title_memory_remapped(at: usize, len: usize) { } /// The runtime is about to unmap title memory `[at, at + len)`: it is -/// nothing of ours any more. Its protection goes with it. +/// nothing of ours any more. Its protection goes with it. Until the change +/// is done ([`Remapping`]) no refresh guards what is there: one that did +/// before the unmapping would leave the address guarded, clean and known by +/// its bits ([`PUBLISHED`]) with no view behind it. pub fn title_memory_unmapping(at: usize, len: usize) { let mut g = title_memory_changed(at, len); + if CHANGING.get().0 && len != 0 { + CHANGING.set((true, true)); + let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); + match g.changing.last_mut() { + Some(before) if before.1 == first => before.1 = last, + _ => g.changing.push((first, last)), + } + } let blocks: Vec = g .protected .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) @@ -1037,9 +1473,65 @@ pub fn title_memory_unmapping(at: usize, len: usize) { g.protected.remove(&block); g.clean.remove(&block); PUBLISHED.clear(block); + PROTECTED.clear(block); } } +/// The title is about to free or decommit memory of its own, +/// `[at, at + len)`, or with no length the whole allocation at `at`: what +/// was noted of its blocks (guarded, clean, absent) would be taken for true +/// of the next memory at the address. +pub fn title_memory_freed(at: usize, len: usize) { + let mut g = guards(); + let first = at / BLOCK; + let noted = [&g.protected, &g.absent, &g.foreign].map(|set| set.range(first..).next()); + let Some(noted) = noted.into_iter().flatten().min().copied() else { + return; + }; + let end = if len != 0 { + at.saturating_add(len).div_ceil(BLOCK) + } else { + allocation_end(at, noted * BLOCK).div_ceil(BLOCK) + }; + if noted >= end { + return; + } + let absent: Vec = g.absent.range(first..end).copied().collect(); + for block in absent { + g.absent.remove(&block); + if g.held.remove(&block) { + PUBLISHED.clear(block); + } + } + let foreign: Vec = g.foreign.range(first..end).copied().collect(); + for block in foreign { + g.foreign.remove(&block); + } + // (Memory that is still a view is not freed by that call, which fails: + // it must not stay read-only.) + open(&mut g, at, end * BLOCK); +} + +/// The end of the allocation at `at`, if `inside` lies in it; else `at`. +fn allocation_end(at: usize, inside: usize) -> usize { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + let ask = |address: 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(address as *const _, &mut info, size_of_val(&info)) }; + (n != 0 && info.AllocationBase as usize == at) + .then(|| (info.BaseAddress as usize).saturating_add(info.RegionSize)) + }; + let mut end = at; + let mut next = ask(inside.max(at)); + while let Some(to) = next { + end = to; + next = ask(to); + } + end +} + /// Tells what keeps track of what title memory shows; the guards, with no /// block of the range known unmapped. fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> { @@ -1052,9 +1544,16 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, crate::inplace::title_memory_freeing(at, len); let mut g = guards(); let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); - let absent: Vec = g.absent.range(range).copied().collect(); + let absent: Vec = g.absent.range(range.clone()).copied().collect(); for block in absent { g.absent.remove(&block); + if g.held.remove(&block) { + PUBLISHED.clear(block); + } + } + let foreign: Vec = g.foreign.range(range).copied().collect(); + for block in foreign { + g.foreign.remove(&block); } g } @@ -1070,6 +1569,7 @@ pub(crate) fn install() { unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 { // SAFETY: the system passes the exception being dispatched. let r = unsafe { &*(*info).ExceptionRecord }; + const READ: usize = 0; const WRITE: usize = 1; // A fault of our own copies (`crate::safecopy`): whatever it is, if // it is not a block we guard, the copy fails and goes on from there. @@ -1085,6 +1585,13 @@ pub(crate) fn install() { { return match ours { Some(exit) => fail(exit), + None if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS + && r.NumberParameters >= 2 + && r.ExceptionInformation[0] == READ + && came_back(r.ExceptionInformation[1], false) => + { + EXCEPTION_CONTINUE_EXECUTION + } None => EXCEPTION_CONTINUE_SEARCH, }; } @@ -1101,8 +1608,11 @@ pub(crate) fn install() { if writable(at) { return EXCEPTION_CONTINUE_EXECUTION; } + // (The runtime wants the guards to end a change.) + drop(g); match ours { Some(exit) => fail(exit), + None if came_back(at, true) => EXCEPTION_CONTINUE_EXECUTION, None => EXCEPTION_CONTINUE_SEARCH, } } @@ -1229,6 +1739,299 @@ mod tests { }; } + /// A placeholder of `blocks` blocks, each its own. + fn placeholder(blocks: usize) -> usize { + use windows_sys::Win32::System::Memory::{ + MEM_PRESERVE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder, split. + unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + blocks * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + for block in 0..blocks - 1 { + assert_ne!( + VirtualFree((p + block * BLOCK) as *mut _, BLOCK, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), + 0 + ); + } + p + } + } + + /// Private memory of `protect` in place of the placeholder of one block. + fn private_at(at: usize, protect: u32) { + use windows_sys::Win32::System::Memory::{MEM_REPLACE_PLACEHOLDER, VirtualAlloc2}; + // SAFETY: our placeholder. + let got = unsafe { + VirtualAlloc2( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + at as *const _, + BLOCK, + MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, + protect, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(got as usize, at); + } + + fn protection(at: usize) -> u32 { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + // SAFETY: plain data the query fills in. + unsafe { + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(at as *const _, &mut info, size_of_val(&info)); + info.Protect + } + } + + /// A refresh between the opening of a kernel read's destination and the + /// read itself leaves it open: the read lands, and is seen. + #[test] + fn a_refresh_leaves_open_what_the_kernel_is_writing() { + use std::io::{Read, Seek, Write}; + use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile}; + // SAFETY: a pagefile section of two blocks, mapped read-write. + let view = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK) + }; + let at = view.Value as usize; + assert_ne!(at, 0); + let pages = |block: usize| at / PAGE + block..at / PAGE + block + 1; + assert!(writes(at, at + 2 * BLOCK, true).is_some()); + assert!(published(at, at + 2 * BLOCK) || !light()); + let mut file = tempfile::tempfile().unwrap(); + file.write_all(b"from the disk").unwrap(); + file.rewind().unwrap(); + let writing = kernel_writing(at + 100, 13); + // The refresh: the block being written is new to it every time, and + // stays open; the other is as it was. + for _ in 0..2 { + assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect())); + let (now, found) = writes(at, at + BLOCK, true).expect("a view"); + assert!(found.contains(&(at / PAGE, now))); + assert!(writable(at) && !writable(at + BLOCK)); + assert!(!published(at, at + BLOCK)); + } + // SAFETY: 13 bytes of our view, nothing else refers to them. + let into = unsafe { std::slice::from_raw_parts_mut((at + 100) as *mut u8, 13) }; + assert_eq!(file.read(into).expect("the kernel's write lands"), 13); + assert_eq!(into, b"from the disk"); + drop(writing); + // Seen by the next refresh, and guarded again. + assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect())); + assert!(!writable(at)); + assert_eq!(guard(at, at + 2 * BLOCK), Some(Vec::new())); + title_memory_unmapping(at, 2 * BLOCK); + // SAFETY: our view. + unsafe { UnmapViewOfFile(view) }; + } + + /// A hole the kernel is to write is no known hole meanwhile, nor is one + /// the runtime has begun to change; after that it is again. + #[test] + fn what_is_left_alone_is_no_known_hole() { + let p = placeholder(3); + let known = |block: usize| published(p + block * BLOCK, p + (block + 1) * BLOCK); + let ask = || writes(p, p + 3 * BLOCK, true).expect("as a view"); + ask(); + let holes = known_holes(); + assert!((0..3).all(known) == holes); + let writing = kernel_writing(p + BLOCK + 5, 100); + for _ in 0..2 { + assert!(known(0) == holes && !known(1) && known(2) == holes); + let (now, written) = ask(); + assert!(written.contains(&(p / PAGE + 1, now))); + assert!(written.iter().all(|w| w.0 == p / PAGE + 1 || w.1 < now)); + } + assert!(!guards().held.contains(&(p / BLOCK + 1))); + drop(writing); + ask(); + assert!((0..3).all(known) == holes); + { + let _changing = title_memory_remapping(); + title_memory_unmapping(p, BLOCK); + ask(); + assert!(!known(0) && !guards().held.contains(&(p / BLOCK))); + } + ask(); + assert!((0..3).all(known) == holes); + title_memory_freed(p, BLOCK); + assert!(!known(0) && !guards().held.contains(&(p / BLOCK))); + title_memory_unmapping(p, 3 * BLOCK); + // SAFETY: our placeholders. + unsafe { + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + } + } + + /// A refresh during a change of mapping guards nothing the runtime has + /// begun to unmap: no note of it stays behind. + #[test] + fn nothing_is_guarded_between_our_forgetting_it_and_its_unmapping() { + use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile}; + // SAFETY: a pagefile section of a block, mapped read-write. + let view = unsafe { + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null()); + assert!(!section.is_null()); + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, BLOCK) + }; + let at = view.Value as usize; + assert_ne!(at, 0); + assert!(writes(at, at + BLOCK, true).is_some()); + let changing = title_memory_remapping(); + title_memory_unmapping(at, BLOCK); + assert!(writes(at, at + BLOCK, true).is_some()); + { + let g = guards(); + assert!(!g.protected.contains(&(at / BLOCK)) && !g.clean.contains(&(at / BLOCK))); + } + assert!(!published(at, at + BLOCK)); + // SAFETY: our view. + unsafe { UnmapViewOfFile(view) }; + drop(changing); + assert!(!guards().left_alone(at / BLOCK)); + } + + /// Memory at an address where blocks were guarded or absent is not + /// taken for them: code stays code, private memory is not guarded. + #[test] + fn other_memory_at_a_guarded_address_keeps_its_protection() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, MapViewOfFile3, PAGE_EXECUTE_READ, + PAGE_EXECUTE_READWRITE, UnmapViewOfFile2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let p = placeholder(3); + // SAFETY: a section's block in place of the first placeholder. + let view = unsafe { + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null()); + assert!(!section.is_null()); + MapViewOfFile3( + section, + GetCurrentProcess(), + p as *const _, + 0, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p); + // One block guarded, two absent. + assert_eq!(guard(p, p + 3 * BLOCK).map(|w| w.len()), Some(3)); + // Not told of what comes: the view goes, code is there; and private + // memory in the holes. + // SAFETY: our view. + assert_ne!(unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }, 0); + private_at(p, PAGE_EXECUTE_READ); + private_at(p + BLOCK, PAGE_READWRITE); + private_at(p + 2 * BLOCK, PAGE_EXECUTE_READWRITE); + // (The runtime's allocations it tells of, or the holes stay known.) + title_memory_allocated(p + BLOCK, 2 * BLOCK); + let as_made = || { + assert_eq!(protection(p), PAGE_EXECUTE_READ); + assert_eq!(protection(p + BLOCK), PAGE_READWRITE); + assert_eq!(protection(p + 2 * BLOCK), PAGE_EXECUTE_READWRITE); + }; + let holes = [p / PAGE + 1, p / PAGE + 2]; + for _ in 0..2 { + let written = guard(p, p + 3 * BLOCK).expect("as a view"); + assert!(holes.iter().all(|page| written.contains(page)), "copied every time"); + as_made(); + let g = guards(); + assert!(holes.iter().all(|block| !g.held.contains(block) && !g.absent.contains(block))); + } + writing(p, BLOCK); + as_made(); + title_memory_unmapping(p, 3 * BLOCK); + // SAFETY: our allocations. + unsafe { + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + } + } + + /// Memory the title frees leaves no note of its blocks, whether it names + /// its length or the allocation. + #[test] + fn freed_memory_leaves_no_notes() { + let p = placeholder(3); + let noted = |block: usize| { + let g = guards(); + let block = p / BLOCK + block; + g.protected.contains(&block) || g.clean.contains(&block) || g.absent.contains(&block) + }; + assert!(guard(p, p + 3 * BLOCK).is_some()); + assert!(noted(0) && noted(1) && noted(2)); + // The middle allocation. + title_memory_freed(p + BLOCK, 0); + assert!(noted(0) && !noted(1) && noted(2)); + title_memory_freed(p, BLOCK); + assert!(!noted(0) && noted(2)); + // Nothing noted there: nothing to do, and nothing beside it. + title_memory_freed(p + BLOCK, 0); + assert!(noted(2)); + title_memory_freed(p + 2 * BLOCK, 0); + assert!(!noted(2)); + // SAFETY: our placeholders. + unsafe { + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + } + } + + /// A write between another thread's asking about a range and the second + /// part of a submission's one asking is later than what that thread + /// copied. + #[test] + fn the_rest_of_the_one_asking_has_a_number_of_its_own() { + // SAFETY: a fresh write-watched allocation, freed at the end. + let p = unsafe { + VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + } as usize; + assert_ne!(p, 0); + // One range: `ask_ahead` leaves it. + let ranges = [(p, p + 4 * PAGE)]; + ask_ahead(&ranges); + let (copied, _) = writes(p, p + 4 * PAGE, false).expect("watched"); + // SAFETY: committed pages of ours. + unsafe { ((p + PAGE) as *mut u8).write_volatile(1) }; + ask_rest(&ranges); + let last = journal().written.get(&(p / PAGE + 1)).copied(); + ask_once_end(); + assert!(last.is_some_and(|last| last > copied), "{last:?} is not after {copied}"); + // SAFETY: our allocation. + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + } + /// The runtime maps a view and then tells us; a copy's refresh on another /// thread can guard it in between. Told, it is the title's to write: a /// block left read-only and forgotten would be an access violation in @@ -1663,7 +2466,8 @@ mod many_askers_tests { // or past the guard. let word = at + page * PAGE + t * 8; // SAFETY (both): as above. - let reading = (next(3) == 0).then(super::title_memory_reading_now).flatten(); + // (Waited for: other tests hold changes of mapping.) + let reading = (next(3) == 0).then(super::title_memory_reading); let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8)); if let Some(to) = beside { unsafe { (to as *mut u64).write_volatile(2) }; @@ -1704,6 +2508,183 @@ mod many_askers_tests { // of these writes.) } + /// A range of a placeholder with views in it is known whole, its holes + /// among it, until something is mapped into one, unmapped from it or + /// allocated there. A hole that is no placeholder's is asked about. + #[test] + fn holes_are_known_until_the_runtime_tells() { + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const BLOCKS: usize = 8; + // SAFETY (all): a placeholder and a section of our own, which stay. + let (at, section) = unsafe { + let at = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + BLOCKS * PAGE, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null()); + (at, section) + }; + let map = |block: usize| unsafe { + let to = at + block * PAGE; + VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER); + let view = MapViewOfFile3( + section, + GetCurrentProcess(), + to as *const _, + (block * PAGE) as u64, + PAGE, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ); + assert_eq!(view.Value as usize, to); + super::title_memory_remapped(to, PAGE); + }; + map(1); + map(5); + assert!(super::placeholder(at / PAGE) && super::placeholder(at / PAGE + 7) && !super::placeholder(at / PAGE + 5)); + let end = at + BLOCKS * PAGE; + let ask = |since: u64| -> (u64, Vec) { + let (now, written) = writes(at, end, true).expect("a view"); + (now, written.into_iter().filter(|w| w.1 > since).map(|w| w.0 - at / PAGE).collect()) + }; + let (first, all) = ask(0); + assert_eq!(all, (0..BLOCKS).collect::>()); + assert!(super::published(at, end), "with its holes"); + // Written; mapped into; unmapped. + unsafe { ((at + 5 * PAGE) as *mut u8).write_volatile(1) }; + assert!(!super::published(at, end)); + let (second, all) = ask(first); + assert_eq!(all, [5]); + map(2); + assert!(!super::published(at, end)); + let (third, all) = ask(second); + assert_eq!(all, [2]); + unsafe { ((at + 2 * PAGE) as *mut u8).write_volatile(1) }; + let (fourth, all) = ask(third); + assert_eq!(all, [2]); + super::title_memory_unmapping(at + 5 * PAGE, PAGE); + unsafe { + let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: (at + 5 * PAGE) as *mut _ }; + UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER); + } + let (fifth, all) = ask(fourth); + assert_eq!(all, [5]); + assert!(super::published(at, end)); + // Told of memory there, though there is none: asked about again. + super::title_memory_allocated(at, PAGE); + assert!(!super::published(at, end)); + let (_, all) = ask(fifth); + assert_eq!(all, []); + // A reservation of the ordinary kind is no placeholder. + let plain = unsafe { VirtualAlloc(std::ptr::null(), PAGE, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert!(!super::placeholder(plain / PAGE)); + super::look_at_holes(); + assert!(!super::published(at, end), "block 0 stays asked about"); + assert!(super::published(at + PAGE, end), "the others are as they were"); + super::title_memory_unmapping(at, BLOCKS * PAGE); + } + + /// Pages mapped into a placeholder, written and unmapped again, each by a + /// thread of its own as the runtime does it, while others ask about all + /// of it: what was written, and that a page came or went, is told to + /// whoever asks after it, and blocks are known by their bits meanwhile. + #[test] + fn no_mapping_is_lost_between_askers() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const BLOCKS: usize = 12; + // SAFETY (all): a placeholder and a section of our own, which stay. + let (at, section) = unsafe { + let at = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + BLOCKS * PAGE, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + for block in 0..BLOCKS - 1 { + VirtualFree((at + block * PAGE) as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER); + } + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null()); + (at, section as usize) + }; + let end = at + BLOCKS * PAGE; + let (stop, by_bits) = (AtomicBool::new(false), AtomicUsize::new(0)); + let number = |written: &[(usize, u64)], block: usize| written.iter().find(|w| w.0 == at / PAGE + block).map_or(0, |w| w.1); + std::thread::scope(|s| { + let mappers: Vec<_> = (0..4usize) + .map(|t| { + let number = &number; + s.spawn(move || { + for round in 0..120 { + let block = t * 3 + round % 3; + let to = at + block * PAGE; + let (before, _) = writes(at, end, true).expect("a view"); + unsafe { + let view = MapViewOfFile3( + section as _, + GetCurrentProcess(), + to as *const _, + (block * PAGE) as u64, + PAGE, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ); + assert_eq!(view.Value as usize, to); + super::title_memory_remapped(to, PAGE); + (to as *mut u8).write_volatile(round as u8); + } + let (mapped, written) = writes(at, end, true).expect("a view"); + assert!(number(&written, block) > before, "mapped and written: not told"); + unsafe { ((to + 9) as *mut u8).write_volatile(round as u8) }; + let (again, written) = writes(to, to + PAGE, true).expect("a view"); + assert!(number(&written, block) > mapped, "written again: not told"); + super::title_memory_unmapping(to, PAGE); + unsafe { + let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: to as *mut _ }; + assert_ne!(UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER), 0); + } + let _ = again; + } + }) + }) + .collect(); + for t in 0..3usize { + let (stop, by_bits) = (&stop, &by_bits); + s.spawn(move || { + let mut k = t; + while !stop.load(Ordering::Relaxed) { + k = (k * 5 + 3) % 64; + let (from, to) = (at + k % 6 * PAGE, end - k / 8 % 5 * PAGE); + by_bits.fetch_add(usize::from(super::published(from, to)), Ordering::Relaxed); + assert!(writes(from, to, true).is_some()); + } + }); + } + let failed = mappers.into_iter().map(|m| m.join()).filter(Result::is_err).count(); + stop.store(true, Ordering::Relaxed); + assert_eq!(failed, 0); + }); + assert!(by_bits.into_inner() > 0, "the bits answered none"); + // All unmapped: known whole, and nothing but holes. + writes(at, end, true).expect("a view"); + assert!(super::published(at, end)); + super::title_memory_unmapping(at, BLOCKS * PAGE); + } + /// A block's bit goes with everything that makes it the title's to write, /// or forgets it. #[test] diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index a2fa943..3522b74 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -24,6 +24,7 @@ windows-sys = { workspace = true, features = [ "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", + "Win32_System_IO", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Power", diff --git a/crates/victory-hle/src/image_watch.rs b/crates/victory-hle/src/image_watch.rs new file mode 100644 index 0000000..e5d6856 --- /dev/null +++ b/crates/victory-hle/src/image_watch.rs @@ -0,0 +1,100 @@ +//! Diagnostics (`VICTORY_IMAGE_WATCH`; off by default): words of the title's +//! image, logged once a second, for what a launch's own counters say (how +//! much of its streaming memory it uses, whether an allocation failed) where +//! two launches end up with different pictures. +//! +//! `VICTORY_IMAGE_WATCH=used=98d26d8:8,failed=98d26d0:1`: a name, the offset +//! in the image (hexadecimal) and the bytes (1, 2, 4 or 8). + +use std::time::Duration; + +struct Word { + name: String, + offset: usize, + bytes: usize, +} + +/// The words `text` names; what cannot be read of it is left out. +fn words(text: &str) -> Vec { + text.split(',') + .filter_map(|part| { + let (name, rest) = part.trim().split_once('=')?; + let (offset, bytes) = rest.split_once(':').unwrap_or((rest, "8")); + let offset = usize::from_str_radix(offset.trim().trim_start_matches("0x"), 16).ok()?; + let bytes = bytes.trim().parse().ok().filter(|n| matches!(n, 1 | 2 | 4 | 8))?; + Some(Word { name: name.trim().to_owned(), offset, bytes }) + }) + .collect() +} + +/// `word` of the image at `base`; `None` if it cannot be read. +fn read(base: usize, word: &Word) -> Option { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut value = [0u8; 8]; + // SAFETY: the kernel copies at most eight bytes into `value`, and fails + // where there is nothing to read. + let ok = unsafe { + ReadProcessMemory( + GetCurrentProcess(), + (base + word.offset) as *const _, + value.as_mut_ptr().cast(), + word.bytes, + std::ptr::null_mut(), + ) + }; + (ok != 0).then(|| u64::from_le_bytes(value)) +} + +/// Starts watching the image at `base`, if asked for. +pub(crate) fn start(base: usize) { + let Ok(text) = std::env::var("VICTORY_IMAGE_WATCH") else { + return; + }; + let words = words(&text); + if base == 0 || words.is_empty() { + return; + } + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("victory-image-watch".into()).spawn(move || { + let mut last = Vec::new(); + loop { + std::thread::sleep(Duration::from_secs(1)); + let now: Vec> = words.iter().map(|word| read(base, word)).collect(); + if now == last { + continue; + } + let values: Vec = words + .iter() + .zip(&now) + .map(|(word, value)| match value { + Some(value) => format!("{}={value:#x}", word.name), + None => format!("{}=?", word.name), + }) + .collect(); + tracing::info!("the title's image: {}", values.join(" ")); + last = now; + } + }); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn words_are_read_where_they_are_named() { + let all = words("used=98d26d8:8, failed = 0x10:1,odd=3:3,none"); + assert_eq!(all.len(), 2); + assert_eq!((all[0].name.as_str(), all[0].offset, all[0].bytes), ("used", 0x98d_26d8, 8)); + assert_eq!((all[1].name.as_str(), all[1].offset, all[1].bytes), ("failed", 0x10, 1)); + let memory = [0x11u8, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]; + let word = |offset, bytes| Word { name: String::new(), offset, bytes }; + let base = memory.as_ptr() as usize; + assert_eq!(read(base, &word(0, 4)), Some(0x4433_2211)); + assert_eq!(read(base, &word(2, 1)), Some(0x33)); + assert_eq!(read(8, &word(0, 8)), None); + } +} diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index a61e988..447de82 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -12,6 +12,7 @@ //! then the host if [`HostPolicy`] allows that DLL, then `Missing`. mod host; +mod image_watch; pub mod modules; mod registry; pub mod runtime; diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 0c5c430..b17b860 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -149,7 +149,8 @@ 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 files = Files::new(file, Io::chosen()); + let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { files }); WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept)); put(out, file) } @@ -263,7 +264,184 @@ static FACTORY_VTABLE: Methods<16> = Methods([ // Files. struct File { - file: std::fs::File, + files: Files, +} + +/// How files are read (`VICTORY_DSTORAGE_IO`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Io { + /// `one`: all workers through the one handle, as before. The host does + /// the reads of a handle one after the other. + One, + /// `handles`: a handle for each worker. + Handles, + /// `overlapped`: one handle, whose reads the host does side by side. + Overlapped, + /// `direct`: a handle for each worker, past the host's file cache. + Direct, +} + +impl Io { + fn chosen() -> Io { + static CHOSEN: OnceLock = OnceLock::new(); + *CHOSEN.get_or_init(|| { + let io = match std::env::var("VICTORY_DSTORAGE_IO").as_deref().map(str::trim) { + Ok("one") => Io::One, + Ok("handles") => Io::Handles, + Ok("overlapped") => Io::Overlapped, + Ok("direct") => Io::Direct, + _ => Io::DEFAULT, + }; + tracing::info!(?io, "dstorage: how files are read (VICTORY_DSTORAGE_IO)"); + io + }) + } + + const DEFAULT: Io = Io::Handles; +} + +/// A file as the workers read it: the handle the title opened, and those +/// made from it when a worker first reads. +struct Files { + first: std::fs::File, + others: Box<[OnceLock>]>, + io: Io, +} + +impl Files { + fn new(first: std::fs::File, io: Io) -> Files { + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()); + let others = match io { + Io::One => 0, + Io::Overlapped => 1, + Io::Handles | Io::Direct => workers, + }; + Files { first, others: (0..others).map(|_| OnceLock::new()).collect(), io } + } + + #[cfg(test)] + fn open_for_test(path: &str, io: Io) -> Files { + Files::new(std::fs::File::open(path).unwrap(), io) + } + + /// Reads at `offset`; as [`FileExt::seek_read`]. + fn read_at(&self, out: &mut [u8], offset: u64) -> std::io::Result { + use windows_sys::Win32::Storage::FileSystem::{FILE_FLAG_NO_BUFFERING, FILE_FLAG_OVERLAPPED}; + let flags = match self.io { + Io::One | Io::Handles => 0, + Io::Overlapped => FILE_FLAG_OVERLAPPED, + Io::Direct => FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, + }; + let other = match self.others.len() { + 0 => None, + n => self.others[this_thread() % n].get_or_init(|| reopen(&self.first, flags)).as_ref(), + }; + match (other, self.io) { + (Some(file), Io::Overlapped) => read_overlapped(file, out, offset), + (Some(file), Io::Direct) => read_direct(file, out, offset), + (file, _) => file.unwrap_or(&self.first).seek_read(out, offset), + } + } +} + +/// A number for this thread: 0 for the first that asks, and so on. +fn this_thread() -> usize { + static NEXT: AtomicU32 = AtomicU32::new(0); + thread_local! { + static NUMBER: usize = NEXT.fetch_add(1, Ordering::Relaxed) as usize; + } + NUMBER.with(|n| *n) +} + +/// Another handle to `file`, for reading; `None` if the host gives none +/// (then the first one is used). +fn reopen(file: &std::fs::File, flags: u32) -> Option { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::{GENERIC_READ, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, ReOpenFile}; + // SAFETY: a file we hold open. + let handle = unsafe { ReOpenFile(file.as_raw_handle(), GENERIC_READ, FILE_SHARE_READ, flags) }; + if handle == INVALID_HANDLE_VALUE { + tracing::warn!(error = %std::io::Error::last_os_error(), flags, "dstorage: a file could not be opened again"); + return None; + } + // SAFETY: a handle just opened, ours alone. + Some(unsafe { std::fs::File::from_raw_handle(handle) }) +} + +/// A read through a handle opened for overlapped reads, waited for. +fn read_overlapped(file: &std::fs::File, out: &mut [u8], offset: u64) -> std::io::Result { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::{CloseHandle, ERROR_HANDLE_EOF, ERROR_IO_PENDING, HANDLE}; + use windows_sys::Win32::Storage::FileSystem::ReadFile; + use windows_sys::Win32::System::IO::{GetOverlappedResult, OVERLAPPED}; + use windows_sys::Win32::System::Threading::CreateEventW; + /// Set when this thread's read is done. + struct Event(HANDLE); + impl Drop for Event { + fn drop(&mut self) { + // SAFETY: our own event. + unsafe { CloseHandle(self.0) }; + } + } + thread_local! { + static DONE: Event = + // SAFETY: a plain manual-reset event. + Event(unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) }); + } + DONE.with(|done| { + if done.0.is_null() { + return Err(std::io::Error::last_os_error()); + } + let mut overlapped = OVERLAPPED { hEvent: done.0, ..Default::default() }; + overlapped.Anonymous.Anonymous.Offset = offset as u32; + overlapped.Anonymous.Anonymous.OffsetHigh = (offset >> 32) as u32; + let len = out.len().min(1 << 30) as u32; + let mut n = 0; + // SAFETY: `out` and `overlapped` stay until the read is done, which + // is waited for. + let mut read = unsafe { + ReadFile(file.as_raw_handle(), out.as_mut_ptr(), len, std::ptr::null_mut(), &mut overlapped) + } != 0; + let mut error = std::io::Error::last_os_error(); + if read || error.raw_os_error() == Some(ERROR_IO_PENDING as i32) { + // SAFETY: as above. + read = unsafe { GetOverlappedResult(file.as_raw_handle(), &overlapped, &mut n, 1) } != 0; + error = std::io::Error::last_os_error(); + } + match error.raw_os_error() { + _ if read => Ok(n as usize), + Some(code) if code == ERROR_HANDLE_EOF as i32 => Ok(0), + _ => Err(error), + } + }) +} + +/// A read past the file cache: of the whole sectors around the bytes, into +/// a buffer of this thread's, unless `out` takes them as they are. +fn read_direct(file: &std::fs::File, out: &mut [u8], offset: u64) -> std::io::Result { + /// Every disk's sectors are at most this; offsets, sizes and addresses + /// are multiples of it. + const SECTOR: usize = 4096; + /// Read at a time. + const MOST: usize = 1 << 20; + let sector = SECTOR as u64; + if offset % sector == 0 && out.len() % SECTOR == 0 && out.as_ptr() as usize % SECTOR == 0 { + return read_overlapped(file, out, offset); + } + thread_local! { + static BUFFER: std::cell::RefCell> = std::cell::RefCell::new(vec![0; MOST + SECTOR]); + } + BUFFER.with_borrow_mut(|buffer| { + let skip = buffer.as_ptr().align_offset(SECTOR); + let before = (offset % sector) as usize; + let len = (before + out.len()).next_multiple_of(SECTOR).min(MOST); + let aligned = &mut buffer[skip..skip + len]; + let read = read_overlapped(file, aligned, offset - before as u64)?; + let n = read.saturating_sub(before).min(out.len()); + out[..n].copy_from_slice(&aligned[before..before + n]); + Ok(n) + }) } static FILE_VTABLE: Methods<8> = Methods([ @@ -1248,16 +1426,16 @@ fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { return Ok(()); } // SAFETY: a file object we created; the title keeps it open. - let file = &unsafe { &*request.source.cast::>() } + let files = &unsafe { &*request.source.cast::>() } .state - .file; + .files; let started = std::time::Instant::now(); let (mut done, mut tries) = (0, 0); let result = loop { if done == out.len() { break Ok(()); } - let error = match file.seek_read(&mut out[done..], request.offset + done as u64) { + let error = match files.read_at(&mut out[done..], request.offset + done as u64) { Ok(0) => break Err(END_OF_FILE), Ok(n) => { done += n; @@ -1300,12 +1478,14 @@ fn into_destination( ) -> Result<(), HRESULT> { if request.options & PAGE_DESTINATION == 0 { // Raw reads land through the kernel, which does not fault into the - // GPU side's guard on title buffers; open them first. - victory_gpu::kernel_will_write(request.destination as usize, len); + // GPU side's guard on title buffers; open them first, and until the + // bytes are there. + let writing = victory_gpu::kernel_writing(request.destination as usize, len); // SAFETY: the title's destination holds `destination_size` bytes, at // least `len`, and nothing else writes it until completion. let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::(), len) }; let filled = fill(out).map(drop); + drop(writing); // Again now that the bytes are there: a texture looked at in between // was uploaded without them (`xmem::pages_written`). if super::xmem::stream_notice() { @@ -1820,6 +2000,86 @@ mod tests { assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, plain.len()) }, plain); } + /// What ways of reading a file give, at `VICTORY_BENCH_FILE` (a file of + /// the title's, only read): 24 threads, requests of 48 KiB at random, + /// first from places nobody read lately, then the same once more. + /// `VICTORY_BENCH_FILE=... cargo test --release -p victory-hle --lib + /// read_bench -- --ignored --nocapture` + #[test] + #[ignore = "a benchmark"] + fn read_bench() { + const THREADS: usize = 24; + const SIZE: usize = 48 << 10; + const READS: usize = 12_000; + let path = std::env::var("VICTORY_BENCH_FILE").expect("VICTORY_BENCH_FILE"); + let len = std::fs::metadata(&path).unwrap().len(); + let mut seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u64 | 1; + let mut random = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for round in 0..2 { + for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct] { + let file = Files::open_for_test(&path, mode); + let at: Vec = (0..READS).map(|_| random() % (len - SIZE as u64) & !15).collect(); + for pass in ["cold", "again"] { + let next = std::sync::atomic::AtomicUsize::new(0); + let busy = AtomicU64::new(0); + let start = Instant::now(); + std::thread::scope(|s| { + for _ in 0..THREADS { + s.spawn(|| { + let mut out = vec![0u8; SIZE]; + while let Some(&at) = at.get(next.fetch_add(1, Ordering::Relaxed)) { + let began = Instant::now(); + let mut done = 0; + while done < SIZE { + done += file.read_at(&mut out[done..], at + done as u64).unwrap(); + } + busy.fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + } + }); + } + }); + let took = start.elapsed().as_secs_f64(); + println!( + "{round} {mode:?} {pass}: {:.0} MB/s, {:.2} ms a read", + (READS * SIZE) as f64 / took / 1e6, + busy.load(Ordering::Relaxed) as f64 / READS as f64 / 1e3 + ); + } + } + } + } + + /// Every way of reading a file gives its bytes, also past its end. + #[test] + fn every_way_of_reading_gives_the_same_bytes() { + let plain = pattern(300_001); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + std::fs::write(&path, &plain).unwrap(); + for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct] { + let file = Files::open_for_test(path.to_str().unwrap(), mode); + for (at, len) in [(0, 4096), (1, 100), (4095, 2), (8192, 200_000), (12_345, 250_000), (299_990, 11), (300_000, 1)] { + let mut out = vec![0u8; len]; + let mut done = 0; + while done < len { + let n = file.read_at(&mut out[done..], (at + done) as u64).unwrap(); + assert_ne!(n, 0, "{mode:?} {at} {len}"); + done += n; + } + assert!(out == plain[at..at + len], "{mode:?} {at} {len}"); + } + let mut out = [0u8; 16]; + assert_eq!(file.read_at(&mut out, 299_999).unwrap(), 2, "{mode:?}"); + assert_eq!(file.read_at(&mut out, 300_001).unwrap(), 0, "{mode:?}"); + assert_eq!(file.read_at(&mut out, 400_000).unwrap(), 0, "{mode:?}"); + } + } + /// Lanes without workers: what `start` picks, and when statuses land. fn lanes(staging: u64) -> Lanes { Lanes { diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index 902c4a9..446263f 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -519,7 +519,7 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi // fail there instead of faulting into its handler; the title's // synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned // destinations and retry a failed `ReadFile` forever. So the destination -// is opened first. +// is opened first, and not guarded again before the call is done. pub extern "system" fn ReadFile( file: *mut c_void, @@ -528,15 +528,36 @@ pub extern "system" fn ReadFile( read: *mut u32, overlapped: *mut c_void, ) -> i32 { - victory_gpu::kernel_will_write(buffer as usize, len as usize); - host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( + let writing = victory_gpu::kernel_writing(buffer as usize, len as usize); + let done = host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( file, buffer, len, read, overlapped, - ) + ); + // The call's error is the title's to ask for. + // SAFETY: plain calls. + let error = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + // shortcut: a read that goes on after the call (overlapped) is written + // into pages the kernel has locked by now: it lands all the same, but a + // refresh that guards its blocks before it does will not see it. + if done == 0 && error == windows_sys::Win32::Foundation::ERROR_IO_PENDING { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::info!(len, "ReadFile: a read of the title's goes on after the call")); + } + if done == 0 && error == windows_sys::Win32::Foundation::ERROR_NOACCESS { + static FAILED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = FAILED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::warn!(n, buffer = format_args!("{buffer:p}"), len, "ReadFile: the title's buffer could not be written"); + } + } + drop(writing); + // SAFETY: as above. + unsafe { windows_sys::Win32::Foundation::SetLastError(error) }; + done } /// The host CRT reads large requests straight into the caller's buffer. pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize { - victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count)); + let _writing = victory_gpu::kernel_writing(buffer as usize, size.saturating_mul(count)); host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)( buffer, size, count, stream, ) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 5aa88d1..ee0e172 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -11,7 +11,7 @@ use std::alloc::{Layout, alloc, dealloc}; use std::collections::{BTreeMap, HashMap}; use std::ffi::c_void; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; +use std::sync::{Arc, LazyLock, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; use windows_sys::Win32::Foundation::{ CloseHandle, ERROR_COMMITMENT_LIMIT, HANDLE, INVALID_HANDLE_VALUE, @@ -162,6 +162,9 @@ pub extern "system" fn XMemVirtualAlloc( "XMemVirtualAlloc" ); } + if !at.is_null() && !placeholder { + victory_gpu::title_memory_allocated(at as usize, size); + } at } @@ -435,65 +438,74 @@ struct Slice { #[derive(Default)] struct Physical { - next_page: usize, - pages: HashMap, /// Mapped views by address: their length and what they show. views: BTreeMap, - /// The other way: the views (by address) that show a page, by the page's - /// section and index. Views of more than [`SHORT`] pages are in `long`. - shown: HashMap<(usize, usize), Vec>, - long: Vec, } -/// Pages of a view noted page by page in [`Physical::shown`]. +/// The title's pages by number. +struct Pages { + next_page: usize, + pages: HashMap, +} + +/// Where the title sees its pages: [`Physical::views`] the other way. +/// Locked apart from them, and only for a moment ([`PAGES`]). +#[derive(Default)] +struct Shown { + /// The addresses that show a page, by the page's section and index. + /// Views of more than [`SHORT`] pages are in `long`. + pages: HashMap<(usize, usize), Vec>, + /// Address, bytes, section, first page. + long: Vec<(usize, usize, usize, usize)>, +} + +/// Pages of a view noted page by page in [`Shown::pages`]. const SHORT: usize = 64; -impl Physical { - fn note_view(&mut self, base: usize, len: usize, slice: &Slice) { +/// Taken after [`PHYSICAL`] where both are. +static SHOWN: LazyLock> = LazyLock::new(Default::default); + +fn shown_mut() -> RwLockWriteGuard<'static, Shown> { + SHOWN.write().unwrap_or_else(|e| e.into_inner()) +} + +impl Shown { + fn note(&mut self, base: usize, len: usize, slice: &Slice) { + let section = Arc::as_ptr(&slice.section) as usize; if len / PAGE > SHORT { - self.long.push(base); + self.long.push((base, len, section, slice.index)); return; } - let section = Arc::as_ptr(&slice.section) as usize; for k in 0..len / PAGE { - self.shown.entry((section, slice.index + k)).or_default().push(base); + self.pages.entry((section, slice.index + k)).or_default().push(base + k * PAGE); } } - fn forget_view(&mut self, base: usize, len: usize, slice: &Slice) { + fn forget(&mut self, base: usize, len: usize, slice: &Slice) { if len / PAGE > SHORT { - self.long.retain(|&b| b != base); + self.long.retain(|view| view.0 != base); return; } let section = Arc::as_ptr(&slice.section) as usize; for k in 0..len / PAGE { let key = (section, slice.index + k); - if let Some(views) = self.shown.get_mut(&key) { - views.retain(|&b| b != base); - if views.is_empty() { - self.shown.remove(&key); + if let Some(at) = self.pages.get_mut(&key) { + at.retain(|&at| at != base + k * PAGE); + if at.is_empty() { + self.pages.remove(&key); } } } } - /// Where the title sees `n` pages from `slice` on: addresses and bytes. - fn shown_at(&self, slice: &Slice, n: usize) -> Vec<(usize, usize)> { + /// Where the title sees the page at `slice`: addresses and bytes. + fn at(&self, slice: &Slice) -> Vec<(usize, usize)> { let section = Arc::as_ptr(&slice.section) as usize; - let mut out: Vec<(usize, usize)> = Vec::new(); - for k in 0..n { - for &base in self.shown.get(&(section, slice.index + k)).into_iter().flatten() { - if let Some((_, s)) = self.views.get(&base) { - out.push((base + (slice.index + k - s.index) * PAGE, PAGE)); - } - } - } - for &base in &self.long { - let Some((len, s)) = self.views.get(&base) else { continue }; - let from = slice.index.max(s.index); - let to = (slice.index + n).min(s.index + len / PAGE); - if Arc::as_ptr(&s.section) as usize == section && from < to { - out.push((base + (from - s.index) * PAGE, (to - from) * PAGE)); + let mut out: Vec<(usize, usize)> = + self.pages.get(&(section, slice.index)).into_iter().flatten().map(|&at| (at, PAGE)).collect(); + for &(base, len, of, index) in &self.long { + if of == section && (index..index + len / PAGE).contains(&slice.index) { + out.push((base + (slice.index - index) * PAGE, PAGE)); } } out @@ -510,13 +522,13 @@ pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) { return; } let mut seen: Vec<(usize, usize)> = { - let physical = physical(); let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default(); - numbers - .iter() - .filter_map(|n| physical.pages.get(n)) - .flat_map(|slice| physical.shown_at(slice, 1)) - .collect() + let slices: Vec = { + let table = page_table(); + numbers.iter().filter_map(|n| table.pages.get(n)).cloned().collect() + }; + let shown = SHOWN.read().unwrap_or_else(|e| e.into_inner()); + slices.iter().flat_map(|slice| shown.at(slice)).collect() }; seen.sort_unstable(); let mut runs: Vec<(usize, usize)> = Vec::new(); @@ -538,18 +550,35 @@ pub(crate) fn stream_notice() -> bool { *ON } -static PHYSICAL: LazyLock> = LazyLock::new(|| { - Mutex::new(Physical { - // Page numbers are opaque to titles; 0 stays unused. - next_page: 0x10_0000, - ..Default::default() - }) -}); +/// The views, changed by the title's mapping calls; held for as long as +/// those take (the host maps, commits and unmaps under it). +static PHYSICAL: LazyLock> = LazyLock::new(Default::default); fn physical() -> MutexGuard<'static, Physical> { PHYSICAL.lock().unwrap_or_else(|e| e.into_inner()) } +/// The title's pages. Apart from the views: DirectStorage looks pages up at +/// every request, from 24 workers, and used to wait there for the title's +/// mapping calls (12,000 waits of 1 to 170 ms in a load of 90 s). Written +/// only where the title allocates or frees pages. Taken after [`PHYSICAL`] +/// where both are. +static PAGES: LazyLock> = LazyLock::new(|| { + RwLock::new(Pages { + // Page numbers are opaque to titles; 0 stays unused. + next_page: 0x10_0000, + pages: HashMap::new(), + }) +}); + +fn page_table() -> RwLockReadGuard<'static, Pages> { + PAGES.read().unwrap_or_else(|e| e.into_inner()) +} + +fn page_table_mut() -> RwLockWriteGuard<'static, Pages> { + PAGES.write().unwrap_or_else(|e| e.into_inner()) +} + /// `count` is in and out (pages wanted, pages given); all or nothing here. pub extern "system" fn XMemAllocatePhysicalPages( flags: u64, @@ -603,18 +632,22 @@ pub extern "system" fn XMemAllocatePhysicalPages( window: std::sync::OnceLock::new(), committed: (0..n.div_ceil(64)).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), }); - let mut physical = physical(); - let first = physical.next_page; - physical.next_page += n * FRAMES; + let mut table = page_table_mut(); + let first = table.next_page; + table.next_page += n * FRAMES; for index in 0..n { let slice = Slice { section: section.clone(), index, }; - let number = first + index * FRAMES; - physical.pages.insert(number, slice); + table.pages.insert(first + index * FRAMES, slice); + } + // Title memory is touched without our locks: a fault there may wait for + // a mapping call, which takes them. + drop(table); + for index in 0..n { // SAFETY: the title passes room for `n` page numbers. - unsafe { pages.add(index).write(number) }; + unsafe { pages.add(index).write(first + index * FRAMES) }; } 1 } @@ -629,11 +662,13 @@ pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> B if pages.is_null() { return 0; } - let mut physical = physical(); - for i in 0..n { - // SAFETY: the title passes `n` page numbers. - physical.pages.remove(&unsafe { *pages.add(i) }); - } + // SAFETY: the title passes `n` page numbers. + let numbers = unsafe { std::slice::from_raw_parts(pages, n) }.to_vec(); + let mut table = page_table_mut(); + // Dropped without the lock: the last page of a section unmaps its window. + let gone: Vec = numbers.iter().filter_map(|number| table.pages.remove(number)).collect(); + drop(table); + drop(gone); 1 } @@ -689,16 +724,15 @@ impl Drop for View { /// The pages behind bytes `[offset, offset + len)` of `pages` (64 KiB /// each), as runs of consecutive slices of one section: each run's first -/// slice and its length in pages. One look at the page table, which the -/// title's own mapping calls share with every DirectStorage worker. `None` +/// slice and its length in pages. One look at the page table. `None` /// if a page is unknown or `pages` ends early. fn runs(pages: &[usize], offset: usize, len: usize) -> Option> { let end = offset.checked_add(len)?; let pages = pages.get(offset / PAGE..end.div_ceil(PAGE))?; - let physical = physical(); + let table = page_table(); let mut runs: Vec<(Slice, usize)> = Vec::new(); for page in pages { - let Some(slice) = physical.pages.get(page) else { + let Some(slice) = table.pages.get(page) else { tracing::warn!(page, offset, len, "a physical page the title does not own (any more)"); return None; }; @@ -717,25 +751,25 @@ fn runs(pages: &[usize], offset: usize, len: usize) -> Option bool { - let physical = physical(); + let table = page_table(); pages .get(offset / PAGE..(offset + len).div_ceil(PAGE)) - .is_some_and(|pages| pages.iter().all(|page| physical.pages.contains_key(page))) + .is_some_and(|pages| pages.iter().all(|page| table.pages.contains_key(page))) } /// Where the title sees the pages under bytes `[offset, offset + len)` now, /// in order (for the streaming trace: whether that changed while a request /// wrote them). pub(crate) fn pages_shown(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> { - let physical = physical(); let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default(); - let mut shown: Vec<(usize, usize)> = numbers - .iter() - .filter_map(|n| physical.pages.get(n)) - .flat_map(|slice| physical.shown_at(slice, 1)) - .collect(); - shown.sort_unstable(); - shown + let slices: Vec = { + let table = page_table(); + numbers.iter().filter_map(|n| table.pages.get(n)).cloned().collect() + }; + let shown = SHOWN.read().unwrap_or_else(|e| e.into_inner()); + let mut at: Vec<(usize, usize)> = slices.iter().flat_map(|slice| shown.at(slice)).collect(); + at.sort_unstable(); + at } /// Copies `data` into physical pages, from `offset` bytes into the first, @@ -822,6 +856,10 @@ pub extern "system" fn XMemMapPhysicalPages( pages: *const usize, ) -> *mut c_void { let base = address as usize; + // Read before any lock is taken: a fault in title memory may wait for + // the mapping call that holds them. + // SAFETY: the title passes `n` page numbers, or null. + let pages = (!pages.is_null()).then(|| unsafe { std::slice::from_raw_parts(pages, n) }.to_vec()); let mut physical = physical(); // Until the pages are mapped again: `unmap` takes whole views away and // maps what stays of them again, and a mapped view is a reservation @@ -829,23 +867,25 @@ pub extern "system" fn XMemMapPhysicalPages( // into that gap (`victory_gpu::title_memory_remapping`). let _changing = victory_gpu::title_memory_remapping(); unmap(&mut physical, base, n * PAGE); - if pages.is_null() { + let Some(pages) = pages else { return address; - } - // SAFETY: the title passes `n` page numbers. - let pages = unsafe { std::slice::from_raw_parts(pages, n) }; + }; + let slices: Vec> = { + let table = page_table(); + pages.iter().map(|page| table.pages.get(page).cloned()).collect() + }; let mut i = 0; while i < n { - let Some(first) = physical.pages.get(&pages[i]).cloned() else { + let Some(first) = slices[i].clone() else { tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page"); return std::ptr::null_mut(); }; // One view per run of consecutive slices of one section. - let run = 1 + pages[i + 1..] + let run = 1 + slices[i + 1..] .iter() .zip(1..) - .take_while(|&(page, k)| { - physical.pages.get(page).is_some_and(|s| { + .take_while(|&(slice, k)| { + slice.as_ref().is_some_and(|s| { Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k }) }) @@ -960,11 +1000,14 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; return false; } + // Noted before the GPU side is told: bytes DirectStorage put in earlier, + // without notice at these addresses ([`pages_written`]), are there by + // the time the copies of them go. + shown_mut().note(base, len, &slice); // New contents, read-write: the GPU side's copies no longer guard it. victory_gpu::title_memory_remapped(base, len); // What the range shows now, for the GPU side's in-place census. victory_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64); - physical.note_view(base, len, &slice); physical.views.insert(base, (len, slice)); true } @@ -1043,7 +1086,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { let Some((size, slice)) = physical.views.remove(&at) else { continue; }; - physical.forget_view(at, size, &slice); + shown_mut().forget(at, size, &slice); victory_gpu::title_memory_unmapping(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { @@ -1151,11 +1194,24 @@ pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL { moved.into() } +/// The title's own `VirtualFree`. What the GPU side noted of the memory goes +/// first: the address may be other memory's the moment it is free. +extern "system" fn title_virtual_free(address: *mut c_void, size: usize, kind: u32) -> BOOL { + const MEM_COALESCE_PLACEHOLDERS: u32 = 1; + // Splitting and joining placeholders changes nothing they show. + if kind & (MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS) == 0 { + victory_gpu::title_memory_freed(address as usize, size); + } + // SAFETY: the title's own arguments. + unsafe { VirtualFree(address, size, kind) } +} + pub(crate) fn module() -> HleModule { HleModule { name: "xmem", - dlls: &["xmem.dll"], + dlls: &["xmem.dll", "kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-*"], exports: vec![ + crate::HleExport { name: "VirtualFree", address: title_virtual_free as *const () as usize }, hle_export!(XMemAlloc), hle_export!(XMemFree), hle_export!(XMemAllocDefault), @@ -1398,7 +1454,9 @@ mod tests { let stop = stop.clone(); std::thread::spawn(move || { let mut reads = 0u64; - while !stop.load(Ordering::Relaxed) { + // (Once at least: the mapping thread may be done before this + // one's first turn.) + while reads == 0 || !stop.load(Ordering::Relaxed) { let _reading = victory_gpu::title_memory_reading(); // SAFETY: the page is mapped whenever no change of // mapping is under way, and none is while `_reading` @@ -1420,6 +1478,57 @@ mod tests { assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); } + /// A title thread that reads and writes a page of a view while other + /// pages of the view are unmapped and mapped again, as the console lets + /// it: the page was never given up. + #[test] + fn a_title_thread_goes_on_using_the_rest_of_a_view() { + use std::sync::atomic::{AtomicBool, Ordering}; + let pages = allocate(4); + for _ in 0..200 { + // A new reservation each time: the pieces of a view cut up stay + // cut up. + let a = XMemVirtualAlloc( + std::ptr::null_mut(), + 4 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ); + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 4, pages.as_ptr()), a); + let (first, stop) = (a as usize, AtomicBool::new(false)); + // SAFETY: mapped read-write. + unsafe { (first as *mut u64).write_volatile(0) }; + std::thread::scope(|s| { + let title = s.spawn(|| { + let mut n = 0u64; + // SAFETY (the block): the first page is the title's all + // the time; a fault would end the process. + unsafe { + while !stop.load(Ordering::Relaxed) { + assert_eq!((first as *const u64).read_volatile(), n); + n += 1; + (first as *mut u64).write_volatile(n); + } + } + n + }); + // SAFETY: as above. + while !title.is_finished() && unsafe { (first as *const u64).read_volatile() } < 100 {} + for page in [3, 2, 1] { + let at = a.wrapping_byte_add(page * PAGE); + assert_eq!(XMemMapPhysicalPages(at, 1, std::ptr::null()), at); + assert_eq!(XMemMapPhysicalPages(at, 1, pages[page..].as_ptr()), at); + } + stop.store(true, Ordering::Relaxed); + assert!(title.join().expect("the title's thread never faulted") > 0); + }); + assert_eq!(XMemMapPhysicalPages(a, 4, std::ptr::null()), a); + } + assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); + } + #[test] fn mapping_no_pages_changes_nothing() { let pages = allocate(2); @@ -1461,6 +1570,66 @@ mod tests { assert_eq!(XMemFreePhysicalPages(2, pages.as_ptr()), 1); } + /// What a title that maps and unmaps pages all the time costs the + /// workers that write others: 24 threads look pages up, fill one and + /// tell of it, as a request does, while one maps. + /// `cargo test --release -p victory-hle --lib map_bench -- --ignored --nocapture` + #[test] + #[ignore = "a benchmark"] + fn map_bench() { + use std::sync::atomic::AtomicU64; + use std::time::{Duration, Instant}; + let pages = allocate(1024); + let a = XMemVirtualAlloc(std::ptr::null_mut(), 1024 * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE) as usize; + for mapping in [false, true] { + let (done, waited, worst, maps) = + (AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)); + let until = Instant::now() + Duration::from_secs(3); + std::thread::scope(|s| { + if mapping { + s.spawn(|| { + let at: Vec<*mut c_void> = (0..256).map(|i| (a + i * PAGE) as *mut c_void).collect(); + while Instant::now() < until { + assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 256, pages.as_ptr()), 1); + assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 256, std::ptr::null()), 1); + maps.fetch_add(512, Ordering::Relaxed); + } + }); + } + for t in 0..24 { + let (pages, done, waited, worst) = (&pages, &done, &waited, &worst); + s.spawn(move || { + let mut i = 256 + t * 16; + while Instant::now() < until { + let page = &pages[i..=i]; + i = if i == 256 + t * 16 + 15 { 256 + t * 16 } else { i + 1 }; + let began = Instant::now(); + assert!(pages_known(page, 0, PAGE)); + let mut window = page_window(page, 0, PAGE).unwrap(); + let looked = began.elapsed(); + window.bytes().fill(t as u8); + let began = Instant::now(); + pages_written(page, 0, PAGE); + let took = (looked + began.elapsed()).as_nanos() as u64; + waited.fetch_add(took, Ordering::Relaxed); + worst.fetch_max(took, Ordering::Relaxed); + done.fetch_add(1, Ordering::Relaxed); + } + }); + } + }); + let n = done.load(Ordering::Relaxed).max(1); + println!( + "mapping {mapping}: {:.0} requests/s, {:.1} us of each on lookups and notices (worst {:.1} ms); {:.0} maps/s", + n as f64 / 3.0, + waited.load(Ordering::Relaxed) as f64 / n as f64 / 1e3, + worst.load(Ordering::Relaxed) as f64 / 1e6, + maps.load(Ordering::Relaxed) as f64 / 3.0 + ); + } + assert_eq!(XMemFreePhysicalPages(1024, pages.as_ptr()), 1); + } + /// `n` pages of one new allocation. fn allocate(n: usize) -> Vec { let (mut pages, mut given) = (vec![0; n], n); @@ -1474,7 +1643,7 @@ mod tests { /// The bytes of one page, through a view of our own. fn page_bytes(page: usize) -> Vec { - let slice = physical().pages.get(&page).cloned().expect("known page"); + let slice = page_table().pages.get(&page).cloned().expect("known page"); View::map(&slice, 1).expect("mapped").bytes().to_vec() } diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index aed5c19..de8817d 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -10,6 +10,7 @@ static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0); /// `GetModuleHandle(NULL)` and friends to return this, not our own exe. pub fn set_main_image(base: usize) { MAIN_IMAGE_BASE.store(base, Ordering::Release); + crate::image_watch::start(base); } pub fn main_image() -> Option { diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index 4727b92..b43a0a7 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -718,9 +718,12 @@ fn translated_shaders_draw_as_pc_ones() { eprintln!("no console or PC compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-diff-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -874,9 +877,12 @@ fn translated_mesh_shaders_draw_as_pc_ones() { eprintln!("no console or PC compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-diff-ms-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -991,9 +997,12 @@ fn float_semantics_are_the_consoles() { eprintln!("no console compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-float-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -1080,9 +1089,12 @@ fn translated_compute_matches_pc() { eprintln!("no console or PC compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-diff-cs-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 8f5407a..4bb533f 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -185,12 +185,24 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); + // SAFETY: the feature query writes the structure of the given size. + // Older runtimes may not recognize OPTIONS19; that means no support. + let aniso_point_mip_supported = unsafe { + self.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS19, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + } + .is_ok() + && options.AnisoFilterWithPointMipSupported.as_bool(); let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { let [u, v, w] = d.address.map(|a| D3D12_TEXTURE_ADDRESS_MODE(a as i32)); samplers.push(D3D12_STATIC_SAMPLER_DESC { - Filter: D3D12_FILTER(d.filter as i32), + Filter: D3D12_FILTER(d.filter_for_host(aniso_point_mip_supported) as i32), AddressU: u, AddressV: v, AddressW: w, diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 899255f..7598738 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -50,7 +50,7 @@ enum Val { pub(crate) struct Lowered { pub dxil: Vec, - /// Bit n: immediate sampler n is used for comparisons. + /// Bit n: immediate sampler n is a comparison sampler. pub cmp_samplers: u64, pub root_cbvs: Vec, pub root_srvs: Vec, @@ -5226,6 +5226,10 @@ impl<'a> Lower<'a> { let x = crate::resource::inline(*k).ok_or("a special operand")?; Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 })) } + // Of a signed operand, a literal sign-extends too. + Some(&Operand::Literal(x)) if name.ends_with("_i64") => { + Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 })) + } _ => Ok(l.s.m.i32(0)), } }; @@ -5312,6 +5316,20 @@ impl<'a> Lower<'a> { l.s.m.cmp(c, pred::NE, o, z) }; return match name { + "s_quadmask_b64" => { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let low = self.quad_mask(a); + let high = self.quad_mask(b); + let k8 = self.s.m.i32(8); + let high = self.s.m.bin(c, Bin::Shl, high, k8); + let mask = self.s.m.bin(c, Bin::Or, low, high); + let zero = self.s.m.i32(0); + self.set(lo, Val::I32(mask)); + self.set(hi, Val::I32(zero)); + let nonzero = self.s.m.cmp(c, pred::NE, mask, zero); + self.set(scc, Val::Bit(nonzero)); + Ok(()) + } "s_bcnt1_i32_b64" => { let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); let i32t = self.s.t.i32; @@ -5437,6 +5455,10 @@ impl<'a> Lower<'a> { let (r, carry): (V, Option) = match name { "s_mov_b32" => (src32(self, 0)?, None), "s_movk_i32" => (sext16(self), None), + "s_quadmask_b32" => { + let pixels = src32(self, 0)?; + (self.quad_mask(pixels), None) + } "s_cselect_b32" => { let cond = self.scc_in(inst)?; let (a, b) = (src32(self, 0)?, src32(self, 1)?); @@ -5630,6 +5652,29 @@ impl<'a> Lower<'a> { Ok(()) } + /// Packs whether each consecutive group of four pixels has a set bit. + fn quad_mask(&mut self, pixels: V) -> V { + let c = self.cur; + let one = self.s.m.i32(1); + let shifted = self.s.m.bin(c, Bin::LShr, pixels, one); + let mut mask = self.s.m.bin(c, Bin::Or, pixels, shifted); + // Fold each nibble into its bottom bit, then gather those bits into + // the low byte in three stages without needing a 64-bit operation. + for (distance, keep) in [ + (2, 0x1111_1111), + (3, 0x0303_0303), + (6, 0x000f_000f), + (12, 0x0000_00ff), + ] { + let distance = self.s.m.i32(distance); + let shifted = self.s.m.bin(c, Bin::LShr, mask, distance); + let combined = self.s.m.bin(c, Bin::Or, mask, shifted); + let keep = self.s.m.i32(keep); + mask = self.s.m.bin(c, Bin::And, combined, keep); + } + mask + } + /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the /// scalar and vector add-with-carry instructions set it. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option) -> (V, V) { @@ -6300,20 +6345,34 @@ impl<'a> Lower<'a> { l.s.m.bin(c, Bin::AShr, t, k) }; let f32t = self.s.t.f32; + // A normalized format's ends are exactly 1.0 and -1.0. The host + // may divide through a reciprocal and land just below 1.0: RDNA + // 4 loaded 16_16_UNORM's 65535 as the half 0x3BFF, not 0x3C00. let x = match numeric { Numeric::Unorm => { let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); - let max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits()); + let top = (1u64 << w) - 1; + let max = self.s.m.f32((top as f32).to_bits()); let q = self.s.m.bin(c, Bin::SDiv, f, max); + let (high, one) = (self.s.m.i32(top as u32), self.s.m.f32(1.0f32.to_bits())); + let at_top = self.s.m.cmp(c, pred::EQ, field, high); + let q = self.s.m.select(c, at_top, one, q); float(self, q) } Numeric::Snorm => { let s = signed(self); let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); - let max = self.s.m.f32((((1u64 << (w - 1)) - 1) as f32).to_bits()); + let top = (1u32 << (w - 1)) - 1; + let max = self.s.m.f32((top as f32).to_bits()); let q = self.s.m.bin(c, Bin::SDiv, f, max); - let lo = self.s.m.f32((-1.0f32).to_bits()); - let q = self.binary(35, q, lo); + // The lowest value is -1.0 too, as is the one above it. + let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits())); + let at_top = self.s.m.cmp(c, pred::SGE, s, high); + let q = self.s.m.select(c, at_top, one, q); + let low = self.s.m.i32(top.wrapping_neg()); + let minus_one = self.s.m.f32((-1.0f32).to_bits()); + let at_bottom = self.s.m.cmp(c, pred::SLE, s, low); + let q = self.s.m.select(c, at_bottom, minus_one, q); float(self, q) } Numeric::Uscaled => { @@ -6355,6 +6414,39 @@ impl<'a> Lower<'a> { Ok(out) } + /// Channels of buffer format `format`, as [`Self::format_load`] gives + /// them, as d16 data: 16 bits each, two per dword, low half first (an + /// odd last high half 0). Integer formats keep their low 16 bits; the + /// others become f16. + fn d16_channels(&mut self, format: u8, channels: Vec) -> Result, Why> { + let (_, numeric) = buffer_format(format).ok_or("a buffer format")?; + let c = self.cur; + let mut halves = Vec::new(); + for x in channels { + halves.push(if matches!(numeric, Numeric::Uint | Numeric::Sint) { + let m = self.s.m.i32(0xFFFF); + self.s.m.bin(c, Bin::And, x, m) + } else { + let (f, i32t) = (self.as_float(x), self.s.t.i32); + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + }); + } + let mut out = Vec::new(); + for pair in halves.chunks(2) { + out.push(match *pair { + [lo, hi] => { + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, lo, hi) + } + [lo] => lo, + _ => unreachable!("chunks of one or two"), + }); + } + Ok(out) + } + /// The byte offset a buffer descriptor built around a root descriptor adds /// (constant and computed parts); none for other descriptors. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option), Why> { @@ -6467,23 +6559,8 @@ impl<'a> Lower<'a> { Ok(h) } Source::Constant(words) if sampler => { - let words: [u32; 4] = words - .get(..4) - .and_then(|w| w.try_into().ok()) - .ok_or("a sampler constant")?; - let n = match self.samplers.iter().position(|w| *w == words) { - Some(n) => n, - None => { - self.samplers.push(words); - self.samplers.len() - 1 - } - }; - if props.0 & 0x8000 != 0 { - // shortcut: one sampler used with and without comparison - // would need two static samplers; it becomes a comparison one. - self.s.cmp_samplers |= 1 << n; - } - Ok(self.s.sampler_handle(self.cur, n as u32)) + let n = self.register_sampler(words, props.0 & 0x8000 != 0)?; + Ok(self.s.sampler_handle(self.cur, n)) } Source::Constant(_) => Err("a constant resource descriptor"), Source::Built { address, .. } => { @@ -6594,22 +6671,30 @@ impl<'a> Lower<'a> { Ok(phi) } - /// Registers an immediate sampler constant and returns its slot index. + /// Registers an immediate sampler constant and returns its slot index: a + /// constant used with and without comparison takes one slot for each. fn register_sampler(&mut self, words: &[u32], cmp: bool) -> Result { let words: [u32; 4] = words .get(..4) .and_then(|w| w.try_into().ok()) .ok_or("a sampler constant")?; - let n = match self.samplers.iter().position(|w| *w == words) { + let slot = self + .samplers + .iter() + .enumerate() + .position(|(n, w)| *w == words && (self.s.cmp_samplers >> n & 1 != 0) == cmp); + let n = match slot { Some(n) => n, None => { + let n = self.samplers.len(); + if n >= u64::BITS as usize { + return Err("more than 64 immediate sampler slots"); + } self.samplers.push(words); - self.samplers.len() - 1 + self.s.cmp_samplers |= u64::from(cmp) << n; + n } }; - if cmp && n < 64 { - self.s.cmp_samplers |= 1 << n; - } Ok(n as u32) } @@ -7630,6 +7715,17 @@ impl<'a> Lower<'a> { let r = self.s.m.cast(c, op, a, self.s.t.f32); float(self, r) } + "v_cvt_off_f32_i4" => { + // The low nibble as a signed 4-bit integer, over 16. + let a = s(self, 0)?; + let k28 = self.s.m.i32(28); + let a = self.s.m.bin(c, Bin::Shl, a, k28); + let a = self.s.m.bin(c, Bin::AShr, a, k28); + let f = self.s.m.cast(c, Cast::SiToFp, a, self.s.t.f32); + let k = self.s.m.f32(0.0625f32.to_bits()); + let r = self.s.m.bin(c, Bin::Mul, f, k); + float(self, r) + } "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { // Each source is f32, or with op_sel_hi the low (op_sel: high) // f16 half; neg_hi is the absolute value here. @@ -8065,8 +8161,14 @@ impl<'a> Lower<'a> { let x = crate::resource::inline(k).ok_or("a special operand")?; Ok(self.s.m.int_const(i64t, i64::from(x as i32))) } + // A signed 64-bit operand sign-extends its 32-bit literal, as + // the hardware does (LLVM's AMDGPU operand rules). + Operand::Literal(x) if inst.name().ends_with("_i64") => { + Ok(self.s.m.int_const(i64t, i64::from(x as i32))) + } _ => { - // Literals and the null register: zero-extended. + // Literals (of unsigned and bit operands) and the null + // register: zero-extended. let x = self.operand(inst, &op)?; Ok(self.s.m.cast(c, Cast::ZExt, x, i64t)) } @@ -9019,6 +9121,18 @@ impl<'a> Lower<'a> { let b = self.s.m.bin(c, op, b, sh); self.s.m.bin(c, Bin::Mul, a, b) } + "v_mul_hi_u32_u24" | "v_mul_hi_i32_i24" => { + // The high dword of the same 48-bit product: the low 24 bits + // of each operand, zero- or sign-extended, multiplied. + let (a, b) = (s(self, 0)?, s(self, 1)?); + let signed = name == "v_mul_hi_i32_i24"; + let (sh, op) = (k(self, 8), if signed { Bin::AShr } else { Bin::LShr }); + let a = self.s.m.bin(c, Bin::Shl, a, sh); + let a = self.s.m.bin(c, op, a, sh); + let b = self.s.m.bin(c, Bin::Shl, b, sh); + let b = self.s.m.bin(c, op, b, sh); + self.mul_hi(a, b, signed) + } "v_bfe_u32" | "v_bfe_i32" => { let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); let w = m31(self, w); @@ -9097,6 +9211,44 @@ impl<'a> Lower<'a> { let m = self.s.m.bin(c, Bin::Mul, a, b); self.s.m.bin(c, Bin::Add, m, d) } + "v_sad_u8" | "v_sad_hi_u8" | "v_sad_u16" | "v_sad_u32" | "v_msad_u8" => { + // src2 plus the sum of the unsigned differences |a - b| of + // the operands' bytes, halves or whole dwords, wrapping at 32 + // bits. v_sad_hi_u8 adds the sum shifted to the high half; + // v_msad_u8 leaves out a byte whose mask byte (src1) is 0. + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let (width, parts) = match name { + "v_sad_u16" => (16, 2), + "v_sad_u32" => (32, 1), + _ => (8, 4), + }; + let zero = k(self, 0); + let mut sum = zero; + for i in 0..parts { + let (mut x, mut y) = (a, b); + if width < 32 { + let (sh, mask) = (k(self, width * i), k(self, (1 << width) - 1)); + x = self.s.m.bin(c, Bin::LShr, x, sh); + x = self.s.m.bin(c, Bin::And, x, mask); + y = self.s.m.bin(c, Bin::LShr, y, sh); + y = self.s.m.bin(c, Bin::And, y, mask); + } + let above = self.s.m.cmp(c, pred::IUGT, x, y); + let hi = self.s.m.select(c, above, x, y); + let lo = self.s.m.select(c, above, y, x); + let mut diff = self.s.m.bin(c, Bin::Sub, hi, lo); + if name == "v_msad_u8" { + let masked = self.s.m.cmp(c, pred::NE, y, zero); + diff = self.s.m.select(c, masked, diff, zero); + } + sum = self.s.m.bin(c, Bin::Add, sum, diff); + } + if name == "v_sad_hi_u8" { + let k16 = k(self, 16); + sum = self.s.m.bin(c, Bin::Shl, sum, k16); + } + self.s.m.bin(c, Bin::Add, sum, d) + } "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32" | "v_med3_u32" => { let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); @@ -10689,8 +10841,9 @@ impl<'a> Lower<'a> { "buffer_load_sshort" => Some((16, true)), _ => None, }; - // d16: two 16-bit channels per VGPR, low half first. - let d16 = name.starts_with("buffer_") && name.contains("_format_d16_"); + // d16: two 16-bit channels per VGPR, low half first (buffer and + // tbuffer formats alike). + let d16 = name.contains("_format_d16_"); let plain = name.replace("_format_d16_", "_format_"); let (typed, count) = match plain .strip_prefix("buffer_load_") @@ -11024,7 +11177,11 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = *data else { return Err("a buffer result"); }; - for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() { + let mut xs = self.format_load(h, off, f, count)?; + if d16 { + xs = self.d16_channels(f, xs)?; + } + for (k, x) in xs.into_iter().enumerate() { self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); @@ -11361,8 +11518,11 @@ impl<'a> Lower<'a> { Ok(()) } - /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all - /// indices 0: no area). + /// Mesh: `exp prim` as the lane's primitive. Each corner takes ten + /// bits: a 9-bit vertex index and, above it, its edge flag (bits 9, 19 + /// and 29), which only the console's edge-flag rasterisation reads and + /// which is no part of the index. Bit 31 culls it (all indices 0: no + /// area). fn emit_indices(&mut self, e: &Export, guard: Option) -> Result<(), Why> { let v = e.values[0].ok_or("a primitive export without its indices")?; let x = self.i32_of(v)?; @@ -11395,7 +11555,7 @@ impl<'a> Lower<'a> { }); let mut indices = [z; 3]; for (k, slot) in indices.iter_mut().enumerate() { - let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x3FF)); + let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x1FF)); let i = self.s.m.bin(c, Bin::LShr, x, shift); let i = self.s.m.bin(c, Bin::And, i, mask); if let Some(n) = written { @@ -11994,6 +12154,55 @@ mod tests { } } + /// Lowers a one-thread compute program that copies four root constants + /// (s0..s3) into v1..v4, runs `body`, and stores v0 to a raw buffer from a + /// descriptor table, so the vector instructions in `body` have an effect. + fn lowers_valu(body: &[u32]) -> Result<(), crate::ShaderError> { + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xFA00_0000, + ]; + // v_mov_b32 v1..v4, s0..s3 + words.extend((0..4u32).map(|i| 0x7E00_0200 | (i + 1) << 17 | i)); + words.extend_from_slice(body); + words.extend_from_slice(&[ + 0xE070_0000, // buffer_store_dword v0, off, s[8:11], 0 + 0x8002_0000, + S_ENDPGM, + ]); + let constants = RootParam { + sgprs: 4, + ..root(RootType::Constants, 0, 0) + }; + let buffer = UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }; + lower_with( + &words, + vec![constants, root(RootType::Table, 4, 1)], + vec![buffer], + ) + .map(|_| ()) + } + + #[test] + fn the_24_bit_multiplies_lower_both_halves() { + // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low + // dword) and v_mul_hi_i32_i24 and v_mul_hi_u32_u24 (the high one). + for op in [0x09u32, 0x0A, 0x0B, 0x0C] { + let word = op << 25 | 2 << 9 | 0x101; + lowers_valu(&[word]).unwrap_or_else(|e| panic!("VOP2 {op:#x}: {e}")); + } + } + #[test] fn buffer_cache_invalidations_lower_as_no_ops() { // MUBUF opcode 0x071/0x072 with no data operand: the title asks the @@ -12002,6 +12211,16 @@ mod tests { assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); } + #[test] + fn sums_of_absolute_differences_lower() { + // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16, + // v_sad_u32 and v_msad_u8. + for op in [0x15Au32, 0x15B, 0x15C, 0x15D, 0x171] { + let words = [0xD400_0000 | op << 16, 0x101 | 0x102 << 9 | 0x103 << 18]; + lowers_valu(&words).unwrap_or_else(|e| panic!("VOP3 {op:#x}: {e}")); + } + } + #[test] fn a_scalar_carry_chain_reaches_the_select() { // The high dword of a 64-bit add or subtract, then a select on the diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index d919660..248e8c9 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -989,6 +989,98 @@ mod tests { assert!(lower(unmarked).is_err()); } + #[test] + fn immediate_sampler_slots_distinguish_comparison_uses() { + let words = [ + 0xBE81_0380u32, // s_mov_b32 s1, 0 + 0xF40C_0000, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[0:1], null + 0xBE88_0380, // s_mov_b32 s8, 0 + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0x7E00_02F0, // v_mov_b32 v0, 0.5 (comparison reference) + 0x7E02_02F0, // v_mov_b32 v1, 0.5 (u) + 0x7E04_02F0, // v_mov_b32 v2, 0.5 (v) + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xF080_0108, + 0x0040_0301, // image_sample v3, v[1:2], s[0:7], s[8:11] + 0xF0A0_0108, + 0x0040_0400, // image_sample_c v4, v[0:2], s[0:7], s[8:11] + 0xF0BC_0108, + 0x0040_0500, // image_sample_c_lz v5, v[0:2], s[0:7], s[8:11] + 0xF080_0108, + 0x0040_0601, // image_sample v6, v[1:2], s[0:7], s[8:11] + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xF800_180F, + 0x0605_0403, // exp mrt0, v3, v4, v5, v6 done vm + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 7, + layout: vec![crate::native::RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![crate::native::UsedResource { + kind: crate::native::ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let output = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + let osg1 = container::signature(&[output], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let out = emit(&c, &native, &p, &st, &io, &res).unwrap(); + + let sampler = StaticSampler::from_words([0; 4]); + let comparison = StaticSampler { + filter: sampler.filter | 0x80, + ..sampler + }; + assert_eq!(out.samplers, [[0; 4]; 2]); + assert_eq!(out.static_samplers, [sampler, comparison]); + #[cfg(windows)] + if let Some(path) = super::validator::Validator::default_path() { + let mut v = super::validator::Validator::load(Some(&path)).unwrap(); + v.validate(&mut out.dxil.clone()).unwrap(); + } + } + /// A wave64 compute program that writes only EXEC's high dword /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was /// opaque and keyed by the unchanged low dword, so building its lane bit @@ -1160,9 +1252,12 @@ mod tests { #[test] #[cfg(windows)] fn stub_pipeline_is_created() { - let Ok(host) = super::host::Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match super::host::Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let ps = super::HostShader { stage: crate::HwStage::Ps, @@ -1226,6 +1321,184 @@ mod tests { assert_eq!(c[4..20], ours[..], "our hash differs from the validator's"); } + /// Triangle (0, 1, 2), each corner's 9-bit index in its 10-bit field. + const TRIANGLE: u32 = 1 << 10 | 2 << 20; + /// The edge flags of the three corners (bits 9, 19 and 29). + const EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29; + /// The culling bit. + const CULL: u32 = 1 << 31; + + /// A one-wave (32-lane) triangle mesh program whose lanes all export + /// primitive `prim` and, as vertex `lane`, the position + /// (lane & 1 ? 3 : -1, lane & 2 ? 3 : -1, 0.5, 1): triangle (0, 1, 2) + /// covers the whole target. + fn triangle_mesh(prim: u32) -> Result { + let words = [ + 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x0001_00C1, + 0x3604_0281, // v_and_b32 v2, 1, v1 + 0x3606_0282, // v_and_b32 v3, 2, v1 + 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 + 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 + 0x1008_04F6, // v_mul_f32 v4, 4.0, v2 + 0x0608_08F3, // v_add_f32 v4, -1.0, v4 + 0x100A_06F4, // v_mul_f32 v5, 2.0, v3 + 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 + 0x7E0C_02F0, // v_mov_b32 v6, 0.5 + 0x7E0E_02F2, // v_mov_b32 v7, 1.0 + 0x7E12_02FF, // v_mov_b32 v9, prim + prim, + 0xF800_0941, // exp prim v9, off, off, off done + 0x0000_0009, + 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done + 0x0706_0504, + 0xBF81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Ms, + wave64: false, + vgprs: 10, + layout: vec![], + used: vec![], + io: StageIo::Ms(crate::native::MeshIo { + outputs: vec![], + clip_cntl: 0, + threads: 32, + max_vertices: 32, + max_primitives: 32, + topology: 2, + lds_bytes: 0, + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let position = SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }; + let osg1 = container::signature(&[position], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes)?; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let st = structure::structure(&p)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native)?; + emit(&c, &native, &p, &st, &io, &res) + } + + /// A primitive export's corners are 9-bit indices: the edge flag above + /// each (bits 9, 19, 29) is no part of it. Masking ten bits made a + /// flagged corner index 512 or more, past any mesh program's vertices + /// (the draw test below shows the triangle). Flagged, unflagged and + /// culled exports translate, and dxil.dll, where there is one, takes + /// each module. + #[test] + fn primitive_export_indices_drop_the_edge_flags() { + #[cfg(windows)] + let mut validator = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) + .ok(); + for prim in [ + TRIANGLE, + TRIANGLE | EDGE_FLAGS, + TRIANGLE | EDGE_FLAGS | CULL, + ] { + let ms = triangle_mesh(prim).unwrap_or_else(|e| panic!("{prim:#x}: {e}")); + #[cfg(windows)] + if let Some(v) = validator.as_mut() { + v.validate(&mut ms.dxil.clone()) + .unwrap_or_else(|e| panic!("{prim:#x}: {e}")); + } + } + } + + /// A triangle mesh program on the host GPU and on WARP (where they have + /// mesh shaders): triangle (0, 1, 2) covers the target with its corners' + /// edge flags set as without them; with the culling bit, nothing is lit. + #[test] + #[cfg(windows)] + fn edge_flagged_triangles_draw_as_unflagged_ones() { + use super::host::{Draw, Host, Root}; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_FEATURE_D3D12_OPTIONS7, D3D12_FEATURE_DATA_D3D12_OPTIONS7, + D3D12_MESH_SHADER_TIER_NOT_SUPPORTED, D3D12_SHADER_VISIBILITY_MESH, + }; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let ps = constant_color(); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + // SAFETY: the query writes the structure of the given size. + let queried = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + if queried.is_err() || options.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED { + eprintln!("no mesh shaders on the {label} device; skipped"); + continue; + } + for (prim, culled) in [ + (TRIANGLE, false), + (TRIANGLE | EDGE_FLAGS, false), + (TRIANGLE | EDGE_FLAGS | CULL, true), + ] { + let ms = triangle_mesh(prim).unwrap(); + let root = host + .root_signature_for(&[(&ms, D3D12_SHADER_VISIBILITY_MESH)]) + .unwrap(); + let pso = host + .mesh_pipeline_with(&root, &ms.dxil, &ps) + .unwrap_or_else(|e| panic!("{label}: mesh pipeline: {e}")); + let texels = host + .draw( + &root, + &pso, + &Draw { + roots: vec![(0, Root::Constants(vec![0]))], + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups: 1, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + let lit = texels.iter().filter(|t| t[3] != 0.0).count(); + if culled { + assert_eq!(lit, 0, "{label}, {prim:#x}: a culled triangle lit texels"); + continue; + } + assert!( + texels.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0]), + "{label}, {prim:#x}: {lit} of 256 texels lit" + ); + } + eprintln!("{label}: edge-flagged triangles drew"); + ran += 1; + } + if ran == 0 { + eprintln!("no device with mesh shaders; skipped"); + } + } + /// A pixel shader interpolating at sample positions (PERSP_SAMPLE /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency: /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1) diff --git a/crates/victory-shader/src/emit/sampler.rs b/crates/victory-shader/src/emit/sampler.rs index e10c0c1..ca010e5 100644 --- a/crates/victory-shader/src/emit/sampler.rs +++ b/crates/victory-shader/src/emit/sampler.rs @@ -34,6 +34,18 @@ pub struct StaticSampler { impl Eq for StaticSampler {} impl StaticSampler { + /// The filter supported by the host device. Anisotropic point-mip + /// filtering is optional (`D3D12_OPTIONS19`); older devices retain the + /// previous linear-mip approximation. Comparison/min/max reduction + /// bits and the sampler's LOD bounds are unchanged. + pub fn filter_for_host(&self, aniso_point_mip_supported: bool) -> u32 { + if !aniso_point_mip_supported && self.filter & !0x180 == 0x54 { + self.filter | 1 + } else { + self.filter + } + } + /// Decodes the four sampler words. pub fn from_words(w: [u32; 4]) -> Self { let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1); @@ -47,7 +59,7 @@ impl StaticSampler { _ => 0, }; let filter = if mag >= 2 || min >= 2 { - 0x55 | reduction << 7 + 0x54 | u32::from(mip == 2) | reduction << 7 } else { (min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7 }; @@ -122,4 +134,54 @@ mod tests { (0x1D5, 16, 15.0) ); } + + #[test] + fn anisotropic_samplers_preserve_mip_point_filtering() { + for (reduction, base) in [(0u32, 0x54u32), (1, 0x154), (2, 0x1D4)] { + let w0 = reduction << 29; + for mip in [0u32, 1] { + let w2 = (mip << 26) | 0x00F0_0000; // mag = 3, min = 3 + let s = StaticSampler::from_words([w0, 0x00FF_F000, w2, 0]); + assert_eq!(s.filter, base, "reduction={reduction} mip={mip}"); + } + let w2 = (2 << 26) | 0x00F0_0000; // mip = 2 (linear) + let s = StaticSampler::from_words([w0, 0x00FF_F000, w2, 0]); + assert_eq!(s.filter, base | 1, "reduction={reduction} mip=2"); + } + // Mixed anisotropic mag (2) with linear min (1) and point mip (1). + let mixed = StaticSampler::from_words([0, 0, (1 << 26) | (1 << 22) | (2 << 20), 0]); + assert_eq!(mixed.filter, 0x54); + } + + #[test] + fn host_filter_falls_back_without_changing_reduction_or_lod() { + for (filter, fallback) in [(0x54, 0x55), (0xD4, 0xD5), (0x154, 0x155), (0x1D4, 0x1D5)] { + for mip in [0u32, 1] { + let s = StaticSampler { + filter, + ..StaticSampler::from_words([0, 0x0054_0100, (mip << 26) | 0x00F0_0000, 0]) + }; + assert_eq!(s.filter_for_host(false), fallback); + assert_eq!(s.filter_for_host(true), filter); + assert_eq!( + (s.min_lod, s.max_lod), + if mip == 0 { (0.0, 0.0) } else { (1.0, 5.25) } + ); + } + } + } + + #[test] + fn host_filter_keeps_other_filters_unchanged() { + for reduction in [0, 0x80, 0x100, 0x180] { + for base in [0, 1, 4, 5, 0x10, 0x11, 0x14, 0x15, 0x55] { + let s = StaticSampler { + filter: base | reduction, + ..StaticSampler::from_words([0; 4]) + }; + assert_eq!(s.filter_for_host(false), s.filter); + assert_eq!(s.filter_for_host(true), s.filter); + } + } + } } diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index f5c2014..65c0c9d 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -219,9 +219,12 @@ fn run_cases_on( let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut ran = 0; for &(label, warp) in devices { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; + let host = match Host::new(warp) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 {label} device ({e}); skipped"); + continue; + } }; let (root, pso) = host .compute_pipeline(shader) @@ -259,6 +262,39 @@ fn run_cases_on( assert!(ran > 0, "no SM 6.6 device available ({devices:?})"); } +#[test] +fn scalar_quad_masks_pack_nibbles_and_set_scc() { + let pack_words = |opcode: u32| { + [ + 0xBE90_0000 | opcode << 8, // s_quadmask s16, s0 (pairs for b64) + sop2(0x0a, 18, 129, 128), // s_cselect_b32 s18, 1, 0 + sop2(0x1e, 18, 18, 144), // s_lshl_b32 s18, s18, 16 + sop2(0x10, 16, 16, 18), // s_or_b32 s16, s16, s18 + vop1(1, 0, sgpr(16)), // v_mov_b32 v0, s16 + ] + }; + let cases = [ + ([0, 0, 0, 0], [0, 0]), + ([0x8000_0420, 0x0100_0001, 0, 0], [0x1_0086, 0x1_4186]), + ([0, 0x8000_0000, 0, 0], [0, 0x1_8000]), + ([u32::MAX, u32::MAX, 0, 0], [0x1_00ff, 0x1_ffff]), + ]; + let inputs = cases.map(|(input, _)| input); + for (wide, opcode) in [0x2c, 0x2d].into_iter().enumerate() { + let shader = build_valu_cs(&pack_words(opcode)); + run_cases(&shader, &inputs, |backend, i, _, got| { + assert_eq!(got, cases[i].1[wide], "{backend}, opcode {opcode:#x}"); + }); + } + let high = build_valu_cs(&[ + 0xBE90_2D00, // s_quadmask_b64 s[16:17], s[0:1] + vop1(1, 0, sgpr(17)), + ]); + run_cases(&high, &inputs, |backend, _, _, got| { + assert_eq!(got, 0, "{backend}: high dword"); + }); +} + fn is_f16_nan(bits: u16) -> bool { (bits & 0x7FFF) > 0x7C00 } @@ -287,6 +323,78 @@ fn f16_to_f32(bits: u16) -> f32 { f32::from_bits(f32_bits) } +/// MTBUF `op vdata, off, s[srsrc:srsrc+3], 0 format:format` (at byte 0). +const fn mtbuf(op: u8, vdata: u8, srsrc: u8, format: u8) -> [u32; 2] { + [ + 0x3A << 26 | (format as u32 & 0x7F) << 19 | (op as u32 & 7) << 16, + 0x80 << 24 + | (op as u32 >> 3 & 1) << 21 + | (srsrc as u32 >> 2 & 0x1F) << 16 + | (vdata as u32) << 8, + ] +} + +/// Stores `v1` to the buffer, then reads it back into `v0` with the tbuffer +/// load `op` in buffer format `format`. +fn tbuffer_load_of_v1(op: u8, format: u8) -> HostShader { + let mut body = buffer_store_dword(1, 8, 0).to_vec(); + body.extend(mtbuf(op, 0, 8, format)); + build_valu_cs(&body) +} + +#[test] +fn tbuffer_d16_loads_pack_two_channels_per_dword() { + // tbuffer_load_format_d16_x and tbuffer_load_format_d16_xy. + let (x, xy) = (8, 9); + // (opcode, format, dword stored, dword loaded) + let cases: &[(u8, u8, u32, u32)] = &[ + // 16_16_FLOAT: the f16 pair (1.0, 2.0) as it was stored. + (xy, 29, 0x4000_3C00, 0x4000_3C00), + // 16_16_UINT: the 16-bit integers as they were stored. + (xy, 27, 0xBEEF_1234, 0xBEEF_1234), + // 16_16_UNORM: 0.0 and 1.0, as f16. + (xy, 23, 0xFFFF_0000, 0x3C00_0000), + // 16_FLOAT, one channel: the high half is 0. + (x, 13, 0x4000_3C00, 0x0000_3C00), + ]; + for &(op, format, stored, want) in cases { + let shader = tbuffer_load_of_v1(op, format); + run_cases(&shader, &[[stored, 0, 0, 0]], |backend, _, _, got| { + assert_eq!( + got, want, + "{backend}: d16 opcode {op} format {format} of {stored:#010x} = {got:#010x}, want {want:#010x}", + ); + }); + } +} + +#[test] +fn normalized_buffer_formats_load_their_ends_exactly() { + // tbuffer_load_format_x. + let x = 0; + // (format, dword stored, value loaded) + let cases: &[(u8, u32, f32)] = &[ + (1, 0xFF, 1.0), // 8_UNORM + (7, 0xFFFF, 1.0), // 16_UNORM + (2, 0x7F, 1.0), // 8_SNORM: the top, the one above the lowest, the lowest + (2, 0x81, -1.0), + (2, 0x80, -1.0), + (8, 0x7FFF, 1.0), // 16_SNORM + (8, 0x8001, -1.0), + (8, 0x8000, -1.0), + ]; + for &(format, stored, want) in cases { + let shader = tbuffer_load_of_v1(x, format); + run_cases(&shader, &[[stored, 0, 0, 0]], |backend, _, _, got| { + assert_eq!( + got, + want.to_bits(), + "{backend}: format {format} of {stored:#x} = {got:#010x}, want {want}", + ); + }); + } +} + #[test] fn packed_add_selects_halves_of_inline_constants() { // Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves. @@ -486,6 +594,77 @@ fn max_and_min_order_negative_zero_below_positive_zero() { } } +/// The f16 forms go through the same `max_min` helper, after widening to f32. +#[test] +fn f16_max_and_min_order_negative_zero_below_positive_zero() { + let (pz, nz) = (0_u32, 0x8000_u32); + let cases = [ + [nz, pz, nz, 0], + [pz, nz, nz, 0], + [nz, pz, pz, 0], + [pz, nz, pz, 0], + ]; + let ops = [ + ("v_max_f16", 0x139, pz), + ("v_min_f16", 0x13A, nz), + ("v_max3_f16", 0x354, pz), + ("v_min3_f16", 0x351, nz), + ]; + for (name, op, want) in ops { + let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(&shader, &cases, |backend, _, inp, got| { + // The f16 result is the low half of v0. + assert_eq!(got & 0xFFFF, want, "{backend}: {name} {inp:x?}"); + }); + } +} + +#[test] +fn v_min3_max3_med3_integer_forms_match_rdna2() { + // v_{min3,max3,med3}_{i32,u32} v0, v1, v2, v3 (VOP3 0x152..0x159). + type Pick = fn([u32; 3]) -> u32; + let ops: [(&str, u16, Pick); 6] = [ + ("v_min3_i32", 0x152, |t| { + t.into_iter().min_by_key(|&x| x as i32).unwrap() + }), + ("v_min3_u32", 0x153, |t| t.into_iter().min().unwrap()), + ("v_max3_i32", 0x155, |t| { + t.into_iter().max_by_key(|&x| x as i32).unwrap() + }), + ("v_max3_u32", 0x156, |t| t.into_iter().max().unwrap()), + ("v_med3_i32", 0x158, |mut t| { + t.sort_by_key(|&x| x as i32); + t[1] + }), + ("v_med3_u32", 0x159, |mut t| { + t.sort_unstable(); + t[1] + }), + ]; + // Every ordering of three values, with the sign bit set on some so that + // the signed and unsigned answers differ. + let values = [0u32, 1, 0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF]; + let mut cases = Vec::new(); + for a in values { + for b in values { + for c in values { + cases.push([a, b, c, 0]); + } + } + } + for (name, op, pick) in ops { + let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(&shader, &cases, |backend, _, inp, got| { + let want = pick([inp[0], inp[1], inp[2]]); + assert_eq!( + got, want, + "{backend}: {name}({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); + } +} + #[test] fn v_med3_f16_matches_rdna2_with_nan() { // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357) @@ -579,6 +758,31 @@ fn v_cmp_lg_is_false_for_nan() { } } +#[test] +fn v_cvt_off_f32_i4_uses_the_signed_low_nibble() { + // v_cvt_off_f32_i4 v0, v1 (VOP1 opcode 0x00e) + let shader = build_valu_cs(&[vop1(0x00e, 0, vgpr(1))]); + let nibble = |n: u32| (((n as i32) << 28) >> 28) as f32 / 16.0; + + let mut cases: Vec = (0..16).collect(); + // Bits above the low nibble are ignored. + cases.extend([0xABCD_EF05, 0xFFFF_FFF8, 0x1234_5670, 0x8000_000F, 0x0000_00F7]); + let inputs: Vec<[u32; 4]> = cases.iter().map(|&x| [x, 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = nibble(cases[i]).to_bits(); + assert_eq!( + got, want, + "{backend}: v_cvt_off_f32_i4({:#010x}) = {got:#010x} ({:?}), want {want:#010x}", + inp[0], + f32::from_bits(got), + ); + }); + // Spot-check the reference itself: 0x5 -> 0.3125, 0x8 -> -0.5, 0xF -> -0.0625. + assert_eq!(nibble(0xABCD_EF05), 0.3125); + assert_eq!(nibble(8), -0.5); + assert_eq!(nibble(0xF), -0.0625); +} + #[test] fn v_fract_f32_never_returns_one() { // v_fract_f32 v0, v1 (VOP1 opcode 0x020) @@ -865,6 +1069,40 @@ fn v_cvt_u16_and_i16_f16_saturate() { } } +#[test] +fn v_cvt_f16_u16_and_i16_widen_the_integer_first() { + // v_mov_b32 v0, 0; v_cvt_f16_u16 / v_cvt_f16_i16 v0, v1 (VOP1 0x050 / 0x051). + // Only integers f16 holds exactly: how the others round is the narrowing's + // business, not this conversion's. `None`: the result depends on rounding. + let cases: &[(u16, Option, Option)] = &[ + // (u16 / i16 input bits, f16 of the unsigned value, f16 of the signed value) + (0x0000, Some(0x0000), Some(0x0000)), // 0 + (0x0001, Some(0x3C00), Some(0x3C00)), // 1.0 + (0x07FF, Some(0x67FF), Some(0x67FF)), // 2047, the last integer below 2048 that f16 holds + (0x8000, Some(0x7800), Some(0xF800)), // 32768 / -32768 + (0xFC00, Some(0x7BE0), Some(0xE400)), // 64512 / -1024 + (0xFFFE, None, Some(0xC000)), // 65534 does not fit f16 / -2 + (0xFFFF, None, Some(0xBC00)), // 65535 does not fit f16 / -1 + ]; + for (op, what, pick) in [ + (0x050u16, "v_cvt_f16_u16", 0usize), + (0x051, "v_cvt_f16_i16", 1), + ] { + let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let want = if pick == 0 { cases[i].1 } else { cases[i].2 }; + let Some(want) = want else { return }; + assert_eq!( + got, + u32::from(want), + "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}", + cases[i].0, + ); + }); + } +} + #[test] fn v_sin_and_v_cos_f16_reduce_large_turns() { let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]); @@ -946,6 +1184,38 @@ fn v_sin_and_v_cos_f16_reduce_large_turns() { }); } +/// A 32-bit literal in a signed 64-bit operand is sign-extended (an +/// unsigned one's is zero-extended): -100 compared with `v[1:2]`, and +/// shifted by `s_ashr_i64`. +#[test] +fn signed_64_bit_operands_sign_extend_their_literal() { + const MINUS_100: u32 = -100_i32 as u32; + let check = |name: &str, body: &[u32], cases: &[([u32; 4], u32)]| { + let shader = build_valu_cs(body); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!(got, want, "{backend}: {name} {inp:x?}"); + }); + }; + // v_cmp_*_i64 s6, v[1:2], -100 (VOP3, literal src1), then + // v_cndmask_b32 v0, 0, 1, s6. + let compare = |op: u16| { + let [a, b] = vop3(op, 6, vgpr(1), 255, 0); + let [c, d] = vop3(0x101, 0, 0x80, 0x81, sgpr(6)); + [a, b, MINUS_100, c, d] + }; + // An i64 as the two input dwords of `v[1:2]`. + let pair = |n: i64| [n as u32, (n >> 32) as u32, 0, 0]; + let eq = [(pair(-100), 1), ([MINUS_100, 0, 0, 0], 0), (pair(0), 0)]; + check("v_cmp_eq_i64", &compare(0x0A2), &eq); + let lt = [(pair(-200), 1), (pair(-50), 0), (pair(0), 0)]; + check("v_cmp_lt_i64", &compare(0x0A1), <); + // s_ashr_i64 s[6:7], -100, 4; v_mov_b32 v0, s7: the high dword. + let ashr = [sop2(0x23, 6, 255, 0x84), MINUS_100, vop1(0x001, 0, sgpr(7))]; + check("s_ashr_i64", &ashr, &[([0; 4], u32::MAX)]); +} + #[test] fn bfe_signed_and_unsigned_match_rdna2() { // v_bfe_i32 v0, v1, v2, v3 (VOP3 opcode 0x149) diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 31dadd6..85e2b1a 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -115,9 +115,12 @@ pub(super) fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec .lock() .unwrap_or_else(|e| e.into_inner()); for (label, warp) in [("hardware", false), ("warp", true)] { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; + let host = match Host::new(warp) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 {label} device ({e}); skipped"); + continue; + } }; let (root, pso) = match host.compute_pipeline(shader) { Ok(p) => p, diff --git a/crates/victory-shader/src/gfx10/fields.rs b/crates/victory-shader/src/gfx10/fields.rs index 2773b3c..bcc0dd3 100644 --- a/crates/victory-shader/src/gfx10/fields.rs +++ b/crates/victory-shader/src/gfx10/fields.rs @@ -235,19 +235,32 @@ impl Instruction { } Encoding::Sopp => Fields::Sopp { imm: w0 as u16 }, Encoding::Smem => { - let data = match name { - "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None, - n if n.starts_with("s_dcache_discard") => None, - "s_memtime" | "s_memrealtime" => Some(2), - _ => Some(data_dwords(name)), + let sdata = (w0 >> 6 & 0x7F) as u8; + // s_atc_probe*: SDATA is a 7-bit immediate, not an SGPR. The + // buffer form's resource is 4 dwords. GLC and DLC are not operands. + let probe = matches!(name, "s_atc_probe" | "s_atc_probe_buffer"); + let data = if probe { + Some(Operand::Literal(u32::from(sdata))) + } else { + match name { + "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None, + n if n.starts_with("s_dcache_discard") => None, + "s_memtime" | "s_memrealtime" => Some(scalar(sdata, 2)), + _ => Some(scalar(sdata, data_dwords(name))), + } }; - let base = 2 + 2 * u8::from(name.starts_with("s_buffer_")); + let base = + 2 + 2 * u8::from(name.starts_with("s_buffer_") || name == "s_atc_probe_buffer"); Fields::Smem { - data: data.map(|d| scalar((w0 >> 6 & 0x7F) as u8, d)), + data, base: scalar(((w0 & 0x3F) << 1) as u8, base), offset: (w1 << 11) as i32 >> 11, soffset: scalar((w1 >> 25) as u8, 1), - cache: cache(bit(w0, 16), false, bit(w0, 14)), + cache: if probe { + Cache::default() + } else { + cache(bit(w0, 16), false, bit(w0, 14)) + }, } } Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc | Encoding::Vop3 | Encoding::Vop3p => { @@ -405,6 +418,8 @@ impl Instruction { saddr: (self.encoding != Encoding::Flat) .then(|| scalar(saddr, 1 + u8::from(self.encoding == Encoding::Global))), offset: match self.encoding { + // GFX10 FLAT offsets are 11-bit and unsigned: the + // hardware ignores bit 11. Encoding::Flat => (w0 & 0x7FF) as i16, _ => ((w0 << 4) as i16) >> 4, }, diff --git a/crates/victory-shader/src/gfx10/mod.rs b/crates/victory-shader/src/gfx10/mod.rs index f029ff4..57e6ea2 100644 --- a/crates/victory-shader/src/gfx10/mod.rs +++ b/crates/victory-shader/src/gfx10/mod.rs @@ -352,6 +352,21 @@ mod tests { .collect() } + #[test] + fn flat_offsets_ignore_bit_eleven() { + let offset = |word0: u32| { + let code = bytes(&[word0, 0x0000_0001, S_ENDPGM]); + match decode(&code).unwrap()[0].fields(false) { + Fields::Flat { offset, .. } => offset, + fields => panic!("{fields:?}"), + } + }; + // flat_load_dword v0, v[1:2]: the FLAT offset is 11-bit and + // unsigned, so bit 11 is ignored (0x800 -> 0, 0xfff -> 0x7ff). + assert_eq!(offset(0xDC30_0800), 0); + assert_eq!(offset(0xDC30_0FFF), 0x7FF); + } + #[test] fn tables_are_sorted() { for t in [ diff --git a/crates/victory-shader/src/gfx10/sp3.rs b/crates/victory-shader/src/gfx10/sp3.rs index 0ca5ab4..baf0e82 100644 --- a/crates/victory-shader/src/gfx10/sp3.rs +++ b/crates/victory-shader/src/gfx10/sp3.rs @@ -137,6 +137,12 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { cache, } => { if let Some(data) = data { + let data = match (name, data) { + ("s_atc_probe" | "s_atc_probe_buffer", Operand::Literal(imm)) => { + atc_immediate(*imm) + } + _ => data.to_string(), + }; let off = match (soffset, offset) { (Operand::Scalar { code: NULL, .. }, 0) => soffset.to_string(), (Operand::Scalar { code: NULL, .. }, _) => { @@ -335,6 +341,15 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { out } +/// `s_atc_probe` immediate: 0..=64 in decimal, larger values in hex. +fn atc_immediate(imm: u32) -> String { + if imm <= 64 { + imm.to_string() + } else { + format!("0x{imm:x}") + } +} + /// Cache flags; images write `dlc` first. fn flags(out: &mut String, cache: &Cache, dlc_first: bool) { let dlc = (cache.dlc, " dlc"); @@ -660,7 +675,7 @@ fn valu(name: &str, v: &Valu, encoding: Encoding) -> String { #[cfg(test)] mod tests { - use crate::gfx10::{Fields, Operand, decode}; + use crate::gfx10::{Cache, Fields, Operand, decode}; /// Text of each instruction in `words` (a straight-line program). fn texts(words: &[u32], wave64: bool) -> Vec { @@ -700,6 +715,69 @@ mod tests { ); } + /// `s_atc_probe` / `s_atc_probe_buffer`: SDATA is a 7-bit immediate, the + /// buffer resource is 4 dwords, and GLC/DLC are not operands. + /// + /// Words checked with `llvm-mc -arch=amdgcn -mcpu=gfx1030 --disassemble`. + /// The offset keeps this printer's 6-digit hex (`0x000064`, not `0x64`). + #[test] + fn atc_probe_immediate_is_not_a_register() { + let cases = [ + ( + [0xF498_01C2, 0xFA00_0064], + "s_atc_probe 7, s[4:5], 0x000064", + Operand::Literal(7), + Operand::Scalar { code: 4, dwords: 2 }, + ), + ( + [0xF498_1FF4, 0x0A00_0001], + "s_atc_probe 0x7f, s[104:105], s5 offset:0x000001", + Operand::Literal(0x7f), + Operand::Scalar { + code: 104, + dwords: 2, + }, + ), + ( + [0xF498_0000, 0xFA00_0000], + "s_atc_probe 0, s[0:1], null", + Operand::Literal(0), + Operand::Scalar { code: 0, dwords: 2 }, + ), + ( + [0xF49C_01C4, 0xFA00_0020], + "s_atc_probe_buffer 7, s[8:11], 0x000020", + Operand::Literal(7), + Operand::Scalar { code: 8, dwords: 4 }, + ), + ( + [0xF499_41C2, 0xFA00_0000], + "s_atc_probe 7, s[4:5], null", + Operand::Literal(7), + Operand::Scalar { code: 4, dwords: 2 }, + ), + ]; + for (words, text, data, base) in cases { + assert_eq!(one(&words, false), text, "{words:08x?}"); + assert_eq!(one(&words, true), text, "{words:08x?}"); + let mut code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + code.extend(0xBF81_0000u32.to_le_bytes()); + let inst = &decode(&code).unwrap()[0]; + let Fields::Smem { + data: got, + base: got_base, + cache, + .. + } = inst.fields(false) + else { + panic!("not an SMEM instruction"); + }; + assert_eq!(got, Some(data), "{words:08x?}"); + assert_eq!(got_base, base, "{words:08x?}"); + assert_eq!(cache, Cache::default(), "{words:08x?}"); + } + } + #[test] fn lane_masks_follow_the_wave_size() { let cmp = [0x7C08_06F0]; // v_cmp_gt_f32 with 0.5 and v3 diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index 3899cc9..ba53eb0 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -26,10 +26,10 @@ //! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and //! its group id from v5 of the first lane (`v_readfirstlane`: the group //! times the group size). Lane n exports vertex n (`exp pos`, `exp param`) -//! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20, -//! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One -//! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | -//! primitives << 12). +//! and primitive n (`exp prim`: 9-bit vertex indices at bits 0, 10, 20, +//! each with an edge flag above it, bit 31 culls); `param` entries with +//! bit 7 are per-primitive outputs. One lane sends the output counts +//! (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | primitives << 12). use crate::ShaderError; use crate::gfx10::{Fields, Operand}; diff --git a/docs/replay.md b/docs/replay.md index 42c0a61..54169e7 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -77,6 +77,30 @@ leaves out waits or work can draw another picture and, with wild data, lose the device: save work in other programs first. Do not run the title at the same time. +## What draws a pixel + + victory replay --pixel 1234,567 [--of 1280x720] [--lists 40..80] + +runs the frame once with copies of the texel under the point after every +command that can change it, and names each command that did with its pipeline +(id, name, DXIL hashes) and the values before and after: draws with their +targets (where the viewport has the picture's shape), dispatches and draws with +the textures of the picture's shape shaders may write at that time, copies, +resolves and clears. `--of` is the size of the picture the point was read from +(a screenshot's). The commands are numbered `:` as in +`--listing`, `--slots` and `--looks`. + +| switch | does | +|---|---| +| `--pixel [.]:,` | a texel of one texture instead (repeatable, both kinds) | +| `--depth` | depth targets too: the whole target is copied after each draw | +| `--targets-only` | no textures of unordered access: fewer copies | +| `--split :` | the draws of that indirect call one by one, each named | +| `--lists 40..80` | only these lists are looked into | + +A texture that was changed by what is not looked into is reported as "changed +unseen". Copies of 3D textures' targets are of the slice drawn to. + ## Runs that differ Shaders that give out places with atomics (the title's culling) give other